main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. "github.com/spf13/cobra"
  13. )
  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"
  20. )
  21. type Config struct {
  22. RunsDir string
  23. LogsDir string
  24. DryRun bool
  25. Verbose bool
  26. }
  27. type Script struct {
  28. Path string
  29. Name string
  30. Description string
  31. }
  32. var config Config
  33. func log(msg string, args ...any) {
  34. fmt.Printf(Green+"[RUN]"+NC+" "+msg+"\n", args...)
  35. }
  36. func warn(msg string, args ...any) {
  37. fmt.Printf(Yellow+"[WARN]"+NC+" "+msg+"\n", args...)
  38. }
  39. func errorLog(msg string, args ...any) {
  40. fmt.Fprintf(os.Stderr, Red+"[ERROR]"+NC+" "+msg+"\n", args...)
  41. }
  42. func commandExists(cmd string) bool {
  43. _, err := exec.LookPath(cmd)
  44. return err == nil
  45. }
  46. func checkDependencies() error {
  47. requiredTools := []string{"git", "find", "grep"}
  48. optionalTools := []string{"gitleaks"}
  49. var missing []string
  50. log("Checking dependencies...")
  51. for _, tool := range requiredTools {
  52. if !commandExists(tool) {
  53. missing = append(missing, tool)
  54. }
  55. }
  56. for _, tool := range optionalTools {
  57. if !commandExists(tool) {
  58. warn("Optional tool missing: %s (recommended for security scanning)", tool)
  59. } else {
  60. log("✓ Found: %s", tool)
  61. }
  62. }
  63. if len(missing) > 0 {
  64. errorLog("Missing required tools: %s", strings.Join(missing, ", "))
  65. errorLog("Please install missing dependencies")
  66. return fmt.Errorf("missing dependencies")
  67. }
  68. log("✓ All required dependencies found")
  69. return nil
  70. }
  71. func runSecurityScan() error {
  72. log("Running security scan...")
  73. if !commandExists("gitleaks") {
  74. warn("GitLeaks not installed - skipping security scan")
  75. warn("Install with: paru -S gitleaks")
  76. fmt.Println()
  77. fmt.Print("Continue without security scan? (y/N): ")
  78. reader := bufio.NewReader(os.Stdin)
  79. answer, _ := reader.ReadString('\n')
  80. answer = strings.TrimSpace(strings.ToLower(answer))
  81. if answer != "y" && answer != "yes" {
  82. errorLog("Push cancelled for security")
  83. return fmt.Errorf("security scan cancelled")
  84. }
  85. return nil
  86. }
  87. log("Using GitLeaks for secret detection...")
  88. cmd := exec.Command("gitleaks", "detect", "--verbose", "--exit-code", "1")
  89. if err := cmd.Run(); err != nil {
  90. errorLog("❌ Secrets detected! Review before pushing.")
  91. return fmt.Errorf("secrets detected")
  92. }
  93. log("✅ No secrets detected")
  94. return nil
  95. }
  96. func isGitRepo() bool {
  97. cmd := exec.Command("git", "rev-parse", "--git-dir")
  98. return cmd.Run() == nil
  99. }
  100. func hasUncommittedChanges() bool {
  101. cmd := exec.Command("git", "diff-index", "--quiet", "HEAD", "--")
  102. return cmd.Run() != nil
  103. }
  104. func getCurrentBranch() (string, error) {
  105. cmd := exec.Command("git", "branch", "--show-current")
  106. output, err := cmd.Output()
  107. if err != nil {
  108. return "", err
  109. }
  110. return strings.TrimSpace(string(output)), nil
  111. }
  112. func handlePush() error {
  113. log("Preparing to push repository...")
  114. if !isGitRepo() {
  115. errorLog("Not in a git repository")
  116. return fmt.Errorf("not in git repo")
  117. }
  118. if hasUncommittedChanges() {
  119. warn("You have uncommitted changes")
  120. fmt.Println()
  121. cmd := exec.Command("git", "status", "--short")
  122. cmd.Stdout = os.Stdout
  123. cmd.Run()
  124. fmt.Println()
  125. defaultMsg := fmt.Sprintf("dev: automated commit - %s", time.Now().Format("2006-01-02 15:04:05"))
  126. fmt.Print("Commit all changes? (Y/n): ")
  127. reader := bufio.NewReader(os.Stdin)
  128. answer, _ := reader.ReadString('\n')
  129. answer = strings.TrimSpace(strings.ToLower(answer))
  130. if answer != "n" && answer != "no" {
  131. fmt.Println()
  132. fmt.Printf("Default: %s\n", defaultMsg)
  133. fmt.Print("Custom commit message (or press Enter for default): ")
  134. commitMsg, _ := reader.ReadString('\n')
  135. commitMsg = strings.TrimSpace(commitMsg)
  136. if commitMsg == "" {
  137. commitMsg = defaultMsg
  138. }
  139. if err := exec.Command("git", "add", ".").Run(); err != nil {
  140. return fmt.Errorf("failed to add changes: %v", err)
  141. }
  142. if err := exec.Command("git", "commit", "-m", commitMsg).Run(); err != nil {
  143. return fmt.Errorf("failed to commit changes: %v", err)
  144. }
  145. log("✓ Changes committed: %s", commitMsg)
  146. }
  147. }
  148. if err := runSecurityScan(); err != nil {
  149. return err
  150. }
  151. branch, err := getCurrentBranch()
  152. if err != nil {
  153. return fmt.Errorf("failed to get current branch: %v", err)
  154. }
  155. log("Pushing branch '%s' to origin...", branch)
  156. cmd := exec.Command("git", "push", "origin", branch)
  157. if err := cmd.Run(); err != nil {
  158. errorLog("❌ Push failed")
  159. return fmt.Errorf("push failed")
  160. }
  161. log("✅ Successfully pushed to origin/%s", branch)
  162. return nil
  163. }
  164. func getDescription(scriptPath string) string {
  165. file, err := os.Open(scriptPath)
  166. if err != nil {
  167. return "No description"
  168. }
  169. defer file.Close()
  170. scanner := bufio.NewScanner(file)
  171. for scanner.Scan() {
  172. line := scanner.Text()
  173. if strings.HasPrefix(line, "# NAME:") {
  174. desc := strings.TrimSpace(strings.TrimPrefix(line, "# NAME:"))
  175. if desc != "" {
  176. return desc
  177. }
  178. }
  179. }
  180. return "No description"
  181. }
  182. func matchesFilters(scriptName string, filters []string) bool {
  183. if len(filters) == 0 {
  184. return true
  185. }
  186. scriptNameLower := strings.ToLower(scriptName)
  187. for _, filter := range filters {
  188. filterLower := strings.ToLower(filter)
  189. if strings.Contains(scriptName, filter) || strings.Contains(scriptNameLower, filterLower) {
  190. return true
  191. }
  192. }
  193. return false
  194. }
  195. func findScripts(filters []string) ([]Script, error) {
  196. var scripts []Script
  197. err := filepath.Walk(config.RunsDir, func(path string, info os.FileInfo, err error) error {
  198. if err != nil {
  199. return err
  200. }
  201. if info.Mode().IsRegular() && (info.Mode()&0o111) != 0 {
  202. scriptName := filepath.Base(path)
  203. if matchesFilters(scriptName, filters) {
  204. scripts = append(scripts, Script{
  205. Path: path,
  206. Name: scriptName,
  207. Description: getDescription(path),
  208. })
  209. }
  210. }
  211. return nil
  212. })
  213. if err != nil {
  214. return nil, err
  215. }
  216. sort.Slice(scripts, func(i, j int) bool {
  217. return scripts[i].Name < scripts[j].Name
  218. })
  219. return scripts, nil
  220. }
  221. func executeScript(script Script, verbose bool) error {
  222. logFile := filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log")
  223. cmd := exec.Command(script.Path)
  224. if verbose {
  225. logFileHandle, err := os.Create(logFile)
  226. if err != nil {
  227. return err
  228. }
  229. defer logFileHandle.Close()
  230. cmd.Stdout = io.MultiWriter(os.Stdout, logFileHandle)
  231. cmd.Stderr = io.MultiWriter(os.Stderr, logFileHandle)
  232. return cmd.Run()
  233. } else {
  234. logFileHandle, err := os.Create(logFile)
  235. if err != nil {
  236. return err
  237. }
  238. defer logFileHandle.Close()
  239. cmd.Stdout = logFileHandle
  240. cmd.Stderr = logFileHandle
  241. return cmd.Run()
  242. }
  243. }
  244. func confirmExecution(scripts []Script) bool {
  245. fmt.Printf(Red + "⚠️ About to run ALL scripts:" + NC + "\n")
  246. for _, script := range scripts {
  247. fmt.Printf(" • %s - %s\n", script.Name, script.Description)
  248. }
  249. fmt.Println()
  250. fmt.Print("Continue? (y/N): ")
  251. reader := bufio.NewReader(os.Stdin)
  252. answer, _ := reader.ReadString('\n')
  253. answer = strings.TrimSpace(strings.ToLower(answer))
  254. return answer == "y" || answer == "yes"
  255. }
  256. func initConfig() {
  257. wd, _ := os.Getwd()
  258. config.RunsDir = filepath.Join(wd, "runs")
  259. config.LogsDir = filepath.Join(wd, "logs")
  260. }
  261. func ensureRunsDir() error {
  262. if _, err := os.Stat(config.RunsDir); os.IsNotExist(err) {
  263. log("Creating runs directory at: %s", config.RunsDir)
  264. if err := os.MkdirAll(config.RunsDir, 0o755); err != nil {
  265. return err
  266. }
  267. exampleScript := filepath.Join(config.RunsDir, "example.sh")
  268. content := `#!/usr/bin/env bash
  269. # NAME: Example script
  270. echo "Hello from runs/example.sh!"
  271. echo "Edit this script or add your own to runs/"
  272. `
  273. if err := os.WriteFile(exampleScript, []byte(content), 0o755); err != nil {
  274. return err
  275. }
  276. log("✅ Created runs/ directory with example script")
  277. log("Use 'dev ls' to list scripts or 'dev new <name>' to create a new one")
  278. return nil
  279. }
  280. return nil
  281. }
  282. var rootCmd = &cobra.Command{
  283. Use: "dev",
  284. Short: "Development script runner",
  285. Long: "A simple tool to manage and run development scripts with security scanning",
  286. }
  287. var runCmd = &cobra.Command{
  288. Use: "run [filters...]",
  289. Short: "Run scripts matching filters (or all if no filters)",
  290. ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  291. scripts, err := findScripts(nil)
  292. if err != nil {
  293. return nil, cobra.ShellCompDirectiveNoFileComp
  294. }
  295. var completions []string
  296. for _, script := range scripts {
  297. scriptName := strings.TrimSuffix(script.Name, ".sh")
  298. if strings.HasPrefix(scriptName, toComplete) {
  299. completions = append(completions, scriptName+"\t"+script.Description)
  300. }
  301. }
  302. return completions, cobra.ShellCompDirectiveNoFileComp
  303. },
  304. RunE: func(cmd *cobra.Command, args []string) error {
  305. if err := ensureRunsDir(); err != nil {
  306. return err
  307. }
  308. if err := os.MkdirAll(config.LogsDir, 0o755); err != nil {
  309. return err
  310. }
  311. scripts, err := findScripts(args)
  312. if err != nil {
  313. return err
  314. }
  315. if len(scripts) == 0 {
  316. if len(args) > 0 {
  317. warn("No scripts match the given filters: %s", strings.Join(args, ", "))
  318. fmt.Println("Use 'dev ls' to see all available scripts")
  319. } else {
  320. warn("No executable scripts found in %s", config.RunsDir)
  321. fmt.Println("Use 'dev new <name>' to create a new script")
  322. }
  323. return nil
  324. }
  325. if len(args) == 0 && !config.DryRun {
  326. if !confirmExecution(scripts) {
  327. fmt.Println("Cancelled")
  328. return nil
  329. }
  330. }
  331. var executed, failed []string
  332. for _, script := range scripts {
  333. if config.DryRun {
  334. fmt.Printf(Blue+"[DRY]"+NC+" Would run: %s - %s\n", script.Name, script.Description)
  335. continue
  336. }
  337. fmt.Printf("\n"+Blue+"▶"+NC+" Running: %s\n", script.Name)
  338. if script.Description != "No description" {
  339. fmt.Printf(" %s\n", script.Description)
  340. }
  341. if err := executeScript(script, config.Verbose); err != nil {
  342. errorLog("❌ %s failed (see %s)", script.Name,
  343. filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log"))
  344. failed = append(failed, script.Name)
  345. } else {
  346. log("✅ %s completed", script.Name)
  347. executed = append(executed, script.Name)
  348. }
  349. }
  350. if !config.DryRun {
  351. fmt.Printf("\n" + Blue + "═══ SUMMARY ═══" + NC + "\n")
  352. fmt.Printf("✅ Completed: %d\n", len(executed))
  353. if len(failed) > 0 {
  354. fmt.Printf("❌ Failed: %d\n", len(failed))
  355. fmt.Printf("\n" + Red + "Failed scripts:" + NC + "\n")
  356. for _, f := range failed {
  357. fmt.Printf(" • %s\n", f)
  358. }
  359. return fmt.Errorf("some scripts failed")
  360. }
  361. }
  362. return nil
  363. },
  364. }
  365. var pushCmd = &cobra.Command{
  366. Use: "push",
  367. Aliases: []string{"u", "ush"},
  368. Short: "Commit, scan for secrets, and push to git origin",
  369. RunE: func(cmd *cobra.Command, args []string) error {
  370. return handlePush()
  371. },
  372. }
  373. var listCmd = &cobra.Command{
  374. Use: "ls",
  375. Aliases: []string{"list"},
  376. Short: "List all available scripts",
  377. RunE: func(cmd *cobra.Command, args []string) error {
  378. scripts, err := findScripts(nil)
  379. if err != nil {
  380. return err
  381. }
  382. if len(scripts) == 0 {
  383. warn("No executable scripts found in %s", config.RunsDir)
  384. return nil
  385. }
  386. fmt.Printf(Blue + "Available scripts:" + NC + "\n")
  387. for _, script := range scripts {
  388. fmt.Printf(" %s%s%s - %s\n", Green, script.Name, NC, script.Description)
  389. }
  390. fmt.Printf("\nTotal: %d scripts\n", len(scripts))
  391. return nil
  392. },
  393. }
  394. var newCmd = &cobra.Command{
  395. Use: "new <name>",
  396. Short: "Create a new script template",
  397. Args: cobra.ExactArgs(1),
  398. RunE: func(cmd *cobra.Command, args []string) error {
  399. scriptName := args[0]
  400. if err := os.MkdirAll(config.RunsDir, 0o755); err != nil {
  401. return err
  402. }
  403. if !strings.HasSuffix(scriptName, ".sh") {
  404. scriptName += ".sh"
  405. }
  406. scriptPath := filepath.Join(config.RunsDir, scriptName)
  407. if _, err := os.Stat(scriptPath); err == nil {
  408. return fmt.Errorf("script %s already exists", scriptName)
  409. }
  410. template := fmt.Sprintf(`#!/usr/bin/env bash
  411. # NAME: %s script
  412. set -euo pipefail
  413. echo "Running %s script..."
  414. # Add your commands here
  415. echo "✅ %s completed successfully"
  416. `, strings.TrimSuffix(scriptName, ".sh"), scriptName, strings.TrimSuffix(scriptName, ".sh"))
  417. if err := os.WriteFile(scriptPath, []byte(template), 0o755); err != nil {
  418. return err
  419. }
  420. log("✅ Created new script: %s", scriptPath)
  421. log("Edit the script to add your commands")
  422. return nil
  423. },
  424. }
  425. var completionCmd = &cobra.Command{
  426. Use: "completion [bash|zsh|fish|powershell]",
  427. Short: "Generate completion script",
  428. Long: `To load completions:
  429. Bash:
  430. $ source <(dev completion bash)
  431. # To load completions for each session, execute once:
  432. # Linux:
  433. $ dev completion bash > /etc/bash_completion.d/dev
  434. # macOS:
  435. $ dev completion bash > $(brew --prefix)/etc/bash_completion.d/dev
  436. Zsh:
  437. # If shell completion is not already enabled in your environment,
  438. # you will need to enable it. You can execute the following once:
  439. $ echo "autoload -U compinit; compinit" >> ~/.zshrc
  440. # To load completions for each session, execute once:
  441. $ dev completion zsh > "${fpath[1]}/_dev"
  442. # You will need to start a new shell for this setup to take effect.
  443. Fish:
  444. $ dev completion fish | source
  445. # To load completions for each session, execute once:
  446. $ dev completion fish > ~/.config/fish/completions/dev.fish
  447. PowerShell:
  448. PS> dev completion powershell | Out-String | Invoke-Expression
  449. # To load completions for every new session, run:
  450. PS> dev completion powershell > dev.ps1
  451. # and source this file from your PowerShell profile.
  452. `,
  453. DisableFlagsInUseLine: true,
  454. ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
  455. Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
  456. RunE: func(cmd *cobra.Command, args []string) error {
  457. switch args[0] {
  458. case "bash":
  459. return rootCmd.GenBashCompletion(os.Stdout)
  460. case "zsh":
  461. return rootCmd.GenZshCompletion(os.Stdout)
  462. case "fish":
  463. return rootCmd.GenFishCompletion(os.Stdout, true)
  464. case "powershell":
  465. return rootCmd.GenPowerShellCompletionWithDesc(os.Stdout)
  466. }
  467. return nil
  468. },
  469. }
  470. var depsCmd = &cobra.Command{
  471. Use: "deps",
  472. Aliases: []string{"check"},
  473. Short: "Check for required dependencies",
  474. RunE: func(cmd *cobra.Command, args []string) error {
  475. return checkDependencies()
  476. },
  477. }
  478. func main() {
  479. initConfig()
  480. runCmd.Flags().BoolVar(&config.DryRun, "dry", false, "Show what would run without executing")
  481. runCmd.Flags().BoolVarP(&config.Verbose, "verbose", "v", false, "Show detailed output during execution")
  482. rootCmd.AddCommand(runCmd, pushCmd, listCmd, newCmd, depsCmd, completionCmd)
  483. if err := rootCmd.Execute(); err != nil {
  484. os.Exit(1)
  485. }
  486. }