Skip to content

Commit 0cf9dc1

Browse files
committed
allow slashes in branch names
1 parent 0c93970 commit 0cf9dc1

2 files changed

Lines changed: 40 additions & 4 deletions

File tree

internal/gitsemver/gitter.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -242,16 +242,30 @@ func (dg DefaultGitter) GetBranchesFromTag(repo, tag string) (branches []string,
242242
tag = strings.TrimPrefix(tag, "tags/")
243243
var b []byte
244244
if b, err = dg.Exec("-C", repo, "branch", "--all", "--no-color", "--contains", "tags/"+tag); len(b) > 0 /* #nosec G204 */ {
245+
seen := map[string]struct{}{}
245246
for _, s := range strings.Split(string(b), "\n") {
246247
if s = strings.TrimSpace(s); len(s) > 1 {
247248
if !strings.Contains(s, "HEAD") {
248249
starred := s[0] == '*'
249250
s = strings.TrimSpace(strings.TrimPrefix(s, "*"))
251+
// Skip symbolic refs like "origin/HEAD -> origin/main".
250252
if len(s) > 0 && !strings.Contains(s, " ") {
251-
branches = append(branches, LastName(s))
252-
if starred {
253-
branches = branches[len(branches)-1:]
254-
break
253+
if strings.HasPrefix(s, "remotes/") {
254+
// Normalize "remotes/<remote>/<branch>" into "<branch>".
255+
s = strings.TrimPrefix(s, "remotes/")
256+
if idx := strings.IndexByte(s, '/'); idx > -1 {
257+
s = s[idx+1:]
258+
}
259+
}
260+
if s != "" {
261+
if _, ok := seen[s]; !ok {
262+
seen[s] = struct{}{}
263+
branches = append(branches, s)
264+
}
265+
if starred {
266+
branches = branches[len(branches)-1:]
267+
break
268+
}
255269
}
256270
}
257271
}

internal/gitsemver/gitter_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,28 @@ func Test_DefaultGitter_GetBranchFromTag(t *testing.T) {
345345
}
346346
}
347347

348+
func Test_DefaultGitter_GetBranchFromTag_PreservesSlashInBranchName(t *testing.T) {
349+
repo := t.TempDir()
350+
runGit(t, repo, nil, "init", "-q")
351+
runGit(t, repo, nil, "config", "user.email", "test@example.com")
352+
runGit(t, repo, nil, "config", "user.name", "Test")
353+
runGit(t, repo, nil, "checkout", "-q", "-b", "rel/main")
354+
commitAt(t, repo, "a.txt", "a\n", "c1", "2020-01-01T00:00:00Z")
355+
runGit(t, repo, nil, "tag", "v1.0.0")
356+
357+
dg, err := gitsemver.NewDefaultGitter("git", nil)
358+
if err != nil {
359+
t.Fatal(err)
360+
}
361+
branches, err := dg.GetBranchesFromTag(repo, "refs/tags/v1.0.0")
362+
if err != nil {
363+
t.Fatal(err)
364+
}
365+
if slices.Compare(branches, []string{"rel/main"}) != 0 {
366+
t.Fatalf("unexpected branches: %v", branches)
367+
}
368+
}
369+
348370
func Test_DefaultGitter_GetBuild(t *testing.T) {
349371
dg, err := gitsemver.NewDefaultGitter("git", nil)
350372
if err != nil {

0 commit comments

Comments
 (0)