diff --git a/git/git.go b/git/git.go index 645a64fd1..5a979bdb5 100644 --- a/git/git.go +++ b/git/git.go @@ -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 diff --git a/git/git_test.go b/git/git_test.go index 537054012..ae2bcc3e2 100644 --- a/git/git_test.go +++ b/git/git_test.go @@ -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)) } }