GetDefaultBranch detects the default branch (main or master) for a repository.
(repoDir string)
| 18 | |
| 19 | // GetDefaultBranch detects the default branch (main or master) for a repository. |
| 20 | func GetDefaultBranch(repoDir string) (string, error) { |
| 21 | // Try symbolic-ref first (works for repos with remotes) |
| 22 | cmd := exec.Command("git", "symbolic-ref", "refs/remotes/origin/HEAD") |
| 23 | cmd.Dir = repoDir |
| 24 | output, err := cmd.Output() |
| 25 | if err == nil { |
| 26 | ref := strings.TrimSpace(string(output)) |
| 27 | // refs/remotes/origin/main -> main |
| 28 | parts := strings.Split(ref, "/") |
| 29 | if len(parts) > 0 { |
| 30 | return parts[len(parts)-1], nil |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // Fallback: check if main or master branch exists |
| 35 | for _, branch := range []string{"main", "master"} { |
| 36 | exists, err := BranchExists(repoDir, branch) |
| 37 | if err != nil { |
| 38 | continue |
| 39 | } |
| 40 | if exists { |
| 41 | return branch, nil |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | return "", fmt.Errorf("could not detect default branch (tried main, master)") |
| 46 | } |
| 47 | |
| 48 | // CreateWorktree creates a branch from the default branch and adds a worktree at the given path. |
| 49 | // If the worktree path already exists and is a valid worktree on the expected branch, it is reused. |