Skip to content

Git designed for AI agents.

operations: read the chosen start reference once, and beat decoys of slashed branches

Federico Eliaa5d13dae1781
diff --git a/internal/git/localrepo/refs.go b/internal/git/localrepo/refs.go
index 9ffeae6..a7b554f 100644
--- a/internal/git/localrepo/refs.go
+++ b/internal/git/localrepo/refs.go
@@ -217,26 +217,6 @@ func badReferenceValue(stderr string, reference git.ReferenceName) (git.ObjectID
return git.ObjectID(value), true
}
-// ReferenceExists reports whether reference exists under its exact name, with `git show-ref
-// --exists`: no DWIM rule, whatever its value points to (an object that is missing included). A
-// name that is not a valid reference name does not exist.
-func (repo *Repo) ReferenceExists(ctx context.Context, reference git.ReferenceName) (bool, error) {
- var stderr bytes.Buffer
- err := repo.ExecAndWait(ctx, gitcmd.Command{
- Name: "show-ref",
- Flags: []gitcmd.Option{gitcmd.Flag{Name: "--exists"}},
- Args: []string{reference.String()},
- }, gitcmd.WithStderr(&stderr))
- if err == nil {
- return true, nil
- }
- // show-ref --exists exits 2 for a reference that does not exist.
- if code, ok := command.ExitStatus(err); ok && code == 2 {
- return false, nil
- }
- return false, fmt.Errorf("show-ref --exists %q: %w, stderr: %q", reference, err, stderr.String())
-}
-
// GetReference looks up and returns the given reference. Returns a
// ReferenceNotFound error if the reference was not found.
func (repo *Repo) GetReference(ctx context.Context, reference git.ReferenceName) (git.Reference, error) {
@@ -470,17 +450,19 @@ func (repo *Repo) GetDefaultBranch(ctx context.Context) (git.ReferenceName, erro
// candidate is read by its exact name: with its DWIM rules, git would take a
// missing refs/heads/main for one of refs/refs/heads/main,
// refs/tags/refs/heads/main, refs/heads/refs/heads/main or
- // refs/remotes/refs/heads/main.
+ // refs/remotes/refs/heads/main. A candidate counts when it has a value: a
+ // branch whose object is missing does, a dangling symbolic reference does
+ // not.
for _, headCandidate := range []git.ReferenceName{
headReference, git.DefaultRef, git.LegacyDefaultRef,
} {
- exists, err := repo.ReferenceExists(ctx, headCandidate)
- if err != nil {
+ if _, err := repo.ResolveReferenceExactly(ctx, headCandidate); err != nil {
+ if errors.Is(err, git.ErrReferenceNotFound) {
+ continue
+ }
return "", err
}
- if exists {
- return headCandidate, nil
- }
+ return headCandidate, nil
}
// If all else fails, return the first branch name
diff --git a/internal/git/localrepo/refs_test.go b/internal/git/localrepo/refs_test.go
index 9c5f5af..5c49f48 100644
--- a/internal/git/localrepo/refs_test.go
+++ b/internal/git/localrepo/refs_test.go
@@ -270,34 +270,22 @@ func TestRepo_GetDefaultBranchReadsCandidatesExactly(t *testing.T) {
require.NoError(t, err)
require.Equal(t, git.DefaultRef, defaultBranch)
})
-}
-
-// TestRepo_ReferenceExists checks that a reference exists only under its exact name, whatever it
-// points to, and that a name that is not a reference name does not exist.
-func TestRepo_ReferenceExists(t *testing.T) {
- t.Parallel()
- ctx := testhelper.Context(t)
- cfg, repo, repoPath := setupRepo(t, withDisabledHooks())
+ t.Run("HEAD's branch a dangling symbolic reference", func(t *testing.T) {
+ t.Parallel()
- commit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))
- gittest.WriteRef(t, cfg, repoPath, "refs/tags/refs/heads/x", commit)
- gittest.WriteRef(t, cfg, repoPath, "refs/heads/x/y", commit)
- broken := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("broken"))
- gittest.WriteRef(t, cfg, repoPath, "refs/heads/broken", broken)
- require.NoError(t, os.Remove(filepath.Join(repoPath, "objects", broken.String()[:2], broken.String()[2:])))
+ // refs/heads/main points to a branch that does not exist: it has no value, so the
+ // default branch falls back to master, whatever decoy is named for main.
+ cfg, repo, repoPath := setupRepo(t, withDisabledHooks())
+ gittest.Exec(t, cfg, "-C", repoPath, "symbolic-ref", "HEAD", "refs/heads/main")
+ gittest.Exec(t, cfg, "-C", repoPath, "symbolic-ref", "refs/heads/main", "refs/heads/nope")
+ master := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("master"))
+ gittest.WriteRef(t, cfg, repoPath, "refs/refs/heads/main", master)
- for reference, expected := range map[git.ReferenceName]bool{
- "refs/heads/main": true,
- "refs/heads/broken": true,
- "refs/heads/x": false,
- "refs/heads/x*": false,
- "refs/heads/main~1": false,
- } {
- exists, err := repo.ReferenceExists(ctx, reference)
- require.NoError(t, err, reference)
- require.Equal(t, expected, exists, reference)
- }
+ defaultBranch, err := repo.GetDefaultBranch(ctx)
+ require.NoError(t, err)
+ require.Equal(t, git.LegacyDefaultRef, defaultBranch)
+ })
}
func TestRepo_GetReferenceWithAmbiguousRefs(t *testing.T) {
diff --git a/internal/git/remoterepo/repository.go b/internal/git/remoterepo/repository.go
index 631fcbb..1641a3a 100644
--- a/internal/git/remoterepo/repository.go
+++ b/internal/git/remoterepo/repository.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
+ "strings"
"sync"
"github.com/feder-cr/git-ai/internal/git"
@@ -120,11 +121,33 @@ func (rr *Repo) ResolveReference(ctx context.Context, name git.ReferenceName) (g
return rr.ResolveRevision(ctx, git.Revision(target)+"^{commit}")
}
-// ReferenceExists will dial to the remote repository and report whether the reference exists under
-// its exact name name, with no DWIM rule.
-func (rr *Repo) ReferenceExists(ctx context.Context, name git.ReferenceName) (bool, error) {
- target, err := rr.referenceTarget(ctx, name)
- return target != "", err
+// ReadReference will dial to the remote repository and read the reference named name by its exact
+// name, to the commit it points to, or return git.ErrReferenceNotFound when it does not exist (a
+// dangling symbolic reference included) or does not peel to a commit. RefExists checks the exact
+// name (show-ref --verify, without listing the references below it), and only then FindCommit
+// resolves it, by the full name, which is the first name git's DWIM rules try. Of the root
+// references, which RefExists does not take, only HEAD is read, by FindCommit: a dangling HEAD falls
+// through git's rules there.
+func (rr *Repo) ReadReference(ctx context.Context, name git.ReferenceName) (git.ObjectID, error) {
+ if !strings.HasPrefix(name.String(), "refs/") {
+ if name != "HEAD" {
+ return "", git.ErrReferenceNotFound
+ }
+ return rr.ResolveRevision(ctx, name.Revision())
+ }
+
+ resp, err := gitalypb.NewRefServiceClient(rr.conn).RefExists(ctx, &gitalypb.RefExistsRequest{
+ Repository: rr.Repository,
+ Ref: []byte(name),
+ })
+ if err != nil {
+ return "", fmt.Errorf("ref exists: %w", err)
+ }
+ if !resp.GetValue() {
+ return "", git.ErrReferenceNotFound
+ }
+
+ return rr.ResolveRevision(ctx, name.Revision())
}
// referenceTarget returns the object ID that the reference named name points to, read by its exact
diff --git a/internal/gitaly/service/operations/branch_exact_test.go b/internal/gitaly/service/operations/branch_exact_test.go
index 2dfe156..0fbc393 100644
--- a/internal/gitaly/service/operations/branch_exact_test.go
+++ b/internal/gitaly/service/operations/branch_exact_test.go
@@ -731,7 +731,21 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {
desc string
start func(setup cherryPickOrRevertSetup) string
decoy func(setup cherryPickOrRevertSetup) git.ReferenceName
+ // branch, when set, is a branch at base that the start names.
+ branch string
}{
+ {
+ desc: "feature/login with refs/feature/login",
+ start: func(cherryPickOrRevertSetup) string { return "feature/login" },
+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return "refs/feature/login" },
+ branch: "feature/login",
+ },
+ {
+ desc: "a branch ORIG_HEAD with a tag ORIG_HEAD",
+ start: func(cherryPickOrRevertSetup) string { return "ORIG_HEAD" },
+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return "refs/tags/ORIG_HEAD" },
+ branch: "ORIG_HEAD",
+ },
{
desc: "HEAD with a branch named HEAD",
start: func(cherryPickOrRevertSetup) string { return "HEAD" },
@@ -779,6 +793,9 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {
t.Parallel()
setup := setupCherryPickOrRevert(t, ctx, cfg)
+ if tc.branch != "" {
+ gittest.WriteRef(t, cfg, setup.repoPath, git.NewReferenceNameFromBranchName(tc.branch), setup.base)
+ }
if decoy := tc.decoy(setup); decoy != "" {
writeDecoy(t, cfg, setup.repoPath, decoy, baseFile)
}
@@ -789,6 +806,42 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {
})
}
+ t.Run("cherry-pick, a dangling symbolic branch by its full name", func(t *testing.T) {
+ t.Parallel()
+
+ // refs/heads/x points to a branch that does not exist: it has no value, and never resolves
+ // through the decoy refs/refs/heads/x that git's rules would try after it.
+ setup := setupCherryPickOrRevert(t, ctx, cfg)
+ gittest.Exec(t, cfg, "-C", setup.repoPath, "symbolic-ref", "refs/heads/x", "refs/heads/nope")
+ writeDecoy(t, cfg, setup.repoPath, "refs/refs/heads/x", baseFile)
+
+ _, err := cherryPick(setup, "refs/heads/x")
+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)
+ require.ErrorContains(t, err, "resolve start ref")
+ })
+
+ t.Run("rebase onto a remote branch with refs/<branch>", func(t *testing.T) {
+ t.Parallel()
+
+ setup := setupRebasableRepositories(t, ctx, cfg, true)
+ writeDecoy(t, cfg, setup.remoteRepoPath, git.ReferenceName("refs/"+setup.remoteBranch))
+
+ stream, err := client.UserRebaseConfirmable(ctx)
+ require.NoError(t, err)
+ require.NoError(t, stream.Send(buildUserRebaseConfirmableHeaderRequest(setup.localRepo, gittest.TestUser, "1",
+ setup.localBranch, setup.localCommit, setup.remoteRepo, setup.remoteBranch)))
+ first, err := stream.Recv()
+ require.NoError(t, err)
+ require.NoError(t, stream.Send(buildUserRebaseConfirmableApplyRequest(true)))
+ _, err = stream.Recv()
+ require.NoError(t, err)
+ _, err = stream.Recv()
+ require.Equal(t, io.EOF, err)
+
+ require.Equal(t, setup.remoteCommit.String(), parentsOf(t, cfg, setup.localRepoPath, first.GetRebaseSha()),
+ "the remote branch beats refs/<branch> of the same name")
+ })
+
t.Run("cherry-pick, main:base, a blob, fails", func(t *testing.T) {
t.Parallel()
@@ -821,11 +874,12 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {
})
}
-// TestResolveStartBranch checks the rule of resolveStartBranch over lookups of a fake repository:
-// git's resolution, but an existing branch of the exact name beats refs/x and refs/tags/x. resolve
-// answers the revision it is given, so the expected value is the revision git is asked for; a name
-// that git reads before any reference (an object ID, a root reference, a revision without a name)
-// is never looked up.
+// TestResolveStartBranch checks the rule of resolveStartBranch over a fake repository: git's
+// resolution, but an existing branch of the exact name beats a reference with the same name
+// (refs/tags/x, refs/x), unless the name starts with a namespace git prefixes. read answers v(ref)
+// for every reference that exists, and resolve answers the revision it is given, so the expected
+// value is the revision git is asked for: the value read, with the suffix. A name that git reads
+// before any reference (an object ID, a revision without a name) is never looked up.
func TestResolveStartBranch(t *testing.T) {
t.Parallel()
@@ -837,34 +891,43 @@ func TestResolveStartBranch(t *testing.T) {
// noLookup tells that the name must not be looked up as a reference.
noLookup bool
}{
- {name: "main", refs: []string{"refs/heads/main"}, expected: "refs/heads/main^{commit}"},
- {name: "main", refs: []string{"refs/tags/main", "refs/heads/main"}, expected: "refs/heads/main^{commit}"},
- {name: "main", refs: []string{"refs/main", "refs/heads/main"}, expected: "refs/heads/main^{commit}"},
- {name: "main", refs: []string{"refs/tags/main"}, expected: "refs/tags/main^{commit}"},
- {name: "main", refs: []string{"refs/main"}, expected: "refs/main^{commit}"},
- {name: "main", refs: []string{"refs/heads/main", "refs/remotes/main"}, expected: "refs/heads/main^{commit}"},
- {name: "heads/main", refs: []string{"refs/heads/main", "refs/heads/heads/main"}, expected: "refs/heads/main^{commit}"},
- {name: "tags/v1", refs: []string{"refs/tags/v1"}, expected: "refs/tags/v1^{commit}"},
- // A name that names its namespace follows git, whatever branch has that name.
- {name: "tags/v1", refs: []string{"refs/tags/v1", "refs/heads/tags/v1"}, expected: "refs/tags/v1^{commit}"},
+ {name: "main", refs: []string{"refs/heads/main"}, expected: "v(refs/heads/main)^{commit}"},
+ {name: "main", refs: []string{"refs/tags/main", "refs/heads/main"}, expected: "v(refs/heads/main)^{commit}"},
+ {name: "main", refs: []string{"refs/main", "refs/heads/main"}, expected: "v(refs/heads/main)^{commit}"},
+ {name: "main", refs: []string{"refs/tags/main"}, expected: "v(refs/tags/main)^{commit}"},
+ {name: "main", refs: []string{"refs/main"}, expected: "v(refs/main)^{commit}"},
+ {name: "main", refs: []string{"refs/heads/main", "refs/remotes/main"}, expected: "v(refs/heads/main)^{commit}"},
+ // A branch with a slash beats a reference with the same name too.
+ {name: "feature/login", refs: []string{"refs/feature/login", "refs/heads/feature/login"}, expected: "v(refs/heads/feature/login)^{commit}"},
+ {name: "a/b", refs: []string{"refs/a/b", "refs/heads/a/b"}, expected: "v(refs/heads/a/b)^{commit}"},
+ {name: "a/b", refs: []string{"refs/tags/a/b", "refs/heads/a/b"}, expected: "v(refs/heads/a/b)^{commit}"},
+ {name: "a/b", refs: []string{"refs/a/b"}, expected: "v(refs/a/b)^{commit}"},
+ // A name that starts with a namespace git prefixes names it, and follows git.
+ {name: "heads/main", refs: []string{"refs/heads/main", "refs/heads/heads/main"}, expected: "v(refs/heads/main)^{commit}"},
+ {name: "tags/v1", refs: []string{"refs/tags/v1"}, expected: "v(refs/tags/v1)^{commit}"},
+ {name: "tags/v1", refs: []string{"refs/tags/v1", "refs/heads/tags/v1"}, expected: "v(refs/tags/v1)^{commit}"},
{
name: "remotes/origin/main",
refs: []string{"refs/remotes/origin/main", "refs/heads/remotes/origin/main"},
- expected: "refs/remotes/origin/main^{commit}",
+ expected: "v(refs/remotes/origin/main)^{commit}",
},
- {name: "a/b", refs: []string{"refs/a/b", "refs/heads/a/b"}, expected: "refs/a/b^{commit}"},
- // A tag of the same name is beaten by the branch, with or without a namespace in the name.
- {name: "a/b", refs: []string{"refs/tags/a/b", "refs/heads/a/b"}, expected: "refs/heads/a/b^{commit}"},
- {name: "origin/x", refs: []string{"refs/remotes/origin/x"}, expected: "refs/remotes/origin/x^{commit}"},
- {name: "origin", refs: []string{"refs/remotes/origin/HEAD"}, expected: "refs/remotes/origin/HEAD^{commit}"},
- {name: "main~1", refs: []string{"refs/tags/main", "refs/heads/main"}, expected: "refs/heads/main~1^{commit}"},
- {name: "main:file", refs: []string{"refs/heads/main"}, expected: "refs/heads/main:file^{commit}"},
- {name: "refs/tags/v1^{}", refs: []string{"refs/tags/v1"}, expected: "refs/tags/v1^{}^{commit}"},
+ {name: "origin/x", refs: []string{"refs/remotes/origin/x"}, expected: "v(refs/remotes/origin/x)^{commit}"},
+ {name: "origin", refs: []string{"refs/remotes/origin/HEAD"}, expected: "v(refs/remotes/origin/HEAD)^{commit}"},
+ // The suffix applies to the value read.
+ {name: "main~1", refs: []string{"refs/tags/main", "refs/heads/main"}, expected: "v(refs/heads/main)~1^{commit}"},
+ {name: "main:file", refs: []string{"refs/heads/main"}, expected: "v(refs/heads/main):file^{commit}"},
+ {name: "refs/tags/v1^{}", refs: []string{"refs/tags/v1"}, expected: "v(refs/tags/v1)^{}^{commit}"},
+ // A reflog suffix needs the name, which is read again afterwards.
+ {name: "main@{1}", refs: []string{"refs/tags/main", "refs/heads/main"}, expected: "refs/heads/main@{1}^{commit}"},
{name: "refs/heads/x", refs: []string{"refs/refs/heads/x"}, expected: "not found"},
{name: "abc1234", expected: "abc1234^{commit}"},
{name: "@", expected: "@^{commit}"},
- {name: "HEAD", refs: []string{"refs/heads/HEAD"}, expected: "HEAD^{commit}", noLookup: true},
- {name: "FETCH_HEAD~1", refs: []string{"refs/heads/FETCH_HEAD"}, expected: "FETCH_HEAD~1^{commit}", noLookup: true},
+ // A root reference that exists comes first; one that does not, such as a dangling HEAD, follows
+ // the rules of a bare name.
+ {name: "HEAD", refs: []string{"HEAD", "refs/heads/HEAD"}, expected: "v(HEAD)^{commit}"},
+ {name: "HEAD", refs: []string{"refs/heads/HEAD"}, expected: "v(refs/heads/HEAD)^{commit}"},
+ {name: "FETCH_HEAD~1", refs: []string{"FETCH_HEAD", "refs/heads/FETCH_HEAD"}, expected: "v(FETCH_HEAD)~1^{commit}"},
+ {name: "ORIG_HEAD", refs: []string{"refs/tags/ORIG_HEAD", "refs/heads/ORIG_HEAD"}, expected: "v(refs/heads/ORIG_HEAD)^{commit}"},
{name: sha, refs: []string{"refs/heads/" + sha}, expected: sha + "^{commit}", noLookup: true},
{name: strings.ToUpper(sha), refs: []string{"refs/heads/" + strings.ToUpper(sha)}, expected: strings.ToUpper(sha) + "^{commit}", noLookup: true},
{name: sha + "~0", refs: []string{"refs/heads/" + sha}, expected: sha + "~0^{commit}", noLookup: true},
@@ -878,15 +941,18 @@ func TestResolveStartBranch(t *testing.T) {
refs[git.ReferenceName(ref)] = true
}
var lookups []git.ReferenceName
- exists := func(name git.ReferenceName) (bool, error) {
+ read := func(name git.ReferenceName) (git.ObjectID, error) {
lookups = append(lookups, name)
- return refs[name], nil
+ if !refs[name] {
+ return "", git.ErrReferenceNotFound
+ }
+ return git.ObjectID("v(" + name + ")"), nil
}
resolve := func(revision git.Revision) (git.ObjectID, error) {
return git.ObjectID(revision), nil
}
- resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, exists, resolve)
+ resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, read, resolve)
if tc.expected == "not found" {
require.ErrorIs(t, err, git.ErrReferenceNotFound)
} else {
@@ -898,6 +964,23 @@ func TestResolveStartBranch(t *testing.T) {
}
})
}
+
+ t.Run("a reference that changes while its reflog is read", func(t *testing.T) {
+ reads := 0
+ read := func(name git.ReferenceName) (git.ObjectID, error) {
+ if name != "refs/heads/main" {
+ return "", git.ErrReferenceNotFound
+ }
+ reads++
+ return git.ObjectID(fmt.Sprintf("v%d", reads)), nil
+ }
+ resolve := func(revision git.Revision) (git.ObjectID, error) {
+ return git.ObjectID(revision), nil
+ }
+
+ _, err := resolveStartBranch("main@{1}", git.ObjectHashSHA1, read, resolve)
+ require.ErrorContains(t, err, "changed while its reflog was read")
+ })
}
// TestSplitRevisionSuffix checks the split of a start revision into its name and its suffix.
diff --git a/internal/gitaly/service/operations/revert.go b/internal/gitaly/service/operations/revert.go
index ebfbe50..1e0713a 100644
--- a/internal/gitaly/service/operations/revert.go
+++ b/internal/gitaly/service/operations/revert.go
@@ -208,95 +208,111 @@ func (s *Server) UserRevert(ctx context.Context, req *gitalypb.UserRevertRequest
// resolveStartBranch resolves the start branch name of a request, a revision, to its commit, as
// git resolves it with one deviation. objectHash is the object format of the repository the start
-// branch is read from; exists reports whether a reference exists there under its exact name, and
+// branch is read from; read returns the value of a reference there, read by its exact name
+// (git.ErrReferenceNotFound when it does not exist, a dangling symbolic reference included), and
// resolve is git's resolution of a revision there.
//
// The revision is split into the name it starts with and its suffix (~1, ^{}, @{1}, :path). git
-// takes a full object ID (in either case) for the object, a root reference such as HEAD or
-// FETCH_HEAD from the repository's directory, and any other name x by its DWIM rules, the first
-// that exists of refs/x, refs/tags/x, refs/heads/x, refs/remotes/x and refs/remotes/x/HEAD. The
-// one deviation: when that is a reference with the same name as the branch, the tag refs/tags/x or,
-// when x names no namespace (no /), refs/x, and the branch refs/heads/x exists, the branch is taken.
-// An existing branch of the exact name beats a non-branch reference of the same name, such as a tag
-// an agent pushed to shadow it; a name such as tags/v1 or remotes/origin/main names its namespace,
-// and everything else follows git. When
-// no reference is named x, git's resolution answers, by design: a SHA (abbreviated) or another
-// revision keeps working as a start point, as before.
+// takes a full object ID (in either case) for the object; a root reference such as HEAD or
+// FETCH_HEAD, when it exists, from the repository's directory (git reads other upper-case files
+// there too, such as AUTO_MERGE, but a push cannot write them); and any other name x by its DWIM
+// rules, the first that exists of refs/x, refs/tags/x, refs/heads/x, refs/remotes/x and
+// refs/remotes/x/HEAD. The one deviation: when that is a reference with the same name as the
+// branch, the tag refs/tags/x or refs/x, and the branch refs/heads/x exists, the branch is taken. An
+// existing branch of the exact name beats a non-branch reference of the same name, such as a tag an
+// agent pushed to shadow it. A name that starts with a namespace git itself prefixes (heads/, tags/,
+// remotes/) names it, and follows git, as everything else does. When no reference is named x,
+// git's resolution answers, by design: an abbreviated SHA or another revision keeps working as a
+// start point, as before. A full reference name (refs/...) is read exactly as given, with no
+// fallback: a missing refs/heads/x does not resolve through refs/refs/heads/x or another decoy.
//
-// A full reference name (refs/...) is read exactly as given, with no fallback: a missing
-// refs/heads/x does not resolve through refs/refs/heads/x or another decoy. The suffix applies to
-// the reference that was chosen, by its full name: that is the first name git's DWIM rules try, so
-// an existing reference is read exactly.
+// The chosen reference is read once, to its value, and the suffix applies to that object ID: no
+// rule resolves the name again, so a reference that is dangling, or that goes away meanwhile, never
+// yields a decoy. A reflog suffix (@{n}) needs the name: it is resolved by the full name, and the
+// reference must still have the value read.
func resolveStartBranch(
name string,
objectHash git.ObjectHash,
- exists func(git.ReferenceName) (bool, error),
+ read func(git.ReferenceName) (git.ObjectID, error),
resolve func(git.Revision) (git.ObjectID, error),
) (git.ObjectID, error) {
- asGit := func() (git.ObjectID, error) { return resolve(git.Revision(name + "^{commit}")) }
-
base, suffix := splitRevisionSuffix(name)
- switch {
// A revision that starts with its suffix (@{-1}, :path) names no reference.
- case base == "", isRootReference(base), isFullObjectID(base, objectHash):
- return asGit()
- case strings.HasPrefix(base, "refs/"):
- found, err := exists(git.ReferenceName(base))
- if err != nil {
- return "", err
- }
- if !found {
- return "", git.ErrReferenceNotFound
- }
- return resolve(git.Revision(base + suffix + "^{commit}"))
+ if base == "" || isFullObjectID(base, objectHash) {
+ return resolve(git.Revision(name + "^{commit}"))
+ }
+
+ reference, value, err := startReference(base, read)
+ switch {
+ case err != nil:
+ return "", err
+ case reference == "" && strings.HasPrefix(base, "refs/"):
+ return "", git.ErrReferenceNotFound
+ case reference == "":
+ return resolve(git.Revision(name + "^{commit}"))
+ case !strings.Contains(suffix, "@{"):
+ return resolve(git.Revision(value.String() + suffix + "^{commit}"))
}
- chosen, err := startReference(base, exists)
+ commit, err := resolve(git.Revision(reference.String() + suffix + "^{commit}"))
+ if err != nil {
+ return "", err
+ }
+ again, err := read(reference)
if err != nil {
return "", err
}
- if chosen == "" {
- return asGit()
+ if again != value {
+ return "", fmt.Errorf("reference %q changed while its reflog was read", reference)
}
- return resolve(git.Revision(chosen.String() + suffix + "^{commit}"))
+ return commit, nil
}
-// startReference returns the reference that git's DWIM rules resolve the bare name to, with the
-// deviation of resolveStartBranch, or an empty name when there is none.
-func startReference(name string, exists func(git.ReferenceName) (bool, error)) (git.ReferenceName, error) {
+// startReference returns the reference that git resolves the name to, with the deviation of
+// resolveStartBranch, and its value; an empty name when there is none.
+func startReference(name string, read func(git.ReferenceName) (git.ObjectID, error)) (git.ReferenceName, git.ObjectID, error) {
+ if strings.HasPrefix(name, "refs/") {
+ value, err := read(git.ReferenceName(name))
+ if errors.Is(err, git.ErrReferenceNotFound) {
+ return "", "", nil
+ }
+ return git.ReferenceName(name), value, err
+ }
+
branch := git.ReferenceName("refs/heads/" + name)
other := git.ReferenceName("refs/" + name)
tag := git.ReferenceName("refs/tags/" + name)
- for _, candidate := range []git.ReferenceName{
- other, tag, branch, git.ReferenceName("refs/remotes/" + name), git.ReferenceName("refs/remotes/" + name + "/HEAD"),
- } {
- found, err := exists(candidate)
- if err != nil {
- return "", err
- }
- if !found {
+ candidates := []git.ReferenceName{other, tag, branch, git.ReferenceName("refs/remotes/" + name), git.ReferenceName("refs/remotes/" + name + "/HEAD")}
+ if isRootReference(name) {
+ candidates = append([]git.ReferenceName{git.ReferenceName(name)}, candidates...)
+ }
+ namesNamespace := strings.HasPrefix(name, "heads/") || strings.HasPrefix(name, "tags/") || strings.HasPrefix(name, "remotes/")
+
+ for _, candidate := range candidates {
+ value, err := read(candidate)
+ if errors.Is(err, git.ErrReferenceNotFound) {
continue
}
- // The deviation applies to a reference with the same name as the branch: the tag
- // refs/tags/x, or refs/x when x names no namespace. A name such as tags/v1 or
- // remotes/origin/main names its namespace, and follows git.
- if candidate == tag || (candidate == other && !strings.Contains(name, "/")) {
- isBranch, err := exists(branch)
- if err != nil {
- return "", err
+ if err != nil {
+ return "", "", err
+ }
+ if !namesNamespace && (candidate == other || candidate == tag) {
+ branchValue, err := read(branch)
+ if err == nil {
+ return branch, branchValue, nil
}
- if isBranch {
- return branch, nil
+ if !errors.Is(err, git.ErrReferenceNotFound) {
+ return "", "", err
}
}
- return candidate, nil
+ return candidate, value, nil
}
- return "", nil
+ return "", "", nil
}
// isRootReference reports whether name has the syntax of a root reference, which git reads from
-// the repository's directory before any DWIM rule: HEAD, or upper-case letters and underscores
-// ending in _HEAD (FETCH_HEAD, ORIG_HEAD, MERGE_HEAD, ...).
+// the repository's directory before any DWIM rule when it exists: HEAD, or upper-case letters and
+// underscores ending in _HEAD (FETCH_HEAD, ORIG_HEAD, MERGE_HEAD, ...).
func isRootReference(name string) bool {
if name == "HEAD" {
return true
@@ -349,8 +365,8 @@ func (s *Server) fetchStartRevision(
// The start branch is read in the start repository, or in the local one without it.
objectHashOf := localRepo.ObjectHash
- exists := func(name git.ReferenceName) (bool, error) {
- return localRepo.ReferenceExists(ctx, name)
+ read := func(name git.ReferenceName) (git.ObjectID, error) {
+ return localRepo.ResolveReferenceExactly(ctx, name)
}
resolve := func(revision git.Revision) (git.ObjectID, error) {
return localRepo.ResolveRevision(ctx, revision)
@@ -361,8 +377,8 @@ func (s *Server) fetchStartRevision(
return "", structerr.NewInternal("%w", err)
}
objectHashOf = remoteRepo.ObjectHash
- exists = func(name git.ReferenceName) (bool, error) {
- return remoteRepo.ReferenceExists(ctx, name)
+ read = func(name git.ReferenceName) (git.ObjectID, error) {
+ return remoteRepo.ReadReference(ctx, name)
}
resolve = func(revision git.Revision) (git.ObjectID, error) {
return remoteRepo.ResolveRevision(ctx, revision)
@@ -373,7 +389,7 @@ func (s *Server) fetchStartRevision(
return "", structerr.NewInternal("detecting object hash: %w", err)
}
- startRevision, err := resolveStartBranch(string(startBranchName), objectHash, exists, resolve)
+ startRevision, err := resolveStartBranch(string(startBranchName), objectHash, read, resolve)
if err != nil {
return "", structerr.NewInvalidArgument("resolve start ref: %w", err)
}