Using git branch --show-current for getting the current branch. Fallback to symbolic-ref

This commit is contained in:
Martín Montes 2020-09-29 22:45:32 +02:00
parent b987cfb39e
commit 0e2e97af68
2 changed files with 35 additions and 6 deletions

View file

@ -56,9 +56,16 @@ func ShowRefs(ref ...string) ([]Ref, error) {
// CurrentBranch reads the checked-out branch for the git repository
func CurrentBranch() (string, error) {
refCmd := GitCommand("symbolic-ref", "--quiet", "--short", "HEAD")
// Available from Git 2.22 and above
branchCmd := GitCommand("branch", "--show-current")
output, err := run.PrepareCmd(branchCmd).Output()
// Fallback to symbolic-ref
if err != nil {
refCmd := GitCommand("symbolic-ref", "--quiet", "--short", "HEAD")
output, err = run.PrepareCmd(refCmd).Output()
}
output, err := run.PrepareCmd(refCmd).Output()
if err == nil {
// Found the branch name
return firstLine(output), nil

View file

@ -58,10 +58,31 @@ func Test_CurrentBranch(t *testing.T) {
}
}
func Test_CurrentBranch_show_current_error(t *testing.T) {
cs, teardown := test.InitCmdStubber()
defer teardown()
cs.StubError("")
expected := "branch-name"
cs.Stub(expected)
result, err := CurrentBranch()
if err != nil {
t.Errorf("got unexpected error: %w", err)
}
if len(cs.Calls) != 2 {
t.Errorf("expected 2 git calls, saw %d", len(cs.Calls))
}
if result != expected {
t.Errorf("unexpected branch name: %s instead of %s", result, expected)
}
}
func Test_CurrentBranch_detached_head(t *testing.T) {
cs, teardown := test.InitCmdStubber()
defer teardown()
cs.StubError("")
cs.StubError("")
_, err := CurrentBranch()
@ -71,8 +92,8 @@ func Test_CurrentBranch_detached_head(t *testing.T) {
if err != ErrNotOnAnyBranch {
t.Errorf("got unexpected error: %s instead of %s", err, ErrNotOnAnyBranch)
}
if len(cs.Calls) != 1 {
t.Errorf("expected 1 git call, saw %d", len(cs.Calls))
if len(cs.Calls) != 2 {
t.Errorf("expected 2 git calls, saw %d", len(cs.Calls))
}
}
@ -80,6 +101,7 @@ func Test_CurrentBranch_unexpected_error(t *testing.T) {
cs, teardown := test.InitCmdStubber()
defer teardown()
cs.StubError("lol")
cs.StubError("lol")
expectedError := "lol\nstub: lol"
@ -91,8 +113,8 @@ func Test_CurrentBranch_unexpected_error(t *testing.T) {
if err.Error() != expectedError {
t.Errorf("got unexpected error: %s instead of %s", err.Error(), expectedError)
}
if len(cs.Calls) != 1 {
t.Errorf("expected 1 git call, saw %d", len(cs.Calls))
if len(cs.Calls) != 2 {
t.Errorf("expected 2 git calls, saw %d", len(cs.Calls))
}
}