Git designed for AI agents.
operations: the start branch follows git, but for a branch of the exact name
Federico Elia6c8ff51a9a0e
diff --git a/internal/git/localrepo/refs.go b/internal/git/localrepo/refs.goindex d80f762..9ffeae6 100644--- a/internal/git/localrepo/refs.go+++ b/internal/git/localrepo/refs.go@@ -171,7 +171,8 @@ func (repo *Repo) ResolveBranchesExactly(ctx context.Context, reader catfile.Obj// ResolveBranchesExactly is the peeled form, for the callers that want the commit.//// show-ref --verify reads the one reference, where for-each-ref <reference> lists every loose-// reference of its directory (50,000 loose branches: 250 ms against 3 ms).+// reference of its directory (50,000 loose branches: 250 ms against 3 ms). A reference whose+// object is missing yields its value too, as rev-parse does: it can still be deleted.func (repo *Repo) ResolveReferenceExactly(ctx context.Context, reference git.ReferenceName) (git.ObjectID, error) {var stdout, stderr bytes.Bufferif err := repo.ExecAndWait(ctx, gitcmd.Command{@@ -180,9 +181,15 @@ func (repo *Repo) ResolveReferenceExactly(ctx context.Context, reference git.RefArgs: []string{reference.String()},}, gitcmd.WithStdout(&stdout), gitcmd.WithStderr(&stderr)); err != nil {// show-ref --verify exits 128 with "not a valid ref" for a reference that does not- // exist or whose name is not valid; anything else is a failure.- if code, ok := command.ExitStatus(err); ok && code == 128 && strings.Contains(stderr.String(), "not a valid ref") {- return "", git.ErrReferenceNotFound+ // exist or whose name is not valid, and with "bad ref <reference> (<object ID>)" for one+ // whose object is missing; anything else is a failure.+ if code, ok := command.ExitStatus(err); ok && code == 128 {+ if strings.Contains(stderr.String(), "not a valid ref") {+ return "", git.ErrReferenceNotFound+ }+ if value, ok := badReferenceValue(stderr.String(), reference); ok {+ return value, nil+ }}return "", fmt.Errorf("show-ref %q: %w, stderr: %q", reference, err, stderr.String())}@@ -196,6 +203,40 @@ func (repo *Repo) ResolveReferenceExactly(ctx context.Context, reference git.Refreturn git.ObjectID(value), nil}+// badReferenceValue returns the value that show-ref --verify reports for reference in stderr when+// the object of the reference is missing: "fatal: git show-ref: bad ref <reference> (<object ID>)".+func badReferenceValue(stderr string, reference git.ReferenceName) (git.ObjectID, bool) {+ _, rest, ok := strings.Cut(stderr, "bad ref "+reference.String()+" (")+ if !ok {+ return "", false+ }+ value, _, ok := strings.Cut(rest, ")")+ if !ok || value == "" {+ return "", false+ }+ 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) {@@ -433,13 +474,13 @@ func (repo *Repo) GetDefaultBranch(ctx context.Context) (git.ReferenceName, errofor _, headCandidate := range []git.ReferenceName{headReference, git.DefaultRef, git.LegacyDefaultRef,} {- if _, err := repo.ResolveReferenceExactly(ctx, headCandidate); err != nil {- if errors.Is(err, git.ErrReferenceNotFound) {- continue- }+ exists, err := repo.ReferenceExists(ctx, headCandidate)+ if err != nil {return "", err}- return headCandidate, nil+ if exists {+ return headCandidate, nil+ }}// If all else fails, return the first branch namediff --git a/internal/git/localrepo/refs_test.go b/internal/git/localrepo/refs_test.goindex c02599b..9c5f5af 100644--- a/internal/git/localrepo/refs_test.go+++ b/internal/git/localrepo/refs_test.go@@ -204,6 +204,10 @@ func TestRepo_ResolveReferenceExactly(t *testing.T) {// git writes only commits to branches; another reference may hold the tag itself.gittest.WriteRef(t, cfg, repoPath, "refs/keep/at-tag", tag)gittest.Exec(t, cfg, "-C", repoPath, "symbolic-ref", "refs/heads/symbolic", "refs/heads/main")+ // A branch whose object is missing still has its value.+ 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:])))for _, tc := range []struct {reference git.ReferenceName@@ -216,6 +220,7 @@ func TestRepo_ResolveReferenceExactly(t *testing.T) {{reference: "refs/heads/x*", expectedErr: git.ErrReferenceNotFound},{reference: "refs/heads/main~1", expectedErr: git.ErrReferenceNotFound},{reference: "refs/keep/at-tag", expected: tag},+ {reference: "refs/heads/broken", expected: broken},{reference: "refs/heads/symbolic", expected: commit},} {t.Run(tc.reference.String(), func(t *testing.T) {@@ -251,6 +256,48 @@ func TestRepo_GetDefaultBranchReadsCandidatesExactly(t *testing.T) {require.Equal(t, git.LegacyDefaultRef, defaultBranch)})}++ t.Run("HEAD's branch at a missing object", func(t *testing.T) {+ t.Parallel()++ // The branch exists, so it is the default branch, whatever it points to.+ cfg, repo, repoPath := setupRepo(t, withDisabledHooks())+ gittest.Exec(t, cfg, "-C", repoPath, "symbolic-ref", "HEAD", "refs/heads/main")+ broken := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))+ require.NoError(t, os.Remove(filepath.Join(repoPath, "objects", broken.String()[:2], broken.String()[2:])))++ defaultBranch, err := repo.GetDefaultBranch(ctx)+ 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())++ 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:])))++ 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)+ }}func TestRepo_GetReferenceWithAmbiguousRefs(t *testing.T) {diff --git a/internal/git/remoterepo/repository.go b/internal/git/remoterepo/repository.goindex 834a37c..631fcbb 100644--- a/internal/git/remoterepo/repository.go+++ b/internal/git/remoterepo/repository.go@@ -107,6 +107,30 @@ func (rr *Repo) ResolveBranch(ctx context.Context, branch string) (git.ObjectID,// git.ErrReferenceNotFound when the reference does not exist (also when references below its name// do) or does not peel to a commit.func (rr *Repo) ResolveReference(ctx context.Context, name git.ReferenceName) (git.ObjectID, error) {+ target, err := rr.referenceTarget(ctx, name)+ if err != nil {+ return "", err+ }+ if target == "" {+ return "", git.ErrReferenceNotFound+ }++ // The object ID read above, peeled as `<name>^{commit}` is: an object ID is never+ // resolved through a reference.+ 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+}++// referenceTarget returns the object ID that the reference named name points to, read by its exact+// name with ListRefs, or an empty string when it does not exist (also when references below its+// name do).+func (rr *Repo) referenceTarget(ctx context.Context, name git.ReferenceName) (string, error) {// ListRefs matches references below the pattern too: only the exact name counts.stream, err := gitalypb.NewRefServiceClient(rr.conn).ListRefs(ctx, &gitalypb.ListRefsRequest{Repository: rr.Repository,@@ -130,13 +154,8 @@ func (rr *Repo) ResolveReference(ctx context.Context, name git.ReferenceName) (g}}}- if target == "" {- return "", git.ErrReferenceNotFound- }- // The object ID read above, peeled as `<name>^{commit}` is: an object ID is never- // resolved through a reference.- return rr.ResolveRevision(ctx, git.Revision(target)+"^{commit}")+ return target, nil}// HasBranches will dial to the remote repository and check whether the repository has any branches.diff --git a/internal/gitaly/service/operations/branch_exact_test.go b/internal/gitaly/service/operations/branch_exact_test.goindex 535da3d..65b38a3 100644--- a/internal/gitaly/service/operations/branch_exact_test.go+++ b/internal/gitaly/service/operations/branch_exact_test.go@@ -4,6 +4,8 @@ import ("context""fmt""io"+ "os"+ "path/filepath""strings""testing"@@ -214,6 +216,25 @@ func TestUserDeleteBranchResolvesBranchesExactly(t *testing.T) {})}+ t.Run("a branch whose object is missing", func(t *testing.T) {+ t.Parallel()++ // The branch exists under its exact name, so it can be deleted, whatever it points to.+ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch))+ doomed := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("doomed"))+ gittest.WriteRef(t, cfg, repoPath, "refs/heads/broken", doomed)+ require.NoError(t, os.Remove(filepath.Join(repoPath, "objects", doomed.String()[:2], doomed.String()[2:])))++ _, err := client.UserDeleteBranch(ctx, &gitalypb.UserDeleteBranchRequest{+ Repository: repo,+ User: gittest.TestUser,+ BranchName: []byte("broken"),+ })+ require.NoError(t, err)+ require.Empty(t, exactReferenceValue(t, cfg, repoPath, "refs/heads/broken"), "the branch is deleted")+ })+t.Run("glob characters in the name", func(t *testing.T) {t.Parallel()@@ -702,6 +723,172 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {require.Equal(t, setup.remoteCommit.String(), parentsOf(t, cfg, setup.localRepoPath, first.GetRebaseSha()),"the rebase is onto the SHA, not onto the branch named like it")})++ // The names git resolves before refs/heads/<name>, each with a branch of that name as a decoy, and+ // a non-branch reference that a branch of the exact name beats.+ baseFile := gittest.TreeEntry{Path: "base", Mode: "100644", Content: "base\n"}+ for _, tc := range []struct {+ desc string+ start func(setup cherryPickOrRevertSetup) string+ decoy func(setup cherryPickOrRevertSetup) git.ReferenceName+ }{+ {+ desc: "HEAD with a branch named HEAD",+ start: func(cherryPickOrRevertSetup) string { return "HEAD" },+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return "refs/heads/HEAD" },+ },+ {+ desc: "heads/main with a branch named heads/main",+ start: func(cherryPickOrRevertSetup) string { return "heads/" + git.DefaultBranch },+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return "refs/heads/heads/" + git.DefaultBranch },+ },+ {+ desc: "an upper-case SHA with a branch named like it",+ start: func(setup cherryPickOrRevertSetup) string { return strings.ToUpper(setup.base.String()) },+ decoy: func(setup cherryPickOrRevertSetup) git.ReferenceName {+ return git.ReferenceName("refs/heads/" + strings.ToUpper(setup.base.String()))+ },+ },+ {+ desc: "SHA~0 with a branch named like the SHA",+ start: func(setup cherryPickOrRevertSetup) string { return setup.base.String() + "~0" },+ decoy: func(setup cherryPickOrRevertSetup) git.ReferenceName {+ return git.ReferenceName("refs/heads/" + setup.base.String())+ },+ },+ {+ desc: "main~0 with a tag named main",+ start: func(cherryPickOrRevertSetup) string { return git.DefaultBranch + "~0" },+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName {+ return git.ReferenceName("refs/tags/" + git.DefaultBranch)+ },+ },+ {+ desc: "main with refs/main",+ start: func(cherryPickOrRevertSetup) string { return git.DefaultBranch },+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return git.ReferenceName("refs/" + git.DefaultBranch) },+ },+ {+ // refs/heads/@ is not a valid reference name, so @ has no branch decoy.+ desc: "@, which is HEAD",+ start: func(cherryPickOrRevertSetup) string { return "@" },+ decoy: func(cherryPickOrRevertSetup) git.ReferenceName { return "" },+ },+ } {+ t.Run("cherry-pick, "+tc.desc, func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ if decoy := tc.decoy(setup); decoy != "" {+ writeDecoy(t, cfg, setup.repoPath, decoy, baseFile)+ }++ resp, err := cherryPick(setup, tc.start(setup))+ require.NoError(t, err)+ require.Equal(t, setup.base.String(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()))+ })+ }++ t.Run("cherry-pick, main:base, a blob, fails", func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ _, err := cherryPick(setup, git.DefaultBranch+":base")+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)+ require.ErrorContains(t, err, "resolve start ref")+ })++ t.Run("rebase onto heads/<branch> with a remote branch named heads/<branch>", func(t *testing.T) {+ t.Parallel()++ setup := setupRebasableRepositories(t, ctx, cfg, true)+ writeDecoy(t, cfg, setup.remoteRepoPath, git.ReferenceName("refs/heads/heads/"+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, "heads/"+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()),+ "heads/<branch> is the branch, as git resolves it, not the branch named heads/<branch>")+ })+}++// 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.+func TestResolveStartBranch(t *testing.T) {+ t.Parallel()++ sha := strings.Repeat("ab", 20)+ for _, tc := range []struct {+ name string+ refs []string+ expected string+ // 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}"},+ {name: "tags/v1", refs: []string{"refs/tags/v1", "refs/heads/tags/v1"}, expected: "refs/heads/tags/v1^{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: "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},+ {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},+ {name: "@{-1}", expected: "@{-1}^{commit}", noLookup: true},+ {name: ":path", expected: ":path^{commit}", noLookup: true},+ {name: "~1", expected: "~1^{commit}", noLookup: true},+ } {+ t.Run(tc.name+" with "+strings.Join(tc.refs, ","), func(t *testing.T) {+ refs := map[git.ReferenceName]bool{}+ for _, ref := range tc.refs {+ refs[git.ReferenceName(ref)] = true+ }+ var lookups []git.ReferenceName+ exists := func(name git.ReferenceName) (bool, error) {+ lookups = append(lookups, name)+ return refs[name], nil+ }+ resolve := func(revision git.Revision) (git.ObjectID, error) {+ return git.ObjectID(revision), nil+ }++ resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, exists, resolve)+ if tc.expected == "not found" {+ require.ErrorIs(t, err, git.ErrReferenceNotFound)+ } else {+ require.NoError(t, err)+ require.Equal(t, tc.expected, resolved.String())+ }+ if tc.noLookup {+ require.Empty(t, lookups, "the name is not looked up as a reference")+ }+ })+ }}// 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.goindex 1e30d59..3d0b466 100644--- a/internal/gitaly/service/operations/revert.go+++ b/internal/gitaly/service/operations/revert.go@@ -206,51 +206,111 @@ func (s *Server) UserRevert(ctx context.Context, req *gitalypb.UserRevertRequest}, nil}-// resolveStartBranch resolves the start branch name of a request, a revision, to its commit.-// objectHash is the object format of the repository the start branch is read from; exact reads a-// reference there by its exact name, peeled to its commit, and resolve is git's resolution of a-// revision there.+// 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+// resolve is git's resolution of a revision there.//-// git resolves a bare name x with its DWIM rules, to refs/tags/x before refs/heads/x, so a tag named-// like the start branch would answer for the branch. The revision is split into the name it starts-// with and its suffix (~1, ^{}, @{1}, :path), and the name is resolved by these rules:-// - a full object ID is the object, as git takes it, even when a reference is named like it;-// - 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;-// - any other name x is read as the branch refs/heads/x first. When there is no such branch, the-// revision is resolved as before this rule, by design: callers pass a SHA or a tag as a start-// point, and a missing branch keeps that DWIM resolution for compatibility.+// 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 refs/x or refs/tags/x, not a branch, 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; 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.//-// The suffix then applies to the reference that was read, by its full name: that is the first name-// git's DWIM rules try, so a reference that exists is read exactly.+// 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.func resolveStartBranch(name string,objectHash git.ObjectHash,- exact func(git.ReferenceName) (git.ObjectID, error),+ exists func(git.ReferenceName) (bool, 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)- if objectHash.ValidateHex(base) == nil {- return resolve(git.Revision(name + "^{commit}"))+ 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}"))}- reference := git.NewReferenceNameFromBranchName(base)- if strings.HasPrefix(base, "refs/") {- reference = git.ReferenceName(base)+ chosen, err := startReference(base, exists)+ if err != nil {+ return "", err+ }+ if chosen == "" {+ return asGit()}+ return resolve(git.Revision(chosen.String() + suffix + "^{commit}"))+}- commit, err := exact(reference)- switch {- case err == nil:- if suffix == "" {- 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) {+ 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}- return resolve(git.Revision(reference.String() + suffix + "^{commit}"))- case !errors.Is(err, git.ErrReferenceNotFound) || strings.HasPrefix(base, "refs/"):- return "", err- default:- return resolve(git.Revision(name + "^{commit}"))+ if !found {+ continue+ }+ if (candidate == other || candidate == tag) && !strings.HasPrefix(candidate.String(), "refs/heads/") {+ isBranch, err := exists(branch)+ if err != nil {+ return "", err+ }+ if isBranch {+ return branch, nil+ }+ }+ return candidate, 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, ...).+func isRootReference(name string) bool {+ if name == "HEAD" {+ return true}+ if !strings.HasSuffix(name, "_HEAD") {+ return false+ }+ for _, c := range name {+ if (c < 'A' || c > 'Z') && c != '_' {+ return false+ }+ }+ return true+}++// isFullObjectID reports whether name is a full object ID of objectHash's format, in either case,+// which git takes for the object.+func isFullObjectID(name string, objectHash git.ObjectHash) bool {+ return objectHash.ValidateHex(strings.ToLower(name)) == nil}// splitRevisionSuffix splits a revision into the name it starts with and the suffix that applies to@@ -284,8 +344,8 @@ func (s *Server) fetchStartRevision(// The start branch is read in the start repository, or in the local one without it.objectHashOf := localRepo.ObjectHash- exact := func(name git.ReferenceName) (git.ObjectID, error) {- return s.resolveBranchCommitExactly(ctx, localRepo, name)+ exists := func(name git.ReferenceName) (bool, error) {+ return localRepo.ReferenceExists(ctx, name)}resolve := func(revision git.Revision) (git.ObjectID, error) {return localRepo.ResolveRevision(ctx, revision)@@ -296,8 +356,8 @@ func (s *Server) fetchStartRevision(return "", structerr.NewInternal("%w", err)}objectHashOf = remoteRepo.ObjectHash- exact = func(name git.ReferenceName) (git.ObjectID, error) {- return remoteRepo.ResolveReference(ctx, name)+ exists = func(name git.ReferenceName) (bool, error) {+ return remoteRepo.ReferenceExists(ctx, name)}resolve = func(revision git.Revision) (git.ObjectID, error) {return remoteRepo.ResolveRevision(ctx, revision)@@ -308,7 +368,7 @@ func (s *Server) fetchStartRevision(return "", structerr.NewInternal("detecting object hash: %w", err)}- startRevision, err := resolveStartBranch(string(startBranchName), objectHash, exact, resolve)+ startRevision, err := resolveStartBranch(string(startBranchName), objectHash, exists, resolve)if err != nil {return "", structerr.NewInvalidArgument("resolve start ref: %w", err)}