Skip to content

Commit 2eab4a9

Browse files
authored
Merge pull request cli#2025 from mmontes11/pr-create-use-git-branch-show-current
Avoding --short option in git symbolic-ref for getting the current branch
2 parents 54e2927 + 2a166d1 commit 2eab4a9

2 files changed

Lines changed: 39 additions & 16 deletions

File tree

git/git.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,12 @@ func ShowRefs(ref ...string) ([]Ref, error) {
5656

5757
// CurrentBranch reads the checked-out branch for the git repository
5858
func CurrentBranch() (string, error) {
59-
refCmd := GitCommand("symbolic-ref", "--quiet", "--short", "HEAD")
59+
refCmd := GitCommand("symbolic-ref", "--quiet", "HEAD")
6060

6161
output, err := run.PrepareCmd(refCmd).Output()
6262
if err == nil {
6363
// Found the branch name
64-
return firstLine(output), nil
64+
return getBranchShortName(output), nil
6565
}
6666

6767
var cmdErr *run.CmdError
@@ -291,3 +291,8 @@ func firstLine(output []byte) string {
291291
}
292292
return string(output)
293293
}
294+
295+
func getBranchShortName(output []byte) string {
296+
branch := firstLine(output)
297+
return strings.TrimPrefix(branch, "refs/heads/")
298+
}

git/git_test.go

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,22 +39,40 @@ func Test_UncommittedChangeCount(t *testing.T) {
3939
}
4040

4141
func Test_CurrentBranch(t *testing.T) {
42-
cs, teardown := test.InitCmdStubber()
43-
defer teardown()
44-
45-
expected := "branch-name"
46-
47-
cs.Stub(expected)
48-
49-
result, err := CurrentBranch()
50-
if err != nil {
51-
t.Errorf("got unexpected error: %w", err)
42+
type c struct {
43+
Stub string
44+
Expected string
5245
}
53-
if len(cs.Calls) != 1 {
54-
t.Errorf("expected 1 git call, saw %d", len(cs.Calls))
46+
cases := []c{
47+
{
48+
Stub: "branch-name\n",
49+
Expected: "branch-name",
50+
},
51+
{
52+
Stub: "refs/heads/branch-name\n",
53+
Expected: "branch-name",
54+
},
55+
{
56+
Stub: "refs/heads/branch\u00A0with\u00A0non\u00A0breaking\u00A0space\n",
57+
Expected: "branch\u00A0with\u00A0non\u00A0breaking\u00A0space",
58+
},
5559
}
56-
if result != expected {
57-
t.Errorf("unexpected branch name: %s instead of %s", result, expected)
60+
61+
for _, v := range cases {
62+
cs, teardown := test.InitCmdStubber()
63+
cs.Stub(v.Stub)
64+
65+
result, err := CurrentBranch()
66+
if err != nil {
67+
t.Errorf("got unexpected error: %w", err)
68+
}
69+
if len(cs.Calls) != 1 {
70+
t.Errorf("expected 1 git call, saw %d", len(cs.Calls))
71+
}
72+
if result != v.Expected {
73+
t.Errorf("unexpected branch name: %s instead of %s", result, v.Expected)
74+
}
75+
teardown()
5876
}
5977
}
6078

0 commit comments

Comments
 (0)