main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 ...interface{}) {
  34. fmt.Printf(Green+"[RUN]"+NC+" "+msg+"\n", args...)
  35. }
  36. func warn(msg string, args ...interface{}) {
  37. fmt.Printf(Yellow+"[WARN]"+NC+" "+msg+"\n", args...)
  38. }
  39. func errorLog(msg string, args ...interface{}) {
  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. RunE: func(cmd *cobra.Command, args []string) error {
  291. if err := ensureRunsDir(); err != nil {
  292. return err
  293. }
  294. if err := os.MkdirAll(config.LogsDir, 0o755); err != nil {
  295. return err
  296. }
  297. scripts, err := findScripts(args)
  298. if err != nil {
  299. return err
  300. }
  301. if len(scripts) == 0 {
  302. if len(args) > 0 {
  303. warn("No scripts match the given filters: %s", strings.Join(args, ", "))
  304. fmt.Println("Use 'dev ls' to see all available scripts")
  305. } else {
  306. warn("No executable scripts found in %s", config.RunsDir)
  307. fmt.Println("Use 'dev new <name>' to create a new script")
  308. }
  309. return nil
  310. }
  311. if len(args) == 0 && !config.DryRun {
  312. if !confirmExecution(scripts) {
  313. fmt.Println("Cancelled")
  314. return nil
  315. }
  316. }
  317. var executed, failed []string
  318. for _, script := range scripts {
  319. if config.DryRun {
  320. fmt.Printf(Blue+"[DRY]"+NC+" Would run: %s - %s\n", script.Name, script.Description)
  321. continue
  322. }
  323. fmt.Printf("\n"+Blue+"▶"+NC+" Running: %s\n", script.Name)
  324. if script.Description != "No description" {
  325. fmt.Printf(" %s\n", script.Description)
  326. }
  327. if err := executeScript(script, config.Verbose); err != nil {
  328. errorLog("❌ %s failed (see %s)", script.Name,
  329. filepath.Join(config.LogsDir, strings.TrimSuffix(script.Name, filepath.Ext(script.Name))+".log"))
  330. failed = append(failed, script.Name)
  331. } else {
  332. log("✅ %s completed", script.Name)
  333. executed = append(executed, script.Name)
  334. }
  335. }
  336. if !config.DryRun {
  337. fmt.Printf("\n" + Blue + "═══ SUMMARY ═══" + NC + "\n")
  338. fmt.Printf("✅ Completed: %d\n", len(executed))
  339. if len(failed) > 0 {
  340. fmt.Printf("❌ Failed: %d\n", len(failed))
  341. fmt.Printf("\n" + Red + "Failed scripts:" + NC + "\n")
  342. for _, f := range failed {
  343. fmt.Printf(" • %s\n", f)
  344. }
  345. return fmt.Errorf("some scripts failed")
  346. }
  347. }
  348. return nil
  349. },
  350. }
  351. var pushCmd = &cobra.Command{
  352. Use: "push",
  353. Aliases: []string{"u", "ush"},
  354. Short: "Commit, scan for secrets, and push to git origin",
  355. RunE: func(cmd *cobra.Command, args []string) error {
  356. return handlePush()
  357. },
  358. }
  359. var listCmd = &cobra.Command{
  360. Use: "ls",
  361. Aliases: []string{"list"},
  362. Short: "List all available scripts",
  363. RunE: func(cmd *cobra.Command, args []string) error {
  364. scripts, err := findScripts(nil)
  365. if err != nil {
  366. return err
  367. }
  368. if len(scripts) == 0 {
  369. warn("No executable scripts found in %s", config.RunsDir)
  370. return nil
  371. }
  372. fmt.Printf(Blue + "Available scripts:" + NC + "\n")
  373. for _, script := range scripts {
  374. fmt.Printf(" %s%s%s - %s\n", Green, script.Name, NC, script.Description)
  375. }
  376. fmt.Printf("\nTotal: %d scripts\n", len(scripts))
  377. return nil
  378. },
  379. }
  380. var newCmd = &cobra.Command{
  381. Use: "new <name>",
  382. Short: "Create a new script template",
  383. Args: cobra.ExactArgs(1),
  384. RunE: func(cmd *cobra.Command, args []string) error {
  385. scriptName := args[0]
  386. if err := os.MkdirAll(config.RunsDir, 0o755); err != nil {
  387. return err
  388. }
  389. if !strings.HasSuffix(scriptName, ".sh") {
  390. scriptName += ".sh"
  391. }
  392. scriptPath := filepath.Join(config.RunsDir, scriptName)
  393. if _, err := os.Stat(scriptPath); err == nil {
  394. return fmt.Errorf("script %s already exists", scriptName)
  395. }
  396. template := fmt.Sprintf(`#!/usr/bin/env bash
  397. # NAME: %s script
  398. set -euo pipefail
  399. echo "Running %s script..."
  400. # Add your commands here
  401. echo "✅ %s completed successfully"
  402. `, strings.TrimSuffix(scriptName, ".sh"), scriptName, strings.TrimSuffix(scriptName, ".sh"))
  403. if err := os.WriteFile(scriptPath, []byte(template), 0o755); err != nil {
  404. return err
  405. }
  406. log("✅ Created new script: %s", scriptPath)
  407. log("Edit the script to add your commands")
  408. return nil
  409. },
  410. }
  411. var depsCmd = &cobra.Command{
  412. Use: "deps",
  413. Aliases: []string{"check"},
  414. Short: "Check for required dependencies",
  415. RunE: func(cmd *cobra.Command, args []string) error {
  416. return checkDependencies()
  417. },
  418. }
  419. func main() {
  420. initConfig()
  421. runCmd.Flags().BoolVar(&config.DryRun, "dry", false, "Show what would run without executing")
  422. runCmd.Flags().BoolVarP(&config.Verbose, "verbose", "v", false, "Show detailed output during execution")
  423. rootCmd.AddCommand(runCmd, pushCmd, listCmd, newCmd, depsCmd)
  424. if err := rootCmd.Execute(); err != nil {
  425. os.Exit(1)
  426. }
  427. }