111 lines
2.4 KiB
Go
111 lines
2.4 KiB
Go
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 <file-or-directory>")
|
|
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)
|
|
}
|
|
|
|
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 {
|
|
// 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.Println("Error detected! Stopping at:", cmdLine)
|
|
return err
|
|
}
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
return fmt.Errorf("Error reading file: %w", err)
|
|
}
|
|
return nil
|
|
}
|