diff --git a/.gitignore b/.gitignore index 5b90e79..ad15ff9 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ go.work.sum # env file .env +# Dev scripts +*.txt +*.sh diff --git a/main.go b/main.go new file mode 100644 index 0000000..a4df867 --- /dev/null +++ b/main.go @@ -0,0 +1,105 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" +) + +func main() { + if len(os.Args) < 2 { + fmt.Println("Usage: runner ") + os.Exit(1) + } + + 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) + } + + currentDir, _ := os.Getwd() + + for _, file := range files { + fmt.Println("=== Executing file:", file, "===") + if err := runCommandsFromFile(file, ¤tDir); err != nil { + os.Exit(1) + } + } +} + +func runCommandsFromFile(filename string, currentDir *string) error { + f, err := os.Open(filename) + if err != nil { + return fmt.Errorf("Error opening file: %w", err) + } + defer f.Close() + + 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 + } + + 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.Println("Error detected! Stopping at:", cmdLine) + return err + } + } + + if err := scanner.Err(); err != nil { + return fmt.Errorf("Error reading file: %w", err) + } + return nil +}