fix error when executing multiple files

This commit is contained in:
Leons Aleksandrovs
2025-08-11 19:06:37 +03:00
parent 2cb4b05d4b
commit 1f420d698e

19
main.go
View File

@@ -44,11 +44,20 @@ func main() {
files = append(files, targetPath) files = append(files, targetPath)
} }
currentDir, _ := os.Getwd() originalDir, _ := os.Getwd()
currentDir := originalDir
for _, file := range files { for _, file := range files {
// Change to the original directory before executing each file
if err := os.Chdir(originalDir); err != nil {
fmt.Println("Error changing to original directory:", err)
os.Exit(1)
}
currentDir = originalDir
fmt.Println("=== Executing file:", file, "===") fmt.Println("=== Executing file:", file, "===")
if err := runCommandsFromFile(file, &currentDir); err != nil { if err := runCommandsFromFile(file, &currentDir); err != nil {
fmt.Println("Error:", err)
os.Exit(1) os.Exit(1)
} }
} }
@@ -58,7 +67,7 @@ func runCommandsFromFile(filename string, currentDir *string) error {
// Try to open the file // Try to open the file
f, err := os.Open(filename) f, err := os.Open(filename)
if err != nil { if err != nil {
return fmt.Errorf("Error opening file: %w", err) return fmt.Errorf("error opening file: %w", err)
} }
defer f.Close() defer f.Close()
@@ -83,7 +92,7 @@ func runCommandsFromFile(filename string, currentDir *string) error {
} }
if err := os.Chdir(newDir); err != nil { if err := os.Chdir(newDir); err != nil {
return fmt.Errorf("Failed to change directory: %w", err) return fmt.Errorf("failed to change directory: %w", err)
} }
*currentDir, _ = os.Getwd() *currentDir, _ = os.Getwd()
fmt.Println("Changed directory to:", *currentDir) fmt.Println("Changed directory to:", *currentDir)
@@ -98,13 +107,13 @@ func runCommandsFromFile(filename string, currentDir *string) error {
cmd.Dir = *currentDir cmd.Dir = *currentDir
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
fmt.Println("Error detected! Stopping at:", cmdLine) fmt.Printf("Error detected! Stopping at:%s \n", cmdLine)
return err return err
} }
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
return fmt.Errorf("Error reading file: %w", err) return fmt.Errorf("error reading file: %w", err)
} }
return nil return nil
} }