package main import ( "bufio" "fmt" "os" "os/exec" "path/filepath" "sort" "strings" ) func main() { // Check for arguments if len(os.Args) < 2 { fmt.Println("Usage: runner ") os.Exit(1) } // Select first argument, and check if it's a file or directory targetPath := os.Args[1] info, err := os.Stat(targetPath) if err != nil { fmt.Println("Error:", err) os.Exit(1) } var files []string if info.IsDir() { // Collect all .sh files from directory entries, err := os.ReadDir(targetPath) if err != nil { fmt.Println("Error reading directory:", err) os.Exit(1) } for _, e := range entries { if !e.IsDir() && strings.HasSuffix(e.Name(), ".sh") { files = append(files, filepath.Join(targetPath, e.Name())) } } sort.Strings(files) } else { files = append(files, targetPath) } originalDir, _ := os.Getwd() currentDir := originalDir 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, "===") if err := runCommandsFromFile(file, ¤tDir); err != nil { fmt.Println("Error:", err) os.Exit(1) } } } func runCommandsFromFile(filename string, currentDir *string) error { // Try to open the file f, err := os.Open(filename) if err != nil { return fmt.Errorf("error opening file: %w", err) } defer f.Close() // Create a scanner to read the file line by line scanner := bufio.NewScanner(f) for scanner.Scan() { cmdLine := strings.TrimSpace(scanner.Text()) if cmdLine == "" || strings.HasPrefix(cmdLine, "#") { continue } // Handle cd command if strings.HasPrefix(cmdLine, "cd ") { newDir := strings.TrimSpace(strings.TrimPrefix(cmdLine, "cd ")) if strings.HasPrefix(newDir, "~") { home, _ := os.UserHomeDir() newDir = filepath.Join(home, strings.TrimPrefix(newDir, "~")) } if !filepath.IsAbs(newDir) { newDir = filepath.Join(*currentDir, newDir) } if err := os.Chdir(newDir); err != nil { return fmt.Errorf("failed to change directory: %w", err) } *currentDir, _ = os.Getwd() fmt.Println("Changed directory to:", *currentDir) continue } // Execute the command fmt.Println(">>> Executing:", cmdLine) cmd := exec.Command("bash", "-c", cmdLine) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = *currentDir if err := cmd.Run(); err != nil { fmt.Printf("Error detected! Stopping at: %s \n", cmdLine) return err } } if err := scanner.Err(); err != nil { return fmt.Errorf("error reading file: %w", err) } return nil }