main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "sort"
  10. "strings"
  11. "time"
  12. )
  13. // Colors for terminal output
  14. const (
  15. Red = "\033[0;31m"
  16. Green = "\033[0;32m"
  17. Blue = "\033[0;34m"
  18. Yellow = "\033[0;33m"
  19. NC = "\033[0m" // No Color
  20. )
  21. // Global configuration
  22. type Config struct {
  23. ScriptDir string
  24. EnvFile string
  25. RunsDir string
  26. LogsDir string
  27. DryRun bool
  28. Verbose bool
  29. Filters []string
  30. Command string
  31. }
  32. // Script represents an executable script
  33. type Script struct {
  34. Path string
  35. Name string
  36. Description string
  37. }
  38. // ExecutionResult tracks script execution outcomes
  39. type ExecutionResult struct {
  40. Executed []string
  41. Failed []string
  42. }
  43. // Logging functions
  44. func log(msg string, args ...interface{}) {
  45. fmt.Printf(Green+"[RUN]"+NC+" "+msg+"\n", args...)
  46. }
  47. func warn(msg string, args ...interface{}) {
  48. fmt.Printf(Yellow+"[WARN]"+NC+" "+msg+"\n", args...)
  49. }
  50. func errorLog(msg string, args ...interface{}) {
  51. fmt.Fprintf(os.Stderr, Red+"[ERROR]"+NC+" "+msg+"\n", args...)
  52. }
  53. // Check if command exists in PATH
  54. func commandExists(cmd string) bool {
  55. _, err := exec.LookPath(cmd)
  56. return err == nil
  57. }
  58. // Check for required and optional dependencies
  59. func checkDependencies() error {
  60. requiredTools := []string{"git", "find", "grep"}
  61. optionalTools := []string{"gitleaks"}
  62. var missing []string
  63. log("Checking dependencies...")
  64. // Check required tools
  65. for _, tool := range requiredTools {
  66. if !commandExists(tool) {
  67. missing = append(missing, tool)
  68. }
  69. }
  70. // Check optional tools
  71. for _, tool := range optionalTools {
  72. if !commandExists(tool) {
  73. warn("Optional tool missing: %s (recommended for security scanning)", tool)
  74. } else {
  75. log("✓ Found: %s", tool)
  76. }
  77. }
  78. // Report missing required tools
  79. if len(missing) > 0 {
  80. errorLog("Missing required tools: %s", strings.Join(missing, ", "))
  81. errorLog("Please install missing dependencies")
  82. return fmt.Errorf("missing dependencies")
  83. }
  84. log("✓ All required dependencies found")
  85. return nil
  86. }
  87. // Run security scan using gitleaks
  88. func runSecurityScan() error {
  89. log("Running security scan...")
  90. if !commandExists("gitleaks") {
  91. warn("GitLeaks not installed - skipping security scan")
  92. warn("Install with: paru -S gitleaks")
  93. fmt.Println()
  94. fmt.Print("Continue without security scan? (y/N): ")
  95. reader := bufio.NewReader(os.Stdin)
  96. answer, _ := reader.ReadString('\n')
  97. answer = strings.TrimSpace(strings.ToLower(answer))
  98. if answer != "y" && answer != "yes" {
  99. errorLog("Push cancelled for security")
  100. return fmt.Errorf("security scan cancelled")
  101. }
  102. return nil
  103. }
  104. log("Using GitLeaks for secret detection...")
  105. cmd := exec.Command("gitleaks", "detect", "--verbose", "--exit-code", "1")
  106. if err := cmd.Run(); err != nil {
  107. errorLog("❌ Secrets detected! Review before pushing.")
  108. return fmt.Errorf("secrets detected")
  109. }
  110. log("✅ No secrets detected")
  111. return nil
  112. }
  113. // Check if we're in a git repository
  114. func isGitRepo() bool {
  115. cmd := exec.Command("git", "rev-parse", "--git-dir")
  116. return cmd.Run() == nil
  117. }
  118. // Check for uncommitted changes
  119. func hasUncommittedChanges() bool {
  120. cmd := exec.Command("git", "diff-index", "--quiet", "HEAD", "--")
  121. return cmd.Run() != nil
  122. }
  123. // Get current git branch
  124. func getCurrentBranch() (string, error) {
  125. cmd := exec.Command("git", "branch", "--show-current")
  126. output, err := cmd.Output()
  127. if err != nil {
  128. return "", err
  129. }
  130. return strings.TrimSpace(string(output)), nil
  131. }
  132. // Handle git push workflow
  133. func handlePush() error {
  134. log("Preparing to push repository...")
  135. // Check if we're in a git repository
  136. if !isGitRepo() {
  137. errorLog("Not in a git repository")
  138. return fmt.Errorf("not in git repo")
  139. }
  140. // Check for uncommitted changes
  141. if hasUncommittedChanges() {
  142. warn("You have uncommitted changes")
  143. fmt.Println()
  144. // Show git status
  145. cmd := exec.Command("git", "status", "--short")
  146. cmd.Stdout = os.Stdout
  147. cmd.Run()
  148. fmt.Println()
  149. // Generate default commit message
  150. defaultMsg := fmt.Sprintf("dev: automated commit - %s", time.Now().Format("2006-01-02 15:04:05"))
  151. fmt.Print("Commit all changes? (Y/n): ")
  152. reader := bufio.NewReader(os.Stdin)
  153. answer, _ := reader.ReadString('\n')
  154. answer = strings.TrimSpace(strings.ToLower(answer))
  155. if answer != "n" && answer != "no" {
  156. fmt.Println()
  157. fmt.Printf("Default: %s\n", defaultMsg)
  158. fmt.Print("Custom commit message (or press Enter for default): ")
  159. commitMsg, _ := reader.ReadString('\n')
  160. commitMsg = strings.TrimSpace(commitMsg)
  161. if commitMsg == "" {
  162. commitMsg = defaultMsg
  163. }
  164. // Add and commit changes
  165. if err := exec.Command("git", "add", ".").Run(); err != nil {
  166. return fmt.Errorf("failed to add changes: %v", err)
  167. }
  168. if err := exec.Command("git", "commit", "-m", commitMsg).Run(); err != nil {
  169. return fmt.Errorf("failed to commit changes: %v", err)
  170. }
  171. log("✓ Changes committed: %s", commitMsg)
  172. }
  173. }
  174. // Run security scan
  175. if err := runSecurityScan(); err != nil {
  176. return err
  177. }
  178. // Get current branch
  179. branch, err := getCurrentBranch()
  180. if err != nil {
  181. return fmt.Errorf("failed to get current branch: %v", err)
  182. }
  183. // Push to origin
  184. log("Pushing branch '%s' to origin...", branch)
  185. cmd := exec.Command("git", "push", "origin", branch)
  186. if err := cmd.Run(); err != nil {
  187. errorLog("❌ Push failed")
  188. return fmt.Errorf("push failed")
  189. }
  190. log("✅ Successfully pushed to origin/%s", branch)
  191. return nil
  192. }
  193. // Show help message
  194. func showHelp(programName string) {
  195. fmt.Printf(`%s - Development script runner
  196. Usage: %s <command> [options] [arguments]
  197. COMMANDS:
  198. run [filters...] Run scripts matching filters (or all if no filters)
  199. push,u,ush Commit, scan for secrets, and push to git origin
  200. ls, list List all available scripts
  201. new <name> Create a new script template
  202. deps, check Check for required dependencies
  203. help Show this help message
  204. RUN OPTIONS:
  205. --dry Show what would run without executing
  206. --verbose Show detailed output during execution
  207. EXAMPLES:
  208. %s # Show this help
  209. %s run # Run all scripts (with confirmation)
  210. %s run docker # Run scripts containing 'docker'
  211. %s run --dry api # Show what API scripts would run
  212. %s ls # List all scripts
  213. %s new backup # Create a new script called 'backup.sh'
  214. %s push # Secure git push with secret scanning
  215. SECURITY:
  216. The push command automatically scans for secrets using GitLeaks
  217. before pushing to prevent accidental credential exposure.
  218. `, programName, programName, programName, programName, programName, programName, programName, programName, programName)
  219. }
  220. // Get script description from comment
  221. func getDescription(scriptPath string) string {
  222. file, err := os.Open(scriptPath)
  223. if err != nil {
  224. return "No description"
  225. }
  226. defer file.Close()
  227. scanner := bufio.NewScanner(file)
  228. for scanner.Scan() {
  229. line := scanner.Text()
  230. if strings.HasPrefix(line, "# NAME:") {
  231. desc := strings.TrimSpace(strings.TrimPrefix(line, "# NAME:"))
  232. if desc != "" {
  233. return desc
  234. }
  235. }
  236. }
  237. return "No description"
  238. }
  239. // Check if script name matches any of the filters
  240. func matchesFilters(scriptName string, filters []string) bool {
  241. if len(filters) == 0 {
  242. return true
  243. }
  244. scriptNameLower := strings.ToLower(scriptName)
  245. for _, filter := range filters {
  246. filterLower := strings.ToLower(filter)
  247. if strings.Contains(scriptName, filter) || strings.Contains(scriptNameLower, filterLower) {
  248. return true
  249. }
  250. }
  251. return false
  252. }
  253. // Find executable scripts in runs directory
  254. func findScripts(runsDir string, filters []string) ([]Script, error) {
  255. var scripts []Script
  256. err := filepath.Walk(runsDir, func(path string, info os.FileInfo, err error) error {
  257. if err != nil {
  258. return err
  259. }
  260. // Check if file is executable
  261. if info.Mode().IsRegular() && (info.Mode()&0o111) != 0 {
  262. scriptName := filepath.Base(path)
  263. if matchesFilters(scriptName, filters) {
  264. scripts = append(scripts, Script{
  265. Path: path,
  266. Name: scriptName,
  267. Description: getDescription(path),
  268. })
  269. }
  270. }
  271. return nil
  272. })
  273. if err != nil {
  274. return nil, err
  275. }
  276. // Sort scripts by name
  277. sort.Slice(scripts, func(i, j int) bool {
  278. return scripts[i].Name < scripts[j].Name
  279. })
  280. return scripts, nil
  281. }
  282. // List all available scripts
  283. func listScripts(runsDir string) error {
  284. scripts, err := findScripts(runsDir, nil)
  285. if err != nil {
  286. return err
  287. }
  288. if len(scripts) == 0 {
  289. warn("No executable scripts found in %s", runsDir)
  290. return nil
  291. }
  292. fmt.Printf(Blue + "Available scripts:" + NC + "\n")
  293. for _, script := range scripts {
  294. fmt.Printf(" %s%s%s - %s\n", Green, script.Name, NC, script.Description)
  295. }
  296. fmt.Printf("\nTotal: %d scripts\n", len(scripts))
  297. return nil
  298. }
  299. // Create a new script template
  300. func createNewScript(runsDir, scriptName string) error {
  301. if scriptName == "" {
  302. return fmt.Errorf("script name required")
  303. }
  304. // Ensure runs directory exists
  305. if err := os.MkdirAll(runsDir, 0o755); err != nil {
  306. return err
  307. }
  308. // Add .sh extension if not provided
  309. if !strings.HasSuffix(scriptName, ".sh") {
  310. scriptName += ".sh"
  311. }
  312. scriptPath := filepath.Join(runsDir, scriptName)
  313. // Check if script already exists
  314. if _, err := os.Stat(scriptPath); err == nil {
  315. return fmt.Errorf("script %s already exists", scriptName)
  316. }
  317. // Create script template
  318. template := fmt.Sprintf(`#!/usr/bin/env bash
  319. # NAME: %s script
  320. set -euo pipefail
  321. # Add your script logic here
  322. echo "Running %s script..."
  323. # Example:
  324. # - Add your commands below
  325. # - Use proper error handling
  326. # - Add logging as needed
  327. echo "✅ %s completed successfully"
  328. `, strings.TrimSuffix(scriptName, ".sh"), scriptName, strings.TrimSuffix(scriptName, ".sh"))
  329. if err := os.WriteFile(scriptPath, []byte(template), 0o755); err != nil {
  330. return err
  331. }
  332. log("✅ Created new script: %s", scriptPath)
  333. log("Edit the script to add your commands")
  334. return nil
  335. }
  336. // Execute a single script
  337. func executeScript(script Script, logsDir string, verbose bool) error {
  338. logFile := filepath.Join(logsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log")
  339. cmd := exec.Command(script.Path)
  340. if verbose {
  341. // Create log file
  342. logFileHandle, err := os.Create(logFile)
  343. if err != nil {
  344. return err
  345. }
  346. defer logFileHandle.Close()
  347. // Use MultiWriter to write to both stdout and log file
  348. cmd.Stdout = io.MultiWriter(os.Stdout, logFileHandle)
  349. cmd.Stderr = io.MultiWriter(os.Stderr, logFileHandle)
  350. return cmd.Run()
  351. } else {
  352. // Only write to log file
  353. logFileHandle, err := os.Create(logFile)
  354. if err != nil {
  355. return err
  356. }
  357. defer logFileHandle.Close()
  358. cmd.Stdout = logFileHandle
  359. cmd.Stderr = logFileHandle
  360. return cmd.Run()
  361. }
  362. }
  363. // Parse command line arguments
  364. func parseArgs(args []string) (*Config, error) {
  365. config := &Config{}
  366. // Get current working directory (equivalent to bash SCRIPT_DIR)
  367. scriptDir, err := os.Getwd()
  368. if err != nil {
  369. return nil, err
  370. }
  371. config.ScriptDir = scriptDir
  372. config.EnvFile = filepath.Join(config.ScriptDir, ".env")
  373. config.RunsDir = filepath.Join(config.ScriptDir, "runs")
  374. config.LogsDir = filepath.Join(config.ScriptDir, "logs")
  375. if len(args) == 0 {
  376. return config, fmt.Errorf("help")
  377. }
  378. i := 0
  379. // First argument should be the command
  380. if i < len(args) {
  381. arg := args[i]
  382. switch arg {
  383. case "--help", "help":
  384. return config, fmt.Errorf("help")
  385. case "run":
  386. config.Command = "run"
  387. i++
  388. case "push", "u", "ush":
  389. config.Command = "push"
  390. i++
  391. case "ls", "list":
  392. config.Command = "list"
  393. i++
  394. case "new":
  395. config.Command = "new"
  396. i++
  397. case "deps", "check":
  398. config.Command = "deps"
  399. i++
  400. default:
  401. return nil, fmt.Errorf("unknown command: %s", arg)
  402. }
  403. }
  404. // Parse remaining arguments based on command
  405. for i < len(args) {
  406. arg := args[i]
  407. switch arg {
  408. case "--dry":
  409. config.DryRun = true
  410. case "--verbose":
  411. config.Verbose = true
  412. default:
  413. if strings.HasPrefix(arg, "-") {
  414. return nil, fmt.Errorf("unknown option: %s", arg)
  415. }
  416. config.Filters = append(config.Filters, arg)
  417. }
  418. i++
  419. }
  420. return config, nil
  421. }
  422. // Confirm execution of all scripts
  423. func confirmExecution(scripts []Script) bool {
  424. fmt.Printf(Red + "⚠️ About to run ALL scripts:" + NC + "\n")
  425. for _, script := range scripts {
  426. fmt.Printf(" • %s - %s\n", script.Name, script.Description)
  427. }
  428. fmt.Println()
  429. fmt.Print("Continue? (y/N): ")
  430. reader := bufio.NewReader(os.Stdin)
  431. answer, _ := reader.ReadString('\n')
  432. answer = strings.TrimSpace(strings.ToLower(answer))
  433. return answer == "y" || answer == "yes"
  434. }
  435. func main() {
  436. const programName = "dev"
  437. // Parse arguments
  438. config, err := parseArgs(os.Args[1:])
  439. if err != nil {
  440. if err.Error() == "help" {
  441. showHelp(programName)
  442. os.Exit(0)
  443. }
  444. errorLog("Error: %v", err)
  445. fmt.Println()
  446. showHelp(programName)
  447. os.Exit(1)
  448. }
  449. // Handle special commands
  450. switch config.Command {
  451. case "push":
  452. if err := handlePush(); err != nil {
  453. os.Exit(1)
  454. }
  455. os.Exit(0)
  456. case "deps":
  457. if err := checkDependencies(); err != nil {
  458. os.Exit(1)
  459. }
  460. os.Exit(0)
  461. case "list":
  462. if err := listScripts(config.RunsDir); err != nil {
  463. errorLog("Error listing scripts: %v", err)
  464. os.Exit(1)
  465. }
  466. os.Exit(0)
  467. case "new":
  468. if len(config.Filters) == 0 {
  469. errorLog("Script name required for 'new' command")
  470. fmt.Printf("Usage: %s new <script-name>\n", programName)
  471. os.Exit(1)
  472. }
  473. scriptName := config.Filters[0]
  474. if err := createNewScript(config.RunsDir, scriptName); err != nil {
  475. errorLog("Error creating script: %v", err)
  476. os.Exit(1)
  477. }
  478. os.Exit(0)
  479. case "run":
  480. // Continue with script execution logic below
  481. case "":
  482. // No command provided, show help
  483. showHelp(programName)
  484. os.Exit(0)
  485. default:
  486. errorLog("Unknown command: %s", config.Command)
  487. showHelp(programName)
  488. os.Exit(1)
  489. }
  490. // Initialize runs directory if it doesn't exist (only for run command)
  491. if _, err := os.Stat(config.RunsDir); os.IsNotExist(err) {
  492. log("Creating runs directory at: %s", config.RunsDir)
  493. if err := os.MkdirAll(config.RunsDir, 0o755); err != nil {
  494. errorLog("Failed to create runs directory: %v", err)
  495. os.Exit(1)
  496. }
  497. // Create example script
  498. exampleScript := filepath.Join(config.RunsDir, "example.sh")
  499. content := `#!/usr/bin/env bash
  500. # NAME: Example script
  501. echo "Hello from runs/example.sh!"
  502. echo "Edit this script or add your own to runs/"
  503. `
  504. if err := os.WriteFile(exampleScript, []byte(content), 0o755); err != nil {
  505. errorLog("Failed to create example script: %v", err)
  506. os.Exit(1)
  507. }
  508. log("✅ Created runs/ directory with example script")
  509. log("Use '%s ls' to list scripts or '%s new <name>' to create a new one", programName, programName)
  510. os.Exit(0)
  511. }
  512. // Create logs directory
  513. if err := os.MkdirAll(config.LogsDir, 0o755); err != nil {
  514. errorLog("Failed to create logs directory: %v", err)
  515. os.Exit(1)
  516. }
  517. // Find scripts to run
  518. scripts, err := findScripts(config.RunsDir, config.Filters)
  519. if err != nil {
  520. errorLog("Error finding scripts: %v", err)
  521. os.Exit(1)
  522. }
  523. if len(scripts) == 0 {
  524. if len(config.Filters) > 0 {
  525. warn("No scripts match the given filters: %s", strings.Join(config.Filters, ", "))
  526. fmt.Printf("Use '%s ls' to see all available scripts\n", programName)
  527. } else {
  528. warn("No executable scripts found in %s", config.RunsDir)
  529. fmt.Printf("Use '%s new <name>' to create a new script\n", programName)
  530. }
  531. os.Exit(0)
  532. }
  533. // Confirm execution if running all scripts without dry run
  534. if len(config.Filters) == 0 && !config.DryRun {
  535. if !confirmExecution(scripts) {
  536. fmt.Println("Cancelled")
  537. os.Exit(0)
  538. }
  539. }
  540. // Execute scripts
  541. result := ExecutionResult{}
  542. for _, script := range scripts {
  543. if config.DryRun {
  544. fmt.Printf(Blue+"[DRY]"+NC+" Would run: %s - %s\n", script.Name, script.Description)
  545. continue
  546. }
  547. fmt.Printf("\n"+Blue+"▶"+NC+" Running: %s\n", script.Name)
  548. if script.Description != "No description" {
  549. fmt.Printf(" %s\n", script.Description)
  550. }
  551. if err := executeScript(script, config.LogsDir, config.Verbose); err != nil {
  552. errorLog("❌ %s failed (see %s)", script.Name,
  553. filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log"))
  554. result.Failed = append(result.Failed, script.Name)
  555. } else {
  556. log("✅ %s completed", script.Name)
  557. result.Executed = append(result.Executed, script.Name)
  558. }
  559. }
  560. // Print summary
  561. if !config.DryRun {
  562. fmt.Printf("\n" + Blue + "═══ SUMMARY ═══" + NC + "\n")
  563. fmt.Printf("✅ Completed: %d\n", len(result.Executed))
  564. if len(result.Failed) > 0 {
  565. fmt.Printf("❌ Failed: %d\n", len(result.Failed))
  566. fmt.Printf("\n" + Red + "Failed scripts:" + NC + "\n")
  567. for _, failed := range result.Failed {
  568. fmt.Printf(" • %s\n", failed)
  569. }
  570. os.Exit(1)
  571. }
  572. }
  573. }