git.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "strings"
  8. "time"
  9. )
  10. func isGitRepo() bool {
  11. cmd := exec.Command("git", "rev-parse", "--git-dir")
  12. return cmd.Run() == nil
  13. }
  14. func hasUncommittedChanges() bool {
  15. cmd := exec.Command("git", "diff-index", "--quiet", "HEAD", "--")
  16. return cmd.Run() != nil
  17. }
  18. func getCurrentBranch() (string, error) {
  19. cmd := exec.Command("git", "branch", "--show-current")
  20. output, err := cmd.Output()
  21. if err != nil {
  22. return "", err
  23. }
  24. return strings.TrimSpace(string(output)), nil
  25. }
  26. func handlePush() error {
  27. log("Preparing to push repository...")
  28. if !isGitRepo() {
  29. errorLog("Not in a git repository")
  30. return fmt.Errorf("not in git repo")
  31. }
  32. if hasUncommittedChanges() {
  33. warn("You have uncommitted changes")
  34. fmt.Println()
  35. cmd := exec.Command("git", "status", "--short")
  36. cmd.Stdout = os.Stdout
  37. cmd.Run()
  38. fmt.Println()
  39. defaultMsg := fmt.Sprintf("dev: automated commit - %s", time.Now().Format("2006-01-02 15:04:05"))
  40. fmt.Print("Commit all changes? (Y/n): ")
  41. reader := bufio.NewReader(os.Stdin)
  42. answer, _ := reader.ReadString('\n')
  43. answer = strings.TrimSpace(strings.ToLower(answer))
  44. if answer != "n" && answer != "no" {
  45. fmt.Println()
  46. fmt.Printf("Default: %s\n", defaultMsg)
  47. fmt.Print("Custom commit message (or press Enter for default): ")
  48. commitMsg, _ := reader.ReadString('\n')
  49. commitMsg = strings.TrimSpace(commitMsg)
  50. if commitMsg == "" {
  51. commitMsg = defaultMsg
  52. }
  53. if err := exec.Command("git", "add", ".").Run(); err != nil {
  54. return fmt.Errorf("failed to add changes: %v", err)
  55. }
  56. if err := exec.Command("git", "commit", "-m", commitMsg).Run(); err != nil {
  57. return fmt.Errorf("failed to commit changes: %v", err)
  58. }
  59. log("✓ Changes committed: %s", commitMsg)
  60. }
  61. }
  62. if err := runSecurityScan(); err != nil {
  63. return err
  64. }
  65. branch, err := getCurrentBranch()
  66. if err != nil {
  67. return fmt.Errorf("failed to get current branch: %v", err)
  68. }
  69. log("Pushing branch '%s' to origin...", branch)
  70. cmd := exec.Command("git", "push", "origin", branch)
  71. if err := cmd.Run(); err != nil {
  72. errorLog("❌ Push failed")
  73. return fmt.Errorf("push failed")
  74. }
  75. log("✅ Successfully pushed to origin/%s", branch)
  76. return nil
  77. }