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 Name string Description string } 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 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 } 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 { 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.Slice(scripts, func(i, j int) bool { return scripts[i].Name < scripts[j].Name }) return scripts, nil } func executeScript(script Script, verbose bool) error { logFile := filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log") cmd := exec.Command(script.Path) 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 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 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") log("Use 'dev ls' to list scripts or 'dev new ' to create a new one") return nil } return nil } var rootCmd = &cobra.Command{ Use: "dev", Short: "Development script runner", Long: "A simple tool to manage and run development scripts with security scanning", } var runCmd = &cobra.Command{ Use: "run [filters...]", Short: "Run scripts matching filters (or all if no filters)", 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 { scriptName := strings.TrimSuffix(script.Name, ".sh") if strings.HasPrefix(scriptName, toComplete) { completions = append(completions, scriptName+"\t"+script.Description) } } return completions, cobra.ShellCompDirectiveNoFileComp }, RunE: func(cmd *cobra.Command, args []string) error { if err := ensureRunsDir(); err != nil { return err } if err := os.MkdirAll(config.LogsDir, 0o755); err != nil { return err } scripts, err := findScripts(args) if err != nil { return err } if len(scripts) == 0 { if len(args) > 0 { warn("No scripts match the given filters: %s", strings.Join(args, ", ")) fmt.Println("Use 'dev ls' to see all available scripts") } else { warn("No executable scripts found in %s", config.RunsDir) fmt.Println("Use 'dev new ' to create a new script") } return nil } if len(args) == 0 && !config.DryRun { if !confirmExecution(scripts) { fmt.Println("Cancelled") return nil } } var executed, failed []string 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.Verbose); err != nil { errorLog("❌ %s failed (see %s)", script.Name, filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log")) failed = append(failed, script.Name) } else { log("✅ %s completed", script.Name) executed = append(executed, script.Name) } } if !config.DryRun { fmt.Printf("\n" + Blue + "═══ SUMMARY ═══" + NC + "\n") fmt.Printf("✅ Completed: %d\n", len(executed)) if len(failed) > 0 { fmt.Printf("❌ Failed: %d\n", len(failed)) fmt.Printf("\n" + Red + "Failed scripts:" + NC + "\n") for _, f := range failed { fmt.Printf(" • %s\n", f) } return fmt.Errorf("some scripts failed") } } return nil }, } 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 listCmd = &cobra.Command{ Use: "ls", Aliases: []string{"list"}, Short: "List all available scripts", RunE: func(cmd *cobra.Command, args []string) error { scripts, err := findScripts(nil) if err != nil { return err } if len(scripts) == 0 { warn("No executable scripts found in %s", config.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 }, } var newCmd = &cobra.Command{ Use: "new ", Short: "Create a new script template", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { scriptName := args[0] 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")) 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 }, } 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. Fish: $ dev completion fish | source # To load completions for each session, execute once: $ dev completion fish > ~/.config/fish/completions/dev.fish PowerShell: PS> dev completion powershell | Out-String | Invoke-Expression # To load completions for every new session, run: PS> dev completion powershell > dev.ps1 # and source this file from your PowerShell profile. `, 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 }, } var depsCmd = &cobra.Command{ Use: "deps", Aliases: []string{"check"}, Short: "Check for required dependencies", RunE: func(cmd *cobra.Command, args []string) error { return checkDependencies() }, } 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 detailed output during execution") rootCmd.AddCommand(runCmd, pushCmd, listCmd, newCmd, depsCmd, completionCmd) if err := rootCmd.Execute(); err != nil { os.Exit(1) } }