| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677 |
- package main
- import (
- "bufio"
- "fmt"
- "io"
- "os"
- "os/exec"
- "path/filepath"
- "sort"
- "strings"
- "time"
- )
- // Colors for terminal output
- const (
- Red = "\033[0;31m"
- Green = "\033[0;32m"
- Blue = "\033[0;34m"
- Yellow = "\033[0;33m"
- NC = "\033[0m" // No Color
- )
- // Global configuration
- type Config struct {
- ScriptDir string
- EnvFile string
- RunsDir string
- LogsDir string
- DryRun bool
- Verbose bool
- Filters []string
- Command string
- }
- // Script represents an executable script
- type Script struct {
- Path string
- Name string
- Description string
- }
- // ExecutionResult tracks script execution outcomes
- type ExecutionResult struct {
- Executed []string
- Failed []string
- }
- // Logging functions
- func log(msg string, args ...interface{}) {
- fmt.Printf(Green+"[RUN]"+NC+" "+msg+"\n", args...)
- }
- func warn(msg string, args ...interface{}) {
- fmt.Printf(Yellow+"[WARN]"+NC+" "+msg+"\n", args...)
- }
- func errorLog(msg string, args ...interface{}) {
- fmt.Fprintf(os.Stderr, Red+"[ERROR]"+NC+" "+msg+"\n", args...)
- }
- // Check if command exists in PATH
- func commandExists(cmd string) bool {
- _, err := exec.LookPath(cmd)
- return err == nil
- }
- // Check for required and optional dependencies
- func checkDependencies() error {
- requiredTools := []string{"git", "find", "grep"}
- optionalTools := []string{"gitleaks"}
- var missing []string
- log("Checking dependencies...")
- // Check required tools
- for _, tool := range requiredTools {
- if !commandExists(tool) {
- missing = append(missing, tool)
- }
- }
- // Check optional tools
- for _, tool := range optionalTools {
- if !commandExists(tool) {
- warn("Optional tool missing: %s (recommended for security scanning)", tool)
- } else {
- log("✓ Found: %s", tool)
- }
- }
- // Report missing required tools
- if len(missing) > 0 {
- errorLog("Missing required tools: %s", strings.Join(missing, ", "))
- errorLog("Please install missing dependencies")
- return fmt.Errorf("missing dependencies")
- }
- log("✓ All required dependencies found")
- return nil
- }
- // Run security scan using gitleaks
- func runSecurityScan() error {
- log("Running security scan...")
- if !commandExists("gitleaks") {
- warn("GitLeaks not installed - skipping security scan")
- warn("Install with: paru -S gitleaks")
- fmt.Println()
- fmt.Print("Continue without security scan? (y/N): ")
- reader := bufio.NewReader(os.Stdin)
- answer, _ := reader.ReadString('\n')
- answer = strings.TrimSpace(strings.ToLower(answer))
- if answer != "y" && answer != "yes" {
- errorLog("Push cancelled for security")
- return fmt.Errorf("security scan cancelled")
- }
- return nil
- }
- log("Using GitLeaks for secret detection...")
- cmd := exec.Command("gitleaks", "detect", "--verbose", "--exit-code", "1")
- if err := cmd.Run(); err != nil {
- errorLog("❌ Secrets detected! Review before pushing.")
- return fmt.Errorf("secrets detected")
- }
- log("✅ No secrets detected")
- return nil
- }
- // Check if we're in a git repository
- func isGitRepo() bool {
- cmd := exec.Command("git", "rev-parse", "--git-dir")
- return cmd.Run() == nil
- }
- // Check for uncommitted changes
- func hasUncommittedChanges() bool {
- cmd := exec.Command("git", "diff-index", "--quiet", "HEAD", "--")
- return cmd.Run() != nil
- }
- // Get current git branch
- func getCurrentBranch() (string, error) {
- cmd := exec.Command("git", "branch", "--show-current")
- output, err := cmd.Output()
- if err != nil {
- return "", err
- }
- return strings.TrimSpace(string(output)), nil
- }
- // Handle git push workflow
- func handlePush() error {
- log("Preparing to push repository...")
- // Check if we're in a git repository
- if !isGitRepo() {
- errorLog("Not in a git repository")
- return fmt.Errorf("not in git repo")
- }
- // Check for uncommitted changes
- if hasUncommittedChanges() {
- warn("You have uncommitted changes")
- fmt.Println()
- // Show git status
- cmd := exec.Command("git", "status", "--short")
- cmd.Stdout = os.Stdout
- cmd.Run()
- fmt.Println()
- // Generate default commit message
- defaultMsg := fmt.Sprintf("dev: automated commit - %s", time.Now().Format("2006-01-02 15:04:05"))
- fmt.Print("Commit all changes? (Y/n): ")
- reader := bufio.NewReader(os.Stdin)
- answer, _ := reader.ReadString('\n')
- answer = strings.TrimSpace(strings.ToLower(answer))
- if answer != "n" && answer != "no" {
- fmt.Println()
- fmt.Printf("Default: %s\n", defaultMsg)
- fmt.Print("Custom commit message (or press Enter for default): ")
- commitMsg, _ := reader.ReadString('\n')
- commitMsg = strings.TrimSpace(commitMsg)
- if commitMsg == "" {
- commitMsg = defaultMsg
- }
- // Add and commit changes
- if err := exec.Command("git", "add", ".").Run(); err != nil {
- return fmt.Errorf("failed to add changes: %v", err)
- }
- if err := exec.Command("git", "commit", "-m", commitMsg).Run(); err != nil {
- return fmt.Errorf("failed to commit changes: %v", err)
- }
- log("✓ Changes committed: %s", commitMsg)
- }
- }
- // Run security scan
- if err := runSecurityScan(); err != nil {
- return err
- }
- // Get current branch
- branch, err := getCurrentBranch()
- if err != nil {
- return fmt.Errorf("failed to get current branch: %v", err)
- }
- // Push to origin
- log("Pushing branch '%s' to origin...", branch)
- cmd := exec.Command("git", "push", "origin", branch)
- if err := cmd.Run(); err != nil {
- errorLog("❌ Push failed")
- return fmt.Errorf("push failed")
- }
- log("✅ Successfully pushed to origin/%s", branch)
- return nil
- }
- // Show help message
- func showHelp(programName string) {
- fmt.Printf(`%s - Development script runner
- Usage: %s <command> [options] [arguments]
- COMMANDS:
- run [filters...] Run scripts matching filters (or all if no filters)
- push,u,ush Commit, scan for secrets, and push to git origin
- ls, list List all available scripts
- new <name> Create a new script template
- deps, check Check for required dependencies
- help Show this help message
- RUN OPTIONS:
- --dry Show what would run without executing
- --verbose Show detailed output during execution
- EXAMPLES:
- %s # Show this help
- %s run # Run all scripts (with confirmation)
- %s run docker # Run scripts containing 'docker'
- %s run --dry api # Show what API scripts would run
- %s ls # List all scripts
- %s new backup # Create a new script called 'backup.sh'
- %s push # Secure git push with secret scanning
- SECURITY:
- The push command automatically scans for secrets using GitLeaks
- before pushing to prevent accidental credential exposure.
- `, programName, programName, programName, programName, programName, programName, programName, programName, programName)
- }
- // Get script description from comment
- func getDescription(scriptPath string) string {
- file, err := os.Open(scriptPath)
- if err != nil {
- return "No description"
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := scanner.Text()
- if strings.HasPrefix(line, "# NAME:") {
- desc := strings.TrimSpace(strings.TrimPrefix(line, "# NAME:"))
- if desc != "" {
- return desc
- }
- }
- }
- return "No description"
- }
- // Check if script name matches any of the filters
- func matchesFilters(scriptName string, filters []string) bool {
- if len(filters) == 0 {
- return true
- }
- scriptNameLower := strings.ToLower(scriptName)
- for _, filter := range filters {
- filterLower := strings.ToLower(filter)
- if strings.Contains(scriptName, filter) || strings.Contains(scriptNameLower, filterLower) {
- return true
- }
- }
- return false
- }
- // Find executable scripts in runs directory
- func findScripts(runsDir string, filters []string) ([]Script, error) {
- var scripts []Script
- err := filepath.Walk(runsDir, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
- // Check if file is executable
- if info.Mode().IsRegular() && (info.Mode()&0o111) != 0 {
- scriptName := filepath.Base(path)
- if matchesFilters(scriptName, filters) {
- scripts = append(scripts, Script{
- Path: path,
- Name: scriptName,
- Description: getDescription(path),
- })
- }
- }
- return nil
- })
- if err != nil {
- return nil, err
- }
- // Sort scripts by name
- sort.Slice(scripts, func(i, j int) bool {
- return scripts[i].Name < scripts[j].Name
- })
- return scripts, nil
- }
- // List all available scripts
- func listScripts(runsDir string) error {
- scripts, err := findScripts(runsDir, nil)
- if err != nil {
- return err
- }
- if len(scripts) == 0 {
- warn("No executable scripts found in %s", runsDir)
- return nil
- }
- fmt.Printf(Blue + "Available scripts:" + NC + "\n")
- for _, script := range scripts {
- fmt.Printf(" %s%s%s - %s\n", Green, script.Name, NC, script.Description)
- }
- fmt.Printf("\nTotal: %d scripts\n", len(scripts))
- return nil
- }
- // Create a new script template
- func createNewScript(runsDir, scriptName string) error {
- if scriptName == "" {
- return fmt.Errorf("script name required")
- }
- // Ensure runs directory exists
- if err := os.MkdirAll(runsDir, 0o755); err != nil {
- return err
- }
- // Add .sh extension if not provided
- if !strings.HasSuffix(scriptName, ".sh") {
- scriptName += ".sh"
- }
- scriptPath := filepath.Join(runsDir, scriptName)
- // Check if script already exists
- if _, err := os.Stat(scriptPath); err == nil {
- return fmt.Errorf("script %s already exists", scriptName)
- }
- // Create script template
- template := fmt.Sprintf(`#!/usr/bin/env bash
- # NAME: %s script
- set -euo pipefail
- # Add your script logic here
- echo "Running %s script..."
- # Example:
- # - Add your commands below
- # - Use proper error handling
- # - Add logging as needed
- echo "✅ %s completed successfully"
- `, strings.TrimSuffix(scriptName, ".sh"), scriptName, strings.TrimSuffix(scriptName, ".sh"))
- if err := os.WriteFile(scriptPath, []byte(template), 0o755); err != nil {
- return err
- }
- log("✅ Created new script: %s", scriptPath)
- log("Edit the script to add your commands")
- return nil
- }
- // Execute a single script
- func executeScript(script Script, logsDir string, verbose bool) error {
- logFile := filepath.Join(logsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log")
- cmd := exec.Command(script.Path)
- if verbose {
- // Create log file
- logFileHandle, err := os.Create(logFile)
- if err != nil {
- return err
- }
- defer logFileHandle.Close()
- // Use MultiWriter to write to both stdout and log file
- cmd.Stdout = io.MultiWriter(os.Stdout, logFileHandle)
- cmd.Stderr = io.MultiWriter(os.Stderr, logFileHandle)
- return cmd.Run()
- } else {
- // Only write to log file
- logFileHandle, err := os.Create(logFile)
- if err != nil {
- return err
- }
- defer logFileHandle.Close()
- cmd.Stdout = logFileHandle
- cmd.Stderr = logFileHandle
- return cmd.Run()
- }
- }
- // Parse command line arguments
- func parseArgs(args []string) (*Config, error) {
- config := &Config{}
- // Get current working directory (equivalent to bash SCRIPT_DIR)
- scriptDir, err := os.Getwd()
- if err != nil {
- return nil, err
- }
- config.ScriptDir = scriptDir
- config.EnvFile = filepath.Join(config.ScriptDir, ".env")
- config.RunsDir = filepath.Join(config.ScriptDir, "runs")
- config.LogsDir = filepath.Join(config.ScriptDir, "logs")
- if len(args) == 0 {
- return config, fmt.Errorf("help")
- }
- i := 0
- // First argument should be the command
- if i < len(args) {
- arg := args[i]
- switch arg {
- case "--help", "help":
- return config, fmt.Errorf("help")
- case "run":
- config.Command = "run"
- i++
- case "push", "u", "ush":
- config.Command = "push"
- i++
- case "ls", "list":
- config.Command = "list"
- i++
- case "new":
- config.Command = "new"
- i++
- case "deps", "check":
- config.Command = "deps"
- i++
- default:
- return nil, fmt.Errorf("unknown command: %s", arg)
- }
- }
- // Parse remaining arguments based on command
- for i < len(args) {
- arg := args[i]
- switch arg {
- case "--dry":
- config.DryRun = true
- case "--verbose":
- config.Verbose = true
- default:
- if strings.HasPrefix(arg, "-") {
- return nil, fmt.Errorf("unknown option: %s", arg)
- }
- config.Filters = append(config.Filters, arg)
- }
- i++
- }
- return config, nil
- }
- // Confirm execution of all scripts
- func confirmExecution(scripts []Script) bool {
- fmt.Printf(Red + "⚠️ About to run ALL scripts:" + NC + "\n")
- for _, script := range scripts {
- fmt.Printf(" • %s - %s\n", script.Name, script.Description)
- }
- fmt.Println()
- fmt.Print("Continue? (y/N): ")
- reader := bufio.NewReader(os.Stdin)
- answer, _ := reader.ReadString('\n')
- answer = strings.TrimSpace(strings.ToLower(answer))
- return answer == "y" || answer == "yes"
- }
- func main() {
- const programName = "dev"
- // Parse arguments
- config, err := parseArgs(os.Args[1:])
- if err != nil {
- if err.Error() == "help" {
- showHelp(programName)
- os.Exit(0)
- }
- errorLog("Error: %v", err)
- fmt.Println()
- showHelp(programName)
- os.Exit(1)
- }
- // Handle special commands
- switch config.Command {
- case "push":
- if err := handlePush(); err != nil {
- os.Exit(1)
- }
- os.Exit(0)
- case "deps":
- if err := checkDependencies(); err != nil {
- os.Exit(1)
- }
- os.Exit(0)
- case "list":
- if err := listScripts(config.RunsDir); err != nil {
- errorLog("Error listing scripts: %v", err)
- os.Exit(1)
- }
- os.Exit(0)
- case "new":
- if len(config.Filters) == 0 {
- errorLog("Script name required for 'new' command")
- fmt.Printf("Usage: %s new <script-name>\n", programName)
- os.Exit(1)
- }
- scriptName := config.Filters[0]
- if err := createNewScript(config.RunsDir, scriptName); err != nil {
- errorLog("Error creating script: %v", err)
- os.Exit(1)
- }
- os.Exit(0)
- case "run":
- // Continue with script execution logic below
- case "":
- // No command provided, show help
- showHelp(programName)
- os.Exit(0)
- default:
- errorLog("Unknown command: %s", config.Command)
- showHelp(programName)
- os.Exit(1)
- }
- // Initialize runs directory if it doesn't exist (only for run command)
- if _, err := os.Stat(config.RunsDir); os.IsNotExist(err) {
- log("Creating runs directory at: %s", config.RunsDir)
- if err := os.MkdirAll(config.RunsDir, 0o755); err != nil {
- errorLog("Failed to create runs directory: %v", err)
- os.Exit(1)
- }
- // Create example script
- exampleScript := filepath.Join(config.RunsDir, "example.sh")
- content := `#!/usr/bin/env bash
- # NAME: Example script
- echo "Hello from runs/example.sh!"
- echo "Edit this script or add your own to runs/"
- `
- if err := os.WriteFile(exampleScript, []byte(content), 0o755); err != nil {
- errorLog("Failed to create example script: %v", err)
- os.Exit(1)
- }
- log("✅ Created runs/ directory with example script")
- log("Use '%s ls' to list scripts or '%s new <name>' to create a new one", programName, programName)
- os.Exit(0)
- }
- // Create logs directory
- if err := os.MkdirAll(config.LogsDir, 0o755); err != nil {
- errorLog("Failed to create logs directory: %v", err)
- os.Exit(1)
- }
- // Find scripts to run
- scripts, err := findScripts(config.RunsDir, config.Filters)
- if err != nil {
- errorLog("Error finding scripts: %v", err)
- os.Exit(1)
- }
- if len(scripts) == 0 {
- if len(config.Filters) > 0 {
- warn("No scripts match the given filters: %s", strings.Join(config.Filters, ", "))
- fmt.Printf("Use '%s ls' to see all available scripts\n", programName)
- } else {
- warn("No executable scripts found in %s", config.RunsDir)
- fmt.Printf("Use '%s new <name>' to create a new script\n", programName)
- }
- os.Exit(0)
- }
- // Confirm execution if running all scripts without dry run
- if len(config.Filters) == 0 && !config.DryRun {
- if !confirmExecution(scripts) {
- fmt.Println("Cancelled")
- os.Exit(0)
- }
- }
- // Execute scripts
- result := ExecutionResult{}
- for _, script := range scripts {
- if config.DryRun {
- fmt.Printf(Blue+"[DRY]"+NC+" Would run: %s - %s\n", script.Name, script.Description)
- continue
- }
- fmt.Printf("\n"+Blue+"▶"+NC+" Running: %s\n", script.Name)
- if script.Description != "No description" {
- fmt.Printf(" %s\n", script.Description)
- }
- if err := executeScript(script, config.LogsDir, config.Verbose); err != nil {
- errorLog("❌ %s failed (see %s)", script.Name,
- filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log"))
- result.Failed = append(result.Failed, script.Name)
- } else {
- log("✅ %s completed", script.Name)
- result.Executed = append(result.Executed, script.Name)
- }
- }
- // Print summary
- if !config.DryRun {
- fmt.Printf("\n" + Blue + "═══ SUMMARY ═══" + NC + "\n")
- fmt.Printf("✅ Completed: %d\n", len(result.Executed))
- if len(result.Failed) > 0 {
- fmt.Printf("❌ Failed: %d\n", len(result.Failed))
- fmt.Printf("\n" + Red + "Failed scripts:" + NC + "\n")
- for _, failed := range result.Failed {
- fmt.Printf(" • %s\n", failed)
- }
- os.Exit(1)
- }
- }
- }
|