MVP version working

This commit is contained in:
Leons Aleksandrovs
2025-08-10 20:57:34 +03:00
parent 5d02f55e84
commit 04a5a27cfe
2 changed files with 108 additions and 0 deletions

3
.gitignore vendored
View File

@@ -25,3 +25,6 @@ go.work.sum
# env file
.env
# Dev scripts
*.txt
*.sh

105
main.go Normal file
View File

@@ -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 <file-or-directory>")
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, &currentDir); 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
}