From 3c6b249810c94b7ca90df192b990de054f885ca7 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 18:02:34 +0000 Subject: [PATCH] feat(got): check branch and tag existence with got IsBranchExist and IsTagExist now ask got.RefExists instead of git's cat-file batch. got's exit status is useless here: `got ref -l ` exits 0 with no output, and an empty repository reports "HEAD: refs/heads/main" for a branch that does not exist yet. The wrapper therefore parses the ": " line and follows symbolic entries with a bounded depth. IsReferenceExist/IsObjectExist keep the cat-file batch: they answer "is this object present" for bare and short commit IDs, which got ref cannot, and `got cat` resolves unknown arguments as paths in HEAD's tree, so it would report file names as existing objects. That gap is documented, not silent. Verified: go test ./modules/got ./modules/git (ref_test.go covers both ref behaviours, the empty repository, and the enclosing-repository escape; ref_got_test.go covers true/false branches and tags plus a missing got binary). Full go test ./modules/... ./services/... ./models/... ./routers/... and make -C cgi check pass. Assisted-by: splinter:claude-opus-4 --- AGENTS.md | 11 +++ README.md | 13 ++- modules/git/ref_got_test.go | 82 ++++++++++++++++++ modules/git/repo_branch_nogogit.go | 7 +- modules/git/repo_tag_nogogit.go | 9 +- modules/got/ref.go | 102 ++++++++++++++++++++++ modules/got/ref_test.go | 133 +++++++++++++++++++++++++++++ 7 files changed, 352 insertions(+), 5 deletions(-) create mode 100644 modules/git/ref_got_test.go create mode 100644 modules/got/ref.go create mode 100644 modules/got/ref_test.go diff --git a/AGENTS.md b/AGENTS.md index 670a8171b0..f14278d8c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,6 +116,17 @@ make test-migration # after modelmigration changes latter also reports `refs/remotes/` copies and can repeat a name. It takes the order from `got branch -lt` and appends any name that pass missed, so a failure there degrades to the lexical order instead of failing the listing. +- `RefExists` is the branch/tag existence check. got's exit status cannot be used + for it: `got ref -l ` exits 0 with no output, and in an empty + repository it lists `HEAD: refs/heads/` for a branch that does not + exist yet. The wrapper parses the `: ` line, follows symbolic + entries (bounded), and answers true only for an object ID. +- `IsReferenceExist`/`IsObjectExist` still use git's cat-file batch on purpose: + they answer "is this object here" (commit IDs, short hashes), which `got ref` + cannot. Do not swap them for `RefExists`; a bare object ID must stay false + there. This is a known gap, not an oversight - got has no object-existence + command, and `got cat` resolves non-object arguments as paths in HEAD's tree, + so it reports files as existing objects. - File changes require a **work tree**, whose metadata is `.got/` (not `.git/`). A bare repository cannot be edited in place: server-side edits and merges need a temporary `got checkout` work tree and a `got commit`. Serialize per repository diff --git a/README.md b/README.md index b5e3983e4e..298c6e1835 100644 --- a/README.md +++ b/README.md @@ -130,13 +130,20 @@ contrast failures (925/945 pass), which do not affect the build path. ## Backend got migration Bare repositories are created with `got init` through `modules/got`, and -`IsEmpty`, `GetDefaultBranch`, `SetDefaultBranch`, `GetBranchCommitID`, and -`GetBranchNames` use got. Unborn branches write HEAD atomically because -`got ref -s` requires the target branch to exist. +`IsEmpty`, `GetDefaultBranch`, `SetDefaultBranch`, `GetBranchCommitID`, +`GetBranchNames`, plus the branch/tag existence checks (`IsBranchExist`, +`IsTagExist` via `RefExists`) use got. Unborn branches write HEAD atomically +because `got ref -s` requires the target branch to exist. `GOT_PATH` in the `[git]` section selects the binary (default `got`). Non-bare temporary worktrees and pushing still use git while the migration proceeds. There is no silent git fallback for the migrated paths. +`IsReferenceExist` and `IsObjectExist` stay on git's cat-file batch: they answer +"is this object present", including bare and abbreviated commit IDs, which +`got ref` cannot express. `got cat` is not a replacement either — it resolves +unknown arguments as paths inside HEAD's tree, so a file name would answer as an +existing object. + ## Design notes - HTML 4.01 Transitional, CSS1, table layout, no JavaScript, no external assets. diff --git a/modules/git/ref_got_test.go b/modules/git/ref_got_test.go new file mode 100644 index 0000000000..a7a968ab20 --- /dev/null +++ b/modules/git/ref_got_test.go @@ -0,0 +1,82 @@ +// Copyright 2026 The Gotea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package git + +import ( + "testing" + + "gotea.dev/modules/got" + "gotea.dev/modules/setting" +) + +func TestIsBranchExistUsesGot(t *testing.T) { + if _, err := got.Version(t.Context()); err != nil { + t.Skipf("got not available: %v", err) + } + repo, err := OpenRepositoryLocal(t.Context(), "tests/repos/repo1_bare") + if err != nil { + t.Fatal(err) + } + defer repo.Close() + + for _, name := range []string{"master", "branch1", "branch2"} { + if !repo.IsBranchExist(t.Context(), name) { + t.Errorf("expected branch %q to exist", name) + } + } + for _, name := range []string{"nosuch", "maste", "branch", "master1"} { + if repo.IsBranchExist(t.Context(), name) { + t.Errorf("expected branch %q not to exist", name) + } + } + + // The fixture has no refs/heads/dev; an enclosing repository must not answer. + if IsBranchExist(t.Context(), repo, "dev") { + t.Error("branch dev resolved from outside the repository") + } +} + +func TestIsTagExistUsesGot(t *testing.T) { + if _, err := got.Version(t.Context()); err != nil { + t.Skipf("got not available: %v", err) + } + repo, err := OpenRepositoryLocal(t.Context(), "tests/repos/repo1_bare") + if err != nil { + t.Fatal(err) + } + defer repo.Close() + + for _, name := range []string{"test", "signed-tag"} { + if !repo.IsTagExist(t.Context(), name) { + t.Errorf("expected tag %q to exist", name) + } + } + for _, name := range []string{"nosuch", "t", "test1"} { + if repo.IsTagExist(t.Context(), name) { + t.Errorf("expected tag %q not to exist", name) + } + } +} + +func TestIsBranchExistDoesNotFallBackToGit(t *testing.T) { + if _, err := got.Version(t.Context()); err != nil { + t.Skipf("got not available: %v", err) + } + repo, err := OpenRepositoryLocal(t.Context(), "tests/repos/repo1_bare") + if err != nil { + t.Fatal(err) + } + defer repo.Close() + + old := setting.Git.GotPath + setting.Git.GotPath = "gotea-test-got-missing" + t.Cleanup(func() { setting.Git.GotPath = old }) + + if repo.IsBranchExist(t.Context(), "master") { + t.Fatal("expected false without got instead of a silent git answer") + } + if repo.IsTagExist(t.Context(), "test") { + t.Fatal("expected false without got instead of a silent git answer") + } +} diff --git a/modules/git/repo_branch_nogogit.go b/modules/git/repo_branch_nogogit.go index f0e10d43ef..16098bbae5 100644 --- a/modules/git/repo_branch_nogogit.go +++ b/modules/git/repo_branch_nogogit.go @@ -61,7 +61,12 @@ func (repo *Repository) IsBranchExist(ctx context.Context, name string) bool { return false } - return repo.IsReferenceExist(ctx, BranchPrefix+name) + exists, err := got.RefExists(ctx, gitrepo.RepoLocalPath(repo), BranchPrefix+name) + if err != nil { + log.Error("IsBranchExist %s: %v", name, err) + return false + } + return exists } // GetBranchNames returns branches from the repository, skipping "skip" initial branches and diff --git a/modules/git/repo_tag_nogogit.go b/modules/git/repo_tag_nogogit.go index 77bc24f927..1331f07e8f 100644 --- a/modules/git/repo_tag_nogogit.go +++ b/modules/git/repo_tag_nogogit.go @@ -11,6 +11,8 @@ import ( "errors" "io" + "gotea.dev/modules/git/gitrepo" + "gotea.dev/modules/got" "gotea.dev/modules/log" ) @@ -20,7 +22,12 @@ func (repo *Repository) IsTagExist(ctx context.Context, name string) bool { return false } - return repo.IsReferenceExist(ctx, TagPrefix+name) + exists, err := got.RefExists(ctx, gitrepo.RepoLocalPath(repo), TagPrefix+name) + if err != nil { + log.Error("IsTagExist %s: %v", name, err) + return false + } + return exists } // GetTagType gets the type of the tag, either commit (simple) or tag (annotated) diff --git a/modules/got/ref.go b/modules/got/ref.go new file mode 100644 index 0000000000..f0cdec5575 --- /dev/null +++ b/modules/got/ref.go @@ -0,0 +1,102 @@ +// Copyright 2026 The Gotea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package got + +import ( + "context" + "fmt" + "strings" +) + +// validRefName rejects names that got would read as an option or that no +// reference can have. Placement is the caller's job; this only keeps the +// argument list intact and stops the obvious garbage. +func validRefName(name string) bool { + if name == "" || strings.HasPrefix(name, "-") || strings.ContainsAny(name, " \t\n\r") { + return false + } + return true +} + +// RefExists reports whether the repository has a reference with exactly that +// name that resolves to an object, matching git show-ref --verify. Two got +// behaviours make that harder than the exit status: +// +// - got exits 0 and prints nothing for an unknown name, so the answer is the +// ": " line, not the command result. +// - in an empty repository got still lists HEAD, as "HEAD: refs/heads/main", +// pointing at a branch that does not exist yet. A symbolic entry therefore +// only counts when its target resolves. +// +// A bare object ID is not a reference and answers false, again like +// show-ref --verify; callers that pass a commit ID rely on that. +func RefExists(ctx context.Context, path, name string) (bool, error) { + for range maxSymbolicDepth { + if !validRefName(name) { + return false, nil + } + out, _, err := run(ctx, "ref", "-l", "-r", path, name) + if err != nil { + if strings.Contains(err.Error(), "bad reference name") { + return false, nil + } + return false, err + } + prefix := name + ": " + var value string + var found bool + for _, line := range strings.Split(out, "\n") { + if v, ok := strings.CutPrefix(line, prefix); ok { + value, found = strings.TrimSpace(v), true + break + } + } + if !found { + return false, nil + } + if isObjectID(value) { + return true, nil + } + name = value // symbolic: resolve its target before answering + } + return false, nil +} + +// maxSymbolicDepth bounds symbolic reference chains; git limits them too, and +// a loop must not hang the caller. +const maxSymbolicDepth = 5 + +// RefObjectID returns the object a reference points at. A symbolic reference +// reports its target instead of an object, which is an error here. +func RefObjectID(ctx context.Context, path, name string) (string, error) { + if !validRefName(name) { + return "", fmt.Errorf("invalid reference name: %q", name) + } + out, _, err := run(ctx, "ref", "-l", "-r", path, name) + if err != nil { + return "", err + } + prefix := name + ": " + for _, line := range strings.Split(out, "\n") { + value, ok := strings.CutPrefix(line, prefix) + if !ok { + continue + } + value = strings.TrimSpace(value) + if isObjectID(value) { + return value, nil + } + return "", fmt.Errorf("reference %s is not an object: %s", name, value) + } + return "", ErrRefNotFound{Name: name} +} + +// ErrRefNotFound reports a missing reference. +type ErrRefNotFound struct { + Name string +} + +func (e ErrRefNotFound) Error() string { + return "reference not found: " + e.Name +} diff --git a/modules/got/ref_test.go b/modules/got/ref_test.go new file mode 100644 index 0000000000..3f2c76d758 --- /dev/null +++ b/modules/got/ref_test.go @@ -0,0 +1,133 @@ +// Copyright 2026 The Gotea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package got + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +// seedRepoWithRefs creates a bare repository holding one commit on main, a +// lightweight tag, an annotated tag, a pull ref, and HEAD pointing at main. +func seedRepoWithRefs(t *testing.T) (repoPath, commitID string) { + t.Helper() + requireGot(t) + dir := t.TempDir() + repoPath = filepath.Join(dir, "repo.git") + if err := InitBare(t.Context(), repoPath, "sha1", "main"); err != nil { + t.Fatal(err) + } + src := filepath.Join(dir, "src") + writeFile(t, src, "a.txt", "x\n") + importTree(t, repoPath, "main", "one", src) + + commitID, err := BranchCommitID(t.Context(), repoPath, "main") + if err != nil { + t.Fatal(err) + } + if _, _, err := run(t.Context(), "ref", "-c", commitID, "refs/tags/light", "-r", repoPath); err != nil { + t.Fatal(err) + } + if _, _, err := run(t.Context(), "tag", "-m", "annotated", "ann", "-r", repoPath); err != nil { + t.Fatal(err) + } + if _, _, err := run(t.Context(), "ref", "-c", commitID, "refs/pull/1/head", "-r", repoPath); err != nil { + t.Fatal(err) + } + return repoPath, commitID +} + +func TestRefExists(t *testing.T) { + repoPath, commitID := seedRepoWithRefs(t) + + for _, name := range []string{ + "HEAD", + "refs/heads/main", + "refs/tags/light", + "refs/tags/ann", + "refs/pull/1/head", + } { + exists, err := RefExists(t.Context(), repoPath, name) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if !exists { + t.Errorf("expected %s to exist", name) + } + } + + for _, name := range []string{ + "refs/heads/nosuch", + "refs/heads/mai", + "refs/tags/nosuch", + "refs/pull/1/head2", + commitID, // a commit ID is not a reference + commitID[:7], // neither is a short one + "refs/heads/", // a namespace is not a reference + "", // empty input + "-x", // would be read as an option + "refs/heads/../escape", // nonsense + } { + exists, err := RefExists(t.Context(), repoPath, name) + if err != nil { + t.Fatalf("%q: %v", name, err) + } + if exists { + t.Errorf("expected %q not to exist", name) + } + } +} + +func TestRefExistsInEmptyRepository(t *testing.T) { + requireGot(t) + repoPath := filepath.Join(t.TempDir(), "repo.git") + if err := InitBare(t.Context(), repoPath, "sha1", "main"); err != nil { + t.Fatal(err) + } + for _, name := range []string{"HEAD", "refs/heads/main"} { + exists, err := RefExists(t.Context(), repoPath, name) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if exists { + t.Errorf("expected %s not to exist in an empty repository", name) + } + } +} + +func TestRefExistsDoesNotEscapeTarget(t *testing.T) { + seedRepoWithRefs(t) + plain := t.TempDir() + if _, err := RefExists(t.Context(), plain, "refs/heads/main"); err == nil { + t.Fatal("expected an error for a directory that is not a repository") + } +} + +func TestRefObjectID(t *testing.T) { + repoPath, commitID := seedRepoWithRefs(t) + + id, err := RefObjectID(t.Context(), repoPath, "refs/heads/main") + if err != nil { + t.Fatal(err) + } + if id != commitID { + t.Fatalf("unexpected ID %q, want %q", id, commitID) + } + + if _, err := RefObjectID(t.Context(), repoPath, "refs/heads/nosuch"); !errors.Is(err, ErrRefNotFound{Name: "refs/heads/nosuch"}) { + t.Fatalf("expected a not-found error, got %v", err) + } + + // HEAD is symbolic: its target is reported instead of an object ID. + if _, err := RefObjectID(t.Context(), repoPath, "HEAD"); err == nil { + t.Fatal("expected an error for a symbolic reference") + } else if errors.Is(err, ErrRefNotFound{}) { + t.Fatalf("symbolic reference should not report as missing: %v", err) + } + if _, err := os.Stat(filepath.Join(repoPath, "HEAD")); err != nil { + t.Fatalf("repository was damaged: %v", err) + } +}