| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763 |
- 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"
- Purple = "\033[0;35m" // For elevated scripts
- NC = "\033[0m"
- )
- type Config struct {
- RunsDir string
- LogsDir string
- DryRun bool
- Verbose bool
- Interactive 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
- RequiresSudo bool // Whether script needs elevated privileges
- RequiresInteractive bool // Whether script needs interactive input
- }
- 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 sudoLog(msg string, args ...any) {
- fmt.Printf(Purple+"[SUDO]"+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
- }
- type ScriptMetadata struct {
- RequiresSudo bool
- RequiresInteractive bool
- }
- func getScriptMetadata(scriptPath string) (string, ScriptMetadata) {
- file, err := os.Open(scriptPath)
- if err != nil {
- return "No description", ScriptMetadata{}
- }
- defer file.Close()
- var desc string
- scriptMetadata := ScriptMetadata{}
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := strings.TrimSpace(scanner.Text())
- if strings.HasPrefix(line, "# NAME:") {
- desc = strings.TrimSpace(strings.TrimPrefix(line, "# NAME:"))
- }
- if strings.HasPrefix(line, "# REQUIRES:") {
- scriptMetadata.RequiresSudo = strings.Contains(line, "sudo")
- scriptMetadata.RequiresInteractive = strings.Contains(line, "interactive")
- }
- }
- if desc == "" {
- desc = "No description"
- }
- return desc, scriptMetadata
- }
- 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) {
- desc, metaData := getScriptMetadata(path)
- scripts = append(scripts, Script{
- Path: path,
- Name: scriptName,
- RelPath: relPath,
- Desc: desc,
- RequiresSudo: metaData.RequiresSudo,
- RequiresInteractive: metaData.RequiresInteractive,
- })
- }
- }
- 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")
- var cmd *exec.Cmd
- if script.RequiresSudo {
- sudoLog("Script requires elevated privileges: %s", script.RelPath)
- if !commandExists("sudo") {
- errorLog("sudo command not found - cannot run elevated script")
- return fmt.Errorf("sudo not available")
- }
- // Use -S to read password from stdin, and preserve environment
- fullArgs := append([]string{"-S", "-E", script.Path}, args...)
- cmd = exec.Command("sudo", fullArgs...)
- sudoLog("Running with sudo: %s", strings.Join(append([]string{script.Path}, args...), " "))
- } else {
- cmd = exec.Command(script.Path, args...)
- }
- if config.Interactive || script.RequiresInteractive {
- cmd.Stdin = os.Stdin
- }
- logFileHandle, err := os.Create(logFile)
- if err != nil {
- return err
- }
- defer logFileHandle.Close()
- showOutput := verbose || config.Interactive || script.RequiresInteractive
- if showOutput {
- cmd.Stdout = io.MultiWriter(os.Stdout, logFileHandle)
- cmd.Stderr = io.MultiWriter(os.Stderr, logFileHandle)
- } else {
- cmd.Stdout = logFileHandle
- cmd.Stderr = logFileHandle
- }
- return cmd.Run()
- }
- func createNewScript(scriptName string) error {
- scriptPath := filepath.Join(config.RunsDir, scriptName)
- dirPath := filepath.Dir(scriptPath)
- if err := os.MkdirAll(dirPath, 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
- # REQUIRES: sudo interactive
- set -euo pipefail
- # Source common functions
- source "$(dirname "$0")/../common.sh" || {
- echo "[ERROR] Could not source common.sh" >&2
- exit 1
- }
- check_requirements() {
- # Check required commands
- local required_commands=()
- # Add your required commands here
- # required_commands=(git curl wget)
- for cmd in "${required_commands[@]}"; do
- if ! command_exists "$cmd"; then
- log_error "Required command not found: $cmd"
- exit 1
- fi
- done
- }
- main() {
- init_script
- check_requirements
- # Your main script logic goes here
- # Example operations:
- # if ! confirm "Proceed with operation?"; then
- # log_info "Operation cancelled"
- # finish_script 0
- # fi
- # Add your implementation here
- finish_script 0
- }
- main "$@"
- `, strings.TrimSuffix(filepath.Base(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
- }
- sudoExampleScript := filepath.Join(config.RunsDir, "system-info.sh")
- sudoContent := `#!/usr/bin/env bash
- # NAME: System information collector
- # REQUIRES: sudo
- set -euo pipefail
- echo "Collecting system information (requires elevated privileges)..."
- echo "=== Disk Usage ==="
- df -h
- echo "=== Memory Info ==="
- free -h
- echo "=== System Logs (last 10 lines) ==="
- tail -n 10 /var/log/syslog 2>/dev/null || tail -n 10 /var/log/messages 2>/dev/null || echo "No accessible system logs"
- echo "✅ System info collection completed"
- `
- if err := os.WriteFile(sudoExampleScript, []byte(sudoContent), 0o755); err != nil {
- return err
- }
- log("✅ Created runs/ directory with example scripts")
- 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.
- Scripts marked with "# REQUIRES: sudo" will automatically run with elevated privileges.
- 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
- dev run system-info # Runs with sudo if marked as required`,
- 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 {
- if strings.HasPrefix(script.Name, toComplete) || strings.HasPrefix(script.RelPath, toComplete) {
- desc := script.Desc
- if script.RequiresSudo {
- desc = desc + " [SUDO]"
- }
- completions = append(completions, fmt.Sprintf("%s\t%s", script.RelPath, 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 {
- for i := runIndex + 1; i < dashDashIndex; i++ {
- arg := rawArgs[i]
- if !strings.HasPrefix(arg, "-") {
- filters = append(filters, arg)
- }
- }
- scriptArgs = rawArgs[dashDashIndex+1:]
- } else {
- 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 <name>' to create one")
- }
- return nil
- }
- for _, script := range scripts {
- if config.DryRun {
- argsStr := ""
- if len(scriptArgs) > 0 {
- argsStr = fmt.Sprintf(" with args: %s", strings.Join(scriptArgs, " "))
- }
- sudoStr := ""
- if script.RequiresSudo {
- sudoStr = " [SUDO]"
- }
- fmt.Printf("[DRY] Would run: %s - %s%s%s\n", script.RelPath, script.Desc, sudoStr, argsStr)
- continue
- }
- argsDisplay := ""
- if len(scriptArgs) > 0 {
- argsDisplay = fmt.Sprintf(" with args: %s", strings.Join(scriptArgs, " "))
- }
- sudoDisplay := ""
- if script.RequiresSudo {
- sudoDisplay = " [ELEVATED]"
- }
- fmt.Printf("Running: %s%s%s\n", script.RelPath, sudoDisplay, 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 {
- if script.RequiresSudo {
- sudoLog("✅ %s completed (elevated)", script.RelPath)
- } 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 <name>' to create a new script")
- return nil
- }
- fmt.Printf("Available scripts in %s:\n\n", config.RunsDir)
- for _, script := range scripts {
- if script.RequiresSudo {
- fmt.Printf(" %s%s%s - %s %s[SUDO]%s\n",
- Blue, script.RelPath, NC, script.Desc, Purple, NC)
- } else {
- fmt.Printf(" %s%s%s - %s\n",
- Blue, script.RelPath, NC, script.Desc)
- }
- }
- sudoCount := 0
- for _, script := range scripts {
- if script.RequiresSudo {
- sudoCount++
- }
- }
- fmt.Printf("\nTotal: %d scripts", len(scripts))
- if sudoCount > 0 {
- fmt.Printf(" (%d require elevated privileges)", sudoCount)
- }
- fmt.Println()
- return nil
- },
- }
- var newCmd = &cobra.Command{
- Use: "new <name>",
- 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")
- runCmd.Flags().BoolVarP(&config.Interactive, "interactive", "i", false, "Run script interactively (show output and allow input)")
- // 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)
- }
- }
|