package main import ( "bufio" "fmt" "io" "os" "os/exec" "path/filepath" "sort" "strings" "time" "github.com/spf13/cobra" ) const ( Red = "\033[0;31m" Green = "\033[0;32m" Blue = "\033[0;34m" Yellow = "\033[0;33m" NC = "\033[0m" ) type Config struct { RunsDir string LogsDir string DryRun bool Verbose bool } type Script struct { Path string // Full filesystem path Name string // Just filename (e.g. "install.sh") RelPath string // Relative path from runs/ (e.g. "tools/install.sh") Desc string // Description from script comment } var config Config func log(msg string, args ...any) { fmt.Printf(Green+"[RUN]"+NC+" "+msg+"\n", args...) } func warn(msg string, args ...any) { fmt.Printf(Yellow+"[WARN]"+NC+" "+msg+"\n", args...) } func errorLog(msg string, args ...any) { fmt.Fprintf(os.Stderr, Red+"[ERROR]"+NC+" "+msg+"\n", args...) } func commandExists(cmd string) bool { _, err := exec.LookPath(cmd) return err == nil } func checkDependencies() error { requiredTools := []string{"git", "find", "grep"} optionalTools := []string{"gitleaks"} var missing []string log("Checking dependencies...") for _, tool := range requiredTools { if !commandExists(tool) { missing = append(missing, tool) } } for _, tool := range optionalTools { if !commandExists(tool) { warn("Optional tool missing: %s (recommended for security scanning)", tool) } else { log("✓ Found: %s", tool) } } 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 } 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 } func isGitRepo() bool { cmd := exec.Command("git", "rev-parse", "--git-dir") return cmd.Run() == nil } func hasUncommittedChanges() bool { cmd := exec.Command("git", "diff-index", "--quiet", "HEAD", "--") return cmd.Run() != nil } 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 } func handlePush() error { log("Preparing to push repository...") if !isGitRepo() { errorLog("Not in a git repository") return fmt.Errorf("not in git repo") } if hasUncommittedChanges() { warn("You have uncommitted changes") fmt.Println() cmd := exec.Command("git", "status", "--short") cmd.Stdout = os.Stdout cmd.Run() fmt.Println() 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 } 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) } } if err := runSecurityScan(); err != nil { return err } branch, err := getCurrentBranch() if err != nil { return fmt.Errorf("failed to get current branch: %v", err) } 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 } 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" } func findScripts(filters []string) ([]Script, error) { var scripts []Script err := filepath.Walk(config.RunsDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.Mode().IsRegular() && (info.Mode()&0o111) != 0 { // Get relative path from runs directory relPath, err := filepath.Rel(config.RunsDir, path) if err != nil { return err } // Skip hidden files and directories if strings.HasPrefix(filepath.Base(path), ".") { return nil } scriptName := filepath.Base(path) if len(filters) == 0 || matchesFilters(relPath, scriptName, filters) { scripts = append(scripts, Script{ Path: path, Name: scriptName, RelPath: relPath, Desc: getDescription(path), }) } } return nil }) sort.Slice(scripts, func(i, j int) bool { return scripts[i].RelPath < scripts[j].RelPath }) return scripts, err } func matchesFilters(relPath, scriptName string, filters []string) bool { for _, filter := range filters { // Normalize paths for comparison (remove .sh extension from filter if present) normalizedFilter := strings.TrimSuffix(filter, ".sh") normalizedRelPath := strings.TrimSuffix(relPath, ".sh") normalizedScriptName := strings.TrimSuffix(scriptName, ".sh") // Check exact matches if normalizedRelPath == normalizedFilter || normalizedScriptName == normalizedFilter { return true } // Check if filter matches the relative path or script name (case insensitive) filterLower := strings.ToLower(normalizedFilter) relPathLower := strings.ToLower(normalizedRelPath) scriptNameLower := strings.ToLower(normalizedScriptName) if strings.Contains(relPathLower, filterLower) || strings.Contains(scriptNameLower, filterLower) { return true } // Check directory match (e.g., "tools" matches "tools/install.sh") if strings.HasPrefix(relPathLower, filterLower+"/") { return true } } return false } func executeScript(script Script, args []string, verbose bool) error { logFile := filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log") // Create command with script path and arguments cmd := exec.Command(script.Path, args...) if verbose { logFileHandle, err := os.Create(logFile) if err != nil { return err } defer logFileHandle.Close() cmd.Stdout = io.MultiWriter(os.Stdout, logFileHandle) cmd.Stderr = io.MultiWriter(os.Stderr, logFileHandle) return cmd.Run() } else { logFileHandle, err := os.Create(logFile) if err != nil { return err } defer logFileHandle.Close() cmd.Stdout = logFileHandle cmd.Stderr = logFileHandle return cmd.Run() } } func createNewScript(scriptName string) error { if err := os.MkdirAll(config.RunsDir, 0o755); err != nil { return err } if !strings.HasSuffix(scriptName, ".sh") { scriptName += ".sh" } scriptPath := filepath.Join(config.RunsDir, scriptName) if _, err := os.Stat(scriptPath); err == nil { return fmt.Errorf("script %s already exists", scriptName) } template := fmt.Sprintf(`#!/usr/bin/env bash # NAME: %s script set -euo pipefail echo "Running %s script..." # Add your commands here echo "✅ %s completed successfully" `, strings.TrimSuffix(scriptName, ".sh"), scriptName, strings.TrimSuffix(scriptName, ".sh")) err := os.WriteFile(scriptPath, []byte(template), 0o755) if err != nil { return err } log("✅ Created script: %s", scriptPath) return nil } func initConfig() { wd, _ := os.Getwd() config.RunsDir = filepath.Join(wd, "runs") config.LogsDir = filepath.Join(wd, "logs") } func ensureRunsDir() error { 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 { return err } 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 { return err } log("✅ Created runs/ directory with example script") return nil } return nil } var rootCmd = &cobra.Command{ Use: "dev", Short: "Development script runner", Long: "A CLI tool for managing and running development scripts", RunE: func(cmd *cobra.Command, args []string) error { // Default behavior: list scripts if no subcommand return listCmd.RunE(cmd, args) }, } var runCmd = &cobra.Command{ Use: "run [filters...] [-- script-args...]", Short: "Run scripts matching filters (or all if no filters)", Long: `Run scripts matching filters. Use -- to pass arguments to scripts. Examples: dev run tools/dev.sh # Run specific script dev run tools/dev.sh -- arg1 arg2 # Run with arguments dev run --verbose install -- --force # Run with flags`, ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { scripts, err := findScripts(nil) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } var completions []string for _, script := range scripts { // Add both the script name and relative path as completion options if strings.HasPrefix(script.Name, toComplete) || strings.HasPrefix(script.RelPath, toComplete) { // Use relative path as the completion value with description completions = append(completions, fmt.Sprintf("%s\t%s", script.RelPath, script.Desc)) } } return completions, cobra.ShellCompDirectiveNoFileComp }, RunE: func(cmd *cobra.Command, args []string) error { // Parse arguments manually to handle -- separator var filters []string var scriptArgs []string // Find "run" command position and -- separator in raw args rawArgs := os.Args[1:] // Skip program name runIndex := -1 dashDashIndex := -1 for i, arg := range rawArgs { if arg == "run" { runIndex = i } if arg == "--" && runIndex >= 0 { dashDashIndex = i break } } if dashDashIndex >= 0 { // Extract everything between "run" and "--" as filters (skip flags) for i := runIndex + 1; i < dashDashIndex; i++ { arg := rawArgs[i] // Skip flags if !strings.HasPrefix(arg, "-") { filters = append(filters, arg) } } // Everything after "--" are script args scriptArgs = rawArgs[dashDashIndex+1:] } else { // No --, use cobra's args as filters filters = args scriptArgs = []string{} } if err := ensureRunsDir(); err != nil { return err } if err := os.MkdirAll(config.LogsDir, 0o755); err != nil { return err } scripts, err := findScripts(filters) if err != nil { return err } if len(scripts) == 0 { if len(filters) > 0 { warn("No scripts match filters: %s", strings.Join(filters, ", ")) } else { warn("No scripts found. Use 'dev new ' to create one") } return nil } // CLI execution for _, script := range scripts { if config.DryRun { argsStr := "" if len(scriptArgs) > 0 { argsStr = fmt.Sprintf(" with args: %s", strings.Join(scriptArgs, " ")) } fmt.Printf("[DRY] Would run: %s - %s%s\n", script.RelPath, script.Desc, argsStr) continue } argsDisplay := "" if len(scriptArgs) > 0 { argsDisplay = fmt.Sprintf(" with args: %s", strings.Join(scriptArgs, " ")) } fmt.Printf("Running: %s%s\n", script.RelPath, argsDisplay) if err := executeScript(script, scriptArgs, config.Verbose); err != nil { errorLog("❌ %s failed", script.RelPath) if !config.Verbose { fmt.Printf(" Check log: %s\n", filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log")) } } else { log("✅ %s completed", script.RelPath) } } return nil }, } var listCmd = &cobra.Command{ Use: "ls", Aliases: []string{"list"}, Short: "List all available scripts", RunE: func(cmd *cobra.Command, args []string) error { if err := ensureRunsDir(); err != nil { return err } scripts, err := findScripts(nil) if err != nil { return err } if len(scripts) == 0 { warn("No scripts found in %s", config.RunsDir) fmt.Println("Use 'dev new ' to create a new script") return nil } fmt.Printf("Available scripts in %s:\n\n", config.RunsDir) for _, script := range scripts { fmt.Printf(" %s%s%s - %s\n", Blue, script.RelPath, NC, script.Desc) } fmt.Printf("\nTotal: %d scripts\n", len(scripts)) return nil }, } var newCmd = &cobra.Command{ Use: "new ", Short: "Create a new script template", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { return createNewScript(args[0]) }, } var pushCmd = &cobra.Command{ Use: "push", Aliases: []string{"u", "ush"}, Short: "Commit, scan for secrets, and push to git origin", RunE: func(cmd *cobra.Command, args []string) error { return handlePush() }, } var depsCmd = &cobra.Command{ Use: "deps", Short: "Install dependencies", RunE: func(cmd *cobra.Command, args []string) error { return checkDependencies() }, } var completionCmd = &cobra.Command{ Use: "completion [bash|zsh|fish|powershell]", Short: "Generate completion script", Long: `To load completions: Bash: $ source <(dev completion bash) # To load completions for each session, execute once: # Linux: $ dev completion bash > /etc/bash_completion.d/dev # macOS: $ dev completion bash > $(brew --prefix)/etc/bash_completion.d/dev Zsh: # If shell completion is not already enabled in your environment, # you will need to enable it. You can execute the following once: $ echo "autoload -U compinit; compinit" >> ~/.zshrc # To load completions for each session, execute once: $ dev completion zsh > "${fpath[1]}/_dev" # You will need to start a new shell for this setup to take effect. `, DisableFlagsInUseLine: true, ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), RunE: func(cmd *cobra.Command, args []string) error { switch args[0] { case "bash": return rootCmd.GenBashCompletion(os.Stdout) case "zsh": return rootCmd.GenZshCompletion(os.Stdout) case "fish": return rootCmd.GenFishCompletion(os.Stdout, true) case "powershell": return rootCmd.GenPowerShellCompletionWithDesc(os.Stdout) } return nil }, } func main() { initConfig() runCmd.Flags().BoolVar(&config.DryRun, "dry", false, "Show what would run without executing") runCmd.Flags().BoolVarP(&config.Verbose, "verbose", "v", false, "Show script output in terminal") // This prevents Cobra from consuming -- and everything after it runCmd.Flags().SetInterspersed(false) rootCmd.AddCommand(runCmd, listCmd, newCmd, pushCmd, depsCmd, completionCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } }