From 8189516c4927466494ed6582ed338125aac39b0c Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 15:55:23 +0000 Subject: [PATCH] feat(got): list branches with got Add got.Branches and route both GetBranchNames implementations through it, so branch listing no longer runs git for-each-ref. Names come from `got ref -l refs/heads/`, not `got branch -l`: the latter also reports refs/remotes copies and can print a name twice. Order comes from `got branch -lt`; names that pass misses are appended, so a failure there degrades to lexical order instead of failing the listing. Two got behaviours needed guarding: - `-r` searches upwards. A path that is not a repository made got answer for the enclosing one, so a broken fixture silently returned the parent repository's refs. run now validates the target first. - got refuses a repository without objects/pack or refs/. Those are empty directories, so a fixture checked into git loses them. run recreates the layout, content-free and idempotent. repo2_empty carried .gitkeep files under refs/heads and refs/tags; got reads them as references and fails with "bad reference name". Dropped both, the layout is now created on demand. Tests: go test ./modules/got ./modules/git ./modules/git -tags gogit ./services/repository/... ./modules/repository/... ./models/git/... ./routers/web/repo/... ./services/context/... - all pass. New tests cover ordering, paging, remote-copy filtering, the missing-directory repair, the enclosing-repository refusal, and absence of a git fallback. Assisted-by: OpenCode:DeepSeek-V4.1-Flash --- modules/git/repo_branch_gogit.go | 49 +---- modules/git/repo_branch_nogogit.go | 4 +- .../repos/repo2_empty/refs/heads/.gitkeep | 0 .../repos/repo2_empty/refs/tags/.gitkeep | 0 modules/got/branch.go | 90 +++++++++ modules/got/branch_test.go | 184 ++++++++++++++++++ modules/got/got.go | 50 +++++ 7 files changed, 334 insertions(+), 43 deletions(-) delete mode 100644 modules/git/tests/repos/repo2_empty/refs/heads/.gitkeep delete mode 100644 modules/git/tests/repos/repo2_empty/refs/tags/.gitkeep create mode 100644 modules/got/branch.go create mode 100644 modules/got/branch_test.go diff --git a/modules/git/repo_branch_gogit.go b/modules/git/repo_branch_gogit.go index a791c72b18..d216184881 100644 --- a/modules/git/repo_branch_gogit.go +++ b/modules/git/repo_branch_gogit.go @@ -8,9 +8,11 @@ package git import ( "context" - "sort" "strings" + "gotea.dev/modules/git/gitrepo" + "gotea.dev/modules/got" + "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/storer" ) @@ -56,48 +58,11 @@ func (repo *Repository) IsBranchExist(_ context.Context, name string) bool { return reference.Type() != plumbing.InvalidReference } -// GetBranches returns branches from the repository, skipping "skip" initial branches and +// GetBranchNames returns branches from the repository, skipping "skip" initial branches and // returning at most "limit" branches, or all branches if "limit" is 0. -// Branches are returned with sort of `-committerdate` as the nogogit -// implementation. This requires full fetch, sort and then the -// skip/limit applies later as gogit returns in undefined order. -func (repo *Repository) GetBranchNames(_ context.Context, skip, limit int) ([]string, int, error) { - type BranchData struct { - name string - committerDate int64 - } - var branchData []BranchData - - branchIter, err := repo.gogitRepo.Branches() - if err != nil { - return nil, 0, err - } - - _ = branchIter.ForEach(func(branch *plumbing.Reference) error { - obj, err := repo.gogitRepo.CommitObject(branch.Hash()) - if err != nil { - // skip branch if can't find commit - return nil - } - - branchData = append(branchData, BranchData{strings.TrimPrefix(branch.Name().String(), BranchPrefix), obj.Committer.When.Unix()}) - return nil - }) - - sort.Slice(branchData, func(i, j int) bool { - return !(branchData[i].committerDate < branchData[j].committerDate) - }) - - var branchNames []string - maxPos := len(branchData) - if limit > 0 { - maxPos = min(skip+limit, maxPos) - } - for i := skip; i < maxPos; i++ { - branchNames = append(branchNames, branchData[i].name) - } - - return branchNames, len(branchData), nil +// Branches are returned with sort of `-committerdate` as the nogogit implementation. +func (repo *Repository) GetBranchNames(ctx context.Context, skip, limit int) ([]string, int, error) { + return got.Branches(ctx, gitrepo.RepoLocalPath(repo), skip, limit) } // WalkReferences walks all the references from the repository diff --git a/modules/git/repo_branch_nogogit.go b/modules/git/repo_branch_nogogit.go index c4ea345117..f0e10d43ef 100644 --- a/modules/git/repo_branch_nogogit.go +++ b/modules/git/repo_branch_nogogit.go @@ -13,6 +13,8 @@ import ( "strings" "gotea.dev/modules/git/gitcmd" + "gotea.dev/modules/git/gitrepo" + "gotea.dev/modules/got" "gotea.dev/modules/log" ) @@ -65,7 +67,7 @@ func (repo *Repository) IsBranchExist(ctx context.Context, name string) bool { // GetBranchNames returns branches from the repository, skipping "skip" initial branches and // returning at most "limit" branches, or all branches if "limit" is 0. func (repo *Repository) GetBranchNames(ctx context.Context, skip, limit int) ([]string, int, error) { - return callShowRef(ctx, repo, BranchPrefix, gitcmd.TrustedCmdArgs{BranchPrefix, "--sort=-committerdate"}, skip, limit) + return got.Branches(ctx, gitrepo.RepoLocalPath(repo), skip, limit) } // WalkReferences walks all the references from the repository diff --git a/modules/git/tests/repos/repo2_empty/refs/heads/.gitkeep b/modules/git/tests/repos/repo2_empty/refs/heads/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/modules/git/tests/repos/repo2_empty/refs/tags/.gitkeep b/modules/git/tests/repos/repo2_empty/refs/tags/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/modules/got/branch.go b/modules/got/branch.go new file mode 100644 index 0000000000..a32b3c2bc2 --- /dev/null +++ b/modules/got/branch.go @@ -0,0 +1,90 @@ +// Copyright 2026 The Gotea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package got + +import ( + "context" + "strings" +) + +// branchNameFromRefLine splits a "refs/heads/: " listing line. +func branchNameFromRefLine(line string) (string, bool) { + name, ok := strings.CutPrefix(line, "refs/heads/") + if !ok { + return "", false + } + name, _, ok = strings.Cut(name, ": ") + if !ok || !validBranchName(name) { + return "", false + } + return name, true +} + +// Branches returns the local branches of the repository at path, most recently +// committed first, honouring skip and limit. limit 0 means "no limit"; the +// second return value is always the untruncated branch count. +// +// got ref -l yields the authoritative refs/heads names (got branch -l also +// lists remote copies and can repeat them), while got branch -lt supplies the +// commit order. If the ordering pass fails the branches stay in the lexical +// order got ref -l produced: wrong last-push-first ordering is not worth +// failing a repository listing over, and nothing here falls back to git. +func Branches(ctx context.Context, path string, skip, limit int) ([]string, int, error) { + out, _, err := run(ctx, "ref", "-l", "-r", path, "refs/heads/") + if err != nil { + return nil, 0, err + } + local := make(map[string]struct{}) + var lexical []string + for _, line := range strings.Split(out, "\n") { + name, ok := branchNameFromRefLine(line) + if !ok { + continue + } + if _, dup := local[name]; dup { + continue + } + local[name] = struct{}{} + lexical = append(lexical, name) + } + + ordered := make([]string, 0, len(lexical)) + seen := make(map[string]struct{}, len(lexical)) + if timeOut, _, timeErr := run(ctx, "branch", "-lt", "-r", path); timeErr == nil { + for _, line := range strings.Split(timeOut, "\n") { + name, _, ok := strings.Cut(strings.TrimSpace(line), ": ") + if !ok { + continue + } + name = strings.TrimSpace(name) + if _, isLocal := local[name]; !isLocal { + continue // a copy of a remote branch, not ours + } + if _, dup := seen[name]; dup { + continue + } + seen[name] = struct{}{} + ordered = append(ordered, name) + } + } + for _, name := range lexical { + if _, done := seen[name]; done { + continue + } + seen[name] = struct{}{} + ordered = append(ordered, name) + } + + total := len(ordered) + if skip > 0 { + if skip >= len(ordered) { + return []string{}, total, nil + } + ordered = ordered[skip:] + } + if limit > 0 && limit < len(ordered) { + ordered = ordered[:limit] + } + return ordered, total, nil +} diff --git a/modules/got/branch_test.go b/modules/got/branch_test.go new file mode 100644 index 0000000000..a9f748ac2a --- /dev/null +++ b/modules/got/branch_test.go @@ -0,0 +1,184 @@ +// Copyright 2026 The Gotea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package got + +import ( + "os" + "path/filepath" + "slices" + "testing" + "time" + + "gotea.dev/modules/setting" +) + +// importTree commits the contents of dir onto branch with got import. +func importTree(t *testing.T, repo, branch, message, dir string) { + t.Helper() + if _, _, err := run(t.Context(), "import", "-r", repo, "-b", branch, "-m", message, dir); err != nil { + t.Fatal(err) + } +} + +func writeFile(t *testing.T, dir, name, content string) { + t.Helper() + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestBranchesEmpty(t *testing.T) { + requireGot(t) + repo := filepath.Join(t.TempDir(), "repo.git") + if err := InitBare(t.Context(), repo, "sha1", "main"); err != nil { + t.Fatal(err) + } + branches, total, err := Branches(t.Context(), repo, 0, 0) + if err != nil { + t.Fatal(err) + } + if len(branches) != 0 || total != 0 { + t.Fatalf("unexpected branches %v (total %d)", branches, total) + } +} + +func TestBranchesOrderingAndPaging(t *testing.T) { + requireGot(t) + t.Setenv("GOT_AUTHOR", "Test User ") + dir := t.TempDir() + repo := filepath.Join(dir, "repo.git") + if err := InitBare(t.Context(), repo, "sha1", "main"); err != nil { + t.Fatal(err) + } + + // got branch -lt sorts by commit date, and got stamps commits with the + // wall clock, so each branch needs its own second to have a defined order. + src := filepath.Join(dir, "src") + for _, step := range []struct{ branch, msg string }{ + {"main", "one"}, {"dev", "two"}, {"feature", "three"}, + } { + writeFile(t, src, step.msg+".txt", step.msg+"\n") + importTree(t, repo, step.branch, step.msg, src) + time.Sleep(1100 * time.Millisecond) + } + + branches, total, err := Branches(t.Context(), repo, 0, 0) + if err != nil { + t.Fatal(err) + } + if total != 3 || len(branches) != 3 { + t.Fatalf("unexpected branches %v (total %d)", branches, total) + } + if want := []string{"feature", "dev", "main"}; !slices.Equal(branches, want) { + t.Fatalf("branches are not newest first: got %v, want %v", branches, want) + } + + page, total, err := Branches(t.Context(), repo, 1, 1) + if err != nil { + t.Fatal(err) + } + if total != 3 || len(page) != 1 || page[0] != "dev" { + t.Fatalf("unexpected page %v (total %d)", page, total) + } + + beyond, total, err := Branches(t.Context(), repo, 5, 1) + if err != nil { + t.Fatal(err) + } + if total != 3 || len(beyond) != 0 { + t.Fatalf("unexpected page beyond the end: %v (total %d)", beyond, total) + } +} + +func TestBranchesIgnoresRemoteCopies(t *testing.T) { + requireGot(t) + t.Setenv("GOT_AUTHOR", "Test User ") + dir := t.TempDir() + repo := filepath.Join(dir, "repo.git") + if err := InitBare(t.Context(), repo, "sha1", "main"); err != nil { + t.Fatal(err) + } + src := filepath.Join(dir, "src") + writeFile(t, src, "one.txt", "one\n") + importTree(t, repo, "main", "one", src) + + // got branch -l would also report origin/main, got ref -l refs/heads/ does not. + if _, _, err := run(t.Context(), "ref", "-s", "refs/heads/main", "refs/remotes/origin/main", "-r", repo); err != nil { + t.Fatal(err) + } + branches, total, err := Branches(t.Context(), repo, 0, 0) + if err != nil { + t.Fatal(err) + } + if total != 1 || len(branches) != 1 || branches[0] != "main" { + t.Fatalf("unexpected branches %v (total %d)", branches, total) + } +} + +func TestBranchesRepairsMissingPackDirectory(t *testing.T) { + requireGot(t) + t.Setenv("GOT_AUTHOR", "Test User ") + dir := t.TempDir() + repo := filepath.Join(dir, "repo.git") + if err := InitBare(t.Context(), repo, "sha1", "main"); err != nil { + t.Fatal(err) + } + src := filepath.Join(dir, "src") + writeFile(t, src, "one.txt", "one\n") + importTree(t, repo, "main", "one", src) + + // A fixture copied through git loses empty directories, and got then + // refuses the repository until the layout is repaired. + if err := os.RemoveAll(filepath.Join(repo, "objects", "pack")); err != nil { + t.Fatal(err) + } + branches, _, err := Branches(t.Context(), repo, 0, 0) + if err != nil { + t.Fatal(err) + } + if len(branches) != 1 || branches[0] != "main" { + t.Fatalf("unexpected branches %v", branches) + } +} + +func TestBranchesDoesNotFallBackToGit(t *testing.T) { + requireGot(t) + repo := filepath.Join(t.TempDir(), "repo.git") + if err := InitBare(t.Context(), repo, "sha1", "main"); err != nil { + t.Fatal(err) + } + old := setting.Git.GotPath + setting.Git.GotPath = "gotea-test-got-missing" + t.Cleanup(func() { setting.Git.GotPath = old }) + + if _, _, err := Branches(t.Context(), repo, 0, 0); err == nil { + t.Fatal("expected a got failure instead of a silent git fallback") + } +} + +func TestBranchesRefusesEnclosingRepository(t *testing.T) { + requireGot(t) + t.Setenv("GOT_AUTHOR", "Test User ") + dir := t.TempDir() + outer := filepath.Join(dir, "outer.git") + if err := InitBare(t.Context(), outer, "sha1", "main"); err != nil { + t.Fatal(err) + } + src := filepath.Join(dir, "src") + writeFile(t, src, "one.txt", "one\n") + importTree(t, outer, "main", "one", src) + + // A directory got cannot use as a repository must not answer with the + // enclosing one, which is what an upwards search would do. + inner := filepath.Join(outer, "not-a-repository") + if err := os.Mkdir(inner, 0o755); err != nil { + t.Fatal(err) + } + if _, _, err := Branches(t.Context(), inner, 0, 0); err == nil { + t.Fatal("expected an error instead of resolving to the enclosing repository") + } +} diff --git a/modules/got/got.go b/modules/got/got.go index 5246e6fb46..589509545a 100644 --- a/modules/got/got.go +++ b/modules/got/got.go @@ -12,6 +12,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "gotea.dev/modules/setting" @@ -29,7 +30,29 @@ func Executable() string { return path } +// checkTarget validates a "-r" target first. got resolves "-r" by searching +// upwards, so a directory that is not a repository - a fixture missing its +// refs, a plain path - silently answers for whatever repository encloses it +// and the caller reads another repository's refs. Refuse that instead. +func checkTarget(path string) error { + if err := ensureLayout(path); err != nil { + return err + } + if IsRepository(path) { + return nil + } + if _, err := os.Stat(filepath.Join(path, ".git")); err == nil { + return nil // a work tree, got uses its .git directory + } + return fmt.Errorf("not a repository: %s", path) +} + func run(ctx context.Context, args ...string) (stdout, stderr string, err error) { + if i := slices.Index(args, "-r"); i >= 0 && i+1 < len(args) { + if err := checkTarget(args[i+1]); err != nil { + return "", "", err + } + } cmd := exec.CommandContext(ctx, Executable(), args...) var out, errOut strings.Builder cmd.Stdout = &out @@ -91,6 +114,33 @@ func InitBare(ctx context.Context, path, objectFormat, defaultBranch string) err return err } +// ensureLayout creates the repository layout git tolerates but got requires: +// existing objects/pack, refs/heads and refs/tags directories. A real +// repository always has them (git init and got init both create them), but a +// repository copied without empty directories - a test fixture checked into +// git, an unpacked archive - loses them, and then got refuses the repository +// and may resolve "-r" to an enclosing one. Creating those directories is +// content-free and idempotent. +func ensureLayout(path string) error { + if !IsRepository(path) { + return nil + } + for _, dir := range []string{ + filepath.Join("objects", "pack"), + filepath.Join("refs", "heads"), + filepath.Join("refs", "tags"), + } { + full := filepath.Join(path, dir) + if st, err := os.Stat(full); err == nil && st.IsDir() { + continue + } + if err := os.MkdirAll(full, 0o755); err != nil { + return fmt.Errorf("repair repository layout %s: %w", path, err) + } + } + return nil +} + func isObjectID(s string) bool { if len(s) != 40 && len(s) != 64 { return false