X Tutup
Skip to content

Commit 0af2324

Browse files
committed
consolidate into one symbolic-ref call
1 parent dd877b6 commit 0af2324

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed

git/git.go

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,27 +21,23 @@ func VerifyRef(ref string) bool {
2121

2222
// CurrentBranch reads the checked-out branch for the git repository
2323
func CurrentBranch() (string, error) {
24-
noBranchError := errors.New("git: not on any branch")
2524

26-
// we avoid using `git branch --show-current` for compatibility with git < 2.22
27-
output, err := run.PrepareCmd(GitCommand("rev-parse", "--abbrev-ref", "HEAD")).Output()
28-
branchName := firstLine(output)
25+
refCmd := GitCommand("symbolic-ref", "--quiet", "--short", "HEAD")
26+
27+
output, err := run.PrepareCmd(refCmd).Output()
2928
if err == nil {
30-
if branchName == "HEAD" {
31-
return "", noBranchError
32-
} else {
33-
return branchName, nil
34-
}
29+
// Found the branch name
30+
return firstLine(output), nil
3531
}
3632

37-
// Fall back to symbolic-ref in case we're in a repository with no commits
38-
output, err = run.PrepareCmd(GitCommand("symbolic-ref", "--short", "HEAD")).Output()
39-
if err != nil {
40-
return "", noBranchError
33+
ce := err.(*run.CmdError)
34+
if ce.Stderr.Len() == 0 {
35+
// Detached head
36+
return "", errors.New("git: not on any branch")
4137
}
42-
branchName = firstLine(output)
4338

44-
return branchName, nil
39+
// Unknown error
40+
return "", err
4541
}
4642

4743
func listRemotes() ([]string, error) {

0 commit comments

Comments
 (0)
X Tutup