Git designed for AI agents.
operations: read the branches of every RPC by their exact names
Federico Elia92cf3c15cf3a
diff --git a/internal/git/localrepo/refs.go b/internal/git/localrepo/refs.goindex 5dc087d..d43a6fc 100644--- a/internal/git/localrepo/refs.go+++ b/internal/git/localrepo/refs.go@@ -170,6 +170,29 @@ func (repo *Repo) ResolveBranchesExactly(ctx context.Context, reader catfile.Objreturn resolved, nil}+// ResolveReferenceExactly returns the object ID that reference points to, read by its exact name+// with one for-each-ref, or git.ErrReferenceNotFound when it does not exist (also when references+// below its name do, refs/heads/<x>/y). Unlike ResolveRevision, whose revision git resolves with+// its DWIM rules, a missing refs/heads/<x> never resolves through refs/tags/refs/heads/<x> or+// another reference. The value is not peeled: it is the value that a compare-and-swap of the+// reference expects, as `git rev-parse <reference>` returns it when the reference exists. A+// symbolic reference yields the object its target points to. ResolveBranchesExactly is the peeled+// form, for the callers that want the commit.+func (repo *Repo) ResolveReferenceExactly(ctx context.Context, reference git.ReferenceName) (git.ObjectID, error) {+ // A pattern also matches the references below it, so only the exact name counts.+ refs, err := repo.GetReferences(ctx, reference.String())+ if err != nil {+ return "", fmt.Errorf("reading %q: %w", reference, err)+ }+ for _, ref := range refs {+ if ref.Name == reference && ref.Target != "" {+ return git.ObjectID(ref.Target), nil+ }+ }++ return "", git.ErrReferenceNotFound+}+// 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) {diff --git a/internal/git/localrepo/refs_test.go b/internal/git/localrepo/refs_test.goindex c9bd365..993fd00 100644--- a/internal/git/localrepo/refs_test.go+++ b/internal/git/localrepo/refs_test.go@@ -183,6 +183,46 @@ func TestRepo_GetReference(t *testing.T) {}}+// TestRepo_ResolveReferenceExactly checks that a reference resolves only by its exact name, to its+// own value: a missing refs/heads/x never resolves through a reference that git's DWIM rules try+// after it, nor through a reference below its name; a reference at an annotated tag resolves to the+// tag, as rev-parse of the reference does; and a symbolic branch to the commit of its target.+func TestRepo_ResolveReferenceExactly(t *testing.T) {+ t.Parallel()++ ctx := testhelper.Context(t)+ cfg, repo, repoPath := setupRepo(t, withDisabledHooks())++ commit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))+ other := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("other"))+ for _, ref := range []git.ReferenceName{+ "refs/refs/heads/x", "refs/tags/refs/heads/x", "refs/heads/refs/heads/x", "refs/remotes/refs/heads/x", "refs/heads/x/y",+ } {+ gittest.WriteRef(t, cfg, repoPath, ref, other)+ }+ tag := gittest.WriteTag(t, cfg, repoPath, "annotated", commit.Revision(), gittest.WriteTagConfig{Message: "annotated"})+ // 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")++ for _, tc := range []struct {+ reference git.ReferenceName+ expected git.ObjectID+ expectedErr error+ }{+ {reference: "refs/heads/main", expected: commit},+ {reference: "refs/heads/x", expectedErr: git.ErrReferenceNotFound},+ {reference: "refs/keep/at-tag", expected: tag},+ {reference: "refs/heads/symbolic", expected: commit},+ } {+ t.Run(tc.reference.String(), func(t *testing.T) {+ oid, err := repo.ResolveReferenceExactly(ctx, tc.reference)+ require.Equal(t, tc.expectedErr, err)+ require.Equal(t, tc.expected, oid)+ })+ }+}+func TestRepo_GetReferenceWithAmbiguousRefs(t *testing.T) {t.Parallel()diff --git a/internal/gitaly/service/operations/apply_patch.go b/internal/gitaly/service/operations/apply_patch.goindex cc54fa0..4b6f256 100644--- a/internal/gitaly/service/operations/apply_patch.go+++ b/internal/gitaly/service/operations/apply_patch.go@@ -70,7 +70,9 @@ func (s *Server) userApplyPatch(ctx context.Context, header *gitalypb.UserApplyPreturn fmt.Errorf("detecting object hash: %w", err)}- parentCommitID, err := repo.ResolveRevision(ctx, targetBranch.Revision()+"^{commit}")+ // The branches are read by their exact names: a missing branch must not resolve through a tag+ // or another reference that git's DWIM rules would try after it.+ parentCommitID, err := s.resolveBranchCommitExactly(ctx, repo, targetBranch)if err != nil {if !errors.Is(err, git.ErrReferenceNotFound) {return fmt.Errorf("resolve target branch: %w", err)@@ -81,7 +83,7 @@ func (s *Server) userApplyPatch(ctx context.Context, header *gitalypb.UserApplyPreturn fmt.Errorf("default branch name: %w", err)}- parentCommitID, err = repo.ResolveRevision(ctx, defaultBranch.Revision()+"^{commit}")+ parentCommitID, err = s.resolveBranchCommitExactly(ctx, repo, defaultBranch)if errors.Is(err, git.ErrReferenceNotFound) {return errNoDefaultBranch} else if err != nil {diff --git a/internal/gitaly/service/operations/branch_exact_test.go b/internal/gitaly/service/operations/branch_exact_test.gonew file mode 100644index 0000000..fda9674--- /dev/null+++ b/internal/gitaly/service/operations/branch_exact_test.go@@ -0,0 +1,424 @@+package operations++import (+ "context"+ "fmt"+ "strings"+ "testing"++ "github.com/stretchr/testify/require"+ "google.golang.org/grpc/codes"+ "google.golang.org/protobuf/types/known/timestamppb"++ "github.com/feder-cr/git-ai/internal/featureflag"+ "github.com/feder-cr/git-ai/internal/git"+ "github.com/feder-cr/git-ai/internal/git/gittest"+ "github.com/feder-cr/git-ai/internal/git/localrepo"+ "github.com/feder-cr/git-ai/internal/gitaly/config"+ "github.com/feder-cr/git-ai/internal/testhelper"+ "github.com/feder-cr/git-ai/proto/go/gitalypb"+)++// The tests of this file check that the operations RPCs read their branches by their exact names,+// as TestUserCommitFilesResolvesBranchesExactly and TestUserLandResolvesBranchesExactly check for+// UserCommitFiles and UserLand. git resolves a revision with its DWIM rules:+// - a missing refs/heads/x resolves through refs/refs/heads/x, refs/tags/refs/heads/x,+// refs/heads/refs/heads/x or refs/remotes/refs/heads/x (exactBranchDecoys), so a request for a+// missing branch x would decide against the commit of such a reference (a tag an agent may+// create);+// - a bare branch name x resolves to refs/tags/x before refs/heads/x, so a tag named like an+// existing branch would answer for the branch (UserUpdateSubmodule took the parent of its+// commit from the bare name).+//+// A request must behave as if the decoy did not exist.++// exactBranchDecoys are the references that git's DWIM rules resolve refs/heads/x through when+// refs/heads/x does not exist.+var exactBranchDecoys = []git.ReferenceName{+ "refs/refs/heads/x", "refs/tags/refs/heads/x", "refs/heads/refs/heads/x", "refs/remotes/refs/heads/x",+}++// setupExactBranchService starts the operations service for a test of this file.+func setupExactBranchService(t *testing.T) (context.Context, config.Cfg, gitalypb.OperationServiceClient) {+ t.Helper()++ ctx := featureflag.OutgoingCtxWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false)+ return setupOperationsService(t, ctx)+}++// writeDecoy writes reference at a commit of its own, unrelated to the history of the branches,+// whose tree holds the given entries and a file named decoy, and returns the commit.+func writeDecoy(t *testing.T, cfg config.Cfg, repoPath string, reference git.ReferenceName, entries ...gittest.TreeEntry) git.ObjectID {+ t.Helper()++ entries = append(entries, gittest.TreeEntry{Path: "decoy", Mode: "100644", Content: "decoy\n"})+ commit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("decoy"), gittest.WithTreeEntries(entries...))+ gittest.WriteRef(t, cfg, repoPath, reference, commit)+ return commit+}++// exactReferenceValue returns the value of reference, read by its exact name, or an empty string+// when it does not exist.+func exactReferenceValue(t *testing.T, cfg config.Cfg, repoPath string, reference git.ReferenceName) string {+ t.Helper()++ output := gittest.Exec(t, cfg, "-C", repoPath, "for-each-ref", "--format=%(refname) %(objectname)", reference.String())+ for _, line := range strings.Split(strings.TrimSpace(string(output)), "\n") {+ if name, value, ok := strings.Cut(line, " "); ok && name == reference.String() {+ return value+ }+ }+ return ""+}++// requireDecoyUntouched checks that the request left the decoy where it was and created no branch x.+func requireDecoyUntouched(t *testing.T, cfg config.Cfg, repoPath string, decoy git.ReferenceName, decoyCommit git.ObjectID) {+ t.Helper()++ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, repoPath, decoy), "the decoy is untouched")+ require.Empty(t, exactReferenceValue(t, cfg, repoPath, "refs/heads/x"), "no branch x")+}++// parentsOf returns the parents of commit.+func parentsOf(t *testing.T, cfg config.Cfg, repoPath string, commit string) string {+ t.Helper()++ return strings.TrimSpace(string(gittest.Exec(t, cfg, "-C", repoPath, "log", "-1", "--format=%P", commit)))+}++// TestUserFFBranchResolvesBranchesExactly checks that UserFFBranch onto a missing branch fails as+// for a branch that does not exist, whatever decoy git's DWIM rules would take for it.+func TestUserFFBranchResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ for _, decoy := range exactBranchDecoys {+ t.Run(decoy.String(), func(t *testing.T) {+ t.Parallel()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch))+ decoyCommit := writeDecoy(t, cfg, repoPath, decoy)+ // A fast-forward of the decoy's commit.+ commit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(decoyCommit))++ _, err := client.UserFFBranch(ctx, &gitalypb.UserFFBranchRequest{+ Repository: repo,+ User: gittest.TestUser,+ CommitId: commit.String(),+ Branch: []byte("x"),+ })+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)+ require.ErrorContains(t, err, "reference not found")+ requireDecoyUntouched(t, cfg, repoPath, decoy, decoyCommit)+ })+ }+}++// TestUserMergeBranchResolvesBranchesExactly checks that UserMergeBranch into a missing branch is+// not found, whatever decoy git's DWIM rules would take for it.+func TestUserMergeBranchResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ for _, decoy := range exactBranchDecoys {+ t.Run(decoy.String(), func(t *testing.T) {+ t.Parallel()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch))+ decoyCommit := writeDecoy(t, cfg, repoPath, decoy)+ commit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(decoyCommit),+ gittest.WithTreeEntries(gittest.TreeEntry{Path: "merged", Mode: "100644", Content: "merged\n"}))++ stream, err := client.UserMergeBranch(ctx)+ require.NoError(t, err)+ require.NoError(t, stream.Send(&gitalypb.UserMergeBranchRequest{+ Repository: repo,+ User: gittest.TestUser,+ CommitId: commit.String(),+ Branch: []byte("x"),+ Message: []byte("merge into x"),+ }))+ _, err = stream.Recv()+ testhelper.RequireGrpcCode(t, err, codes.NotFound)+ requireDecoyUntouched(t, cfg, repoPath, decoy, decoyCommit)+ })+ }+}++// TestUserDeleteBranchResolvesBranchesExactly checks that UserDeleteBranch of a missing branch+// finds no branch, whatever decoy git's DWIM rules would take for it.+func TestUserDeleteBranchResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ for _, decoy := range exactBranchDecoys {+ t.Run(decoy.String(), func(t *testing.T) {+ t.Parallel()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch))+ decoyCommit := writeDecoy(t, cfg, repoPath, decoy)++ _, err := client.UserDeleteBranch(ctx, &gitalypb.UserDeleteBranchRequest{+ Repository: repo,+ User: gittest.TestUser,+ BranchName: []byte("x"),+ })+ testhelper.RequireGrpcCode(t, err, codes.FailedPrecondition)+ require.ErrorContains(t, err, `branch not found: "x"`)+ requireDecoyUntouched(t, cfg, repoPath, decoy, decoyCommit)+ })+ }+}++// cherryPickOrRevertSetup is a repository whose branch main is at base, with commit, a commit on+// base that adds the file picked, to cherry-pick, and commit's parent revert, which adds the file+// reverted, so that reverting commit's child is clean.+type cherryPickOrRevertSetup struct {+ repo *gitalypb.Repository+ repoPath string+ base git.ObjectID+ commit *gitalypb.GitCommit+}++func setupCherryPickOrRevert(t *testing.T, ctx context.Context, cfg config.Cfg, entries ...gittest.TreeEntry) cherryPickOrRevertSetup {+ t.Helper()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ base := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch),+ gittest.WithTreeEntries(append([]gittest.TreeEntry{{Path: "base", Mode: "100644", Content: "base\n"}}, entries...)...))+ commitID := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(base), gittest.WithTreeEntries(+ append([]gittest.TreeEntry{+ {Path: "base", Mode: "100644", Content: "base\n"},+ {Path: "picked", Mode: "100644", Content: "picked\n"},+ }, entries...)...))+ commit, err := localrepo.NewTestRepo(t, cfg, repo).ReadCommit(ctx, commitID.Revision())+ require.NoError(t, err)++ return cherryPickOrRevertSetup{repo: repo, repoPath: repoPath, base: base, commit: commit}+}++// TestUserCherryPickResolvesBranchesExactly checks that UserCherryPick reads its target branch by its+// exact name: onto a missing branch x it creates x from the start branch, whatever decoy git's DWIM+// rules would take for x.+func TestUserCherryPickResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ for _, decoy := range exactBranchDecoys {+ t.Run("missing branch, "+decoy.String(), func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ decoyCommit := writeDecoy(t, cfg, setup.repoPath, decoy)++ resp, err := client.UserCherryPick(ctx, &gitalypb.UserCherryPickRequest{+ Repository: setup.repo,+ User: gittest.TestUser,+ Commit: setup.commit,+ BranchName: []byte("x"),+ StartBranchName: []byte(git.DefaultBranch),+ Message: []byte("cherry-pick onto x"),+ })+ require.NoError(t, err)+ require.True(t, resp.GetBranchUpdate().GetBranchCreated())+ created := resp.GetBranchUpdate().GetCommitId()+ require.Equal(t, created, exactReferenceValue(t, cfg, setup.repoPath, "refs/heads/x"))+ require.Equal(t, setup.base.String(), parentsOf(t, cfg, setup.repoPath, created), "x starts from the start branch")+ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, setup.repoPath, decoy), "the decoy is untouched")+ })+ }+}++// TestUserRevertResolvesBranchesExactly is TestUserCherryPickResolvesBranchesExactly for+// UserRevert.+func TestUserRevertResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ // revertSetup moves main to the commit of the setup, which the request then reverts.+ revertSetup := func(t *testing.T) cherryPickOrRevertSetup {+ setup := setupCherryPickOrRevert(t, ctx, cfg)+ gittest.WriteRef(t, cfg, setup.repoPath, git.DefaultRef, git.ObjectID(setup.commit.GetId()))+ return setup+ }++ for _, decoy := range exactBranchDecoys {+ t.Run("missing branch, "+decoy.String(), func(t *testing.T) {+ t.Parallel()++ setup := revertSetup(t)+ decoyCommit := writeDecoy(t, cfg, setup.repoPath, decoy)++ resp, err := client.UserRevert(ctx, &gitalypb.UserRevertRequest{+ Repository: setup.repo,+ User: gittest.TestUser,+ Commit: setup.commit,+ BranchName: []byte("x"),+ StartBranchName: []byte(git.DefaultBranch),+ Message: []byte("revert onto x"),+ })+ require.NoError(t, err)+ require.True(t, resp.GetBranchUpdate().GetBranchCreated())+ created := resp.GetBranchUpdate().GetCommitId()+ require.Equal(t, created, exactReferenceValue(t, cfg, setup.repoPath, "refs/heads/x"))+ require.Equal(t, setup.commit.GetId(), parentsOf(t, cfg, setup.repoPath, created), "x starts from the start branch")+ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, setup.repoPath, decoy), "the decoy is untouched")+ })+ }+}++// TestUserUpdateSubmoduleResolvesBranchesExactly checks that UserUpdateSubmodule reads its branch by+// its exact name: a missing branch is not found whatever decoy git's DWIM rules would take for it,+// and a tag named like the branch is neither the parent nor the tree of the new commit.+func TestUserUpdateSubmoduleResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ setup := func(t *testing.T) (*gitalypb.Repository, string, git.ObjectID, git.ObjectID, gittest.TreeEntry) {+ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ subCommit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("sub"))+ submodule := gittest.TreeEntry{OID: subCommit, Mode: "160000", Path: "sub"}+ branchCommit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch), gittest.WithTreeEntries(submodule))+ newSubCommit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithMessage("new sub"), gittest.WithParents(subCommit))+ return repo, repoPath, branchCommit, newSubCommit, submodule+ }++ for _, decoy := range exactBranchDecoys {+ t.Run("missing branch, "+decoy.String(), func(t *testing.T) {+ t.Parallel()++ repo, repoPath, _, newSubCommit, submodule := setup(t)+ decoyCommit := writeDecoy(t, cfg, repoPath, decoy, submodule)++ _, err := client.UserUpdateSubmodule(ctx, &gitalypb.UserUpdateSubmoduleRequest{+ Repository: repo,+ User: gittest.TestUser,+ CommitSha: newSubCommit.String(),+ Branch: []byte("x"),+ Submodule: []byte("sub"),+ CommitMessage: []byte("update sub on x"),+ })+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)+ require.ErrorContains(t, err, "Cannot find branch")+ requireDecoyUntouched(t, cfg, repoPath, decoy, decoyCommit)+ })+ }++ t.Run("branch with a tag of its name", func(t *testing.T) {+ t.Parallel()++ repo, repoPath, branchCommit, newSubCommit, submodule := setup(t)+ writeDecoy(t, cfg, repoPath, git.ReferenceName("refs/tags/"+git.DefaultBranch), submodule)++ resp, err := client.UserUpdateSubmodule(ctx, &gitalypb.UserUpdateSubmoduleRequest{+ Repository: repo,+ User: gittest.TestUser,+ CommitSha: newSubCommit.String(),+ Branch: []byte(git.DefaultBranch),+ Submodule: []byte("sub"),+ CommitMessage: []byte("update sub"),+ })+ require.NoError(t, err)+ updated := resp.GetBranchUpdate().GetCommitId()+ require.Equal(t, branchCommit.String(), parentsOf(t, cfg, repoPath, updated), "the branch, not the tag of its name, is the parent")+ require.Equal(t, "sub\n", string(gittest.Exec(t, cfg, "-C", repoPath, "ls-tree", "--name-only", updated)), "the tree is the branch's")+ })+}++// exactBranchPatch is a patch of the file named file, from "change me" to "changed".+func exactBranchPatch(parent git.ObjectID) []byte {+ return []byte(fmt.Sprintf(`From %s Mon Sep 17 00:00:00 2001+From: Patch User <[email protected]>+Date: Thu, 18 Oct 2018 13:40:35 +0200+Subject: [PATCH] A commit from a patch++---+ file | 2 +-+ 1 file changed, 1 insertion(+), 1 deletion(-)++diff --git a/file b/file+index 3742e48..e40a3b9 100644+--- a/file++++ b/file+@@ -1 +1 @@+-change me++changed+--+2.19.1+`, parent))+}++// applyExactBranchPatch applies exactBranchPatch onto targetBranch.+func applyExactBranchPatch(t *testing.T, ctx context.Context, client gitalypb.OperationServiceClient, repo *gitalypb.Repository, targetBranch string, parent git.ObjectID) (*gitalypb.UserApplyPatchResponse, error) {+ t.Helper()++ stream, err := client.UserApplyPatch(ctx)+ require.NoError(t, err)+ require.NoError(t, stream.Send(&gitalypb.UserApplyPatchRequest{+ UserApplyPatchRequestPayload: &gitalypb.UserApplyPatchRequest_Header_{+ Header: &gitalypb.UserApplyPatchRequest_Header{+ Repository: repo,+ User: gittest.TestUser,+ TargetBranch: []byte(targetBranch),+ Timestamp: ×tamppb.Timestamp{Seconds: 1234512345},+ },+ },+ }))+ require.NoError(t, stream.Send(&gitalypb.UserApplyPatchRequest{+ UserApplyPatchRequestPayload: &gitalypb.UserApplyPatchRequest_Patches{Patches: exactBranchPatch(parent)},+ }))+ return stream.CloseAndRecv()+}++// TestUserApplyPatchResolvesBranchesExactly checks that UserApplyPatch reads its target branch and+// the default branch by their exact names: onto a missing branch x it creates x from the default+// branch, and without a default branch it fails as such, whatever decoy git's DWIM rules would+// take for either.+func TestUserApplyPatchResolvesBranchesExactly(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)+ file := gittest.TreeEntry{Path: "file", Mode: "100644", Content: "change me\n"}++ for _, decoy := range exactBranchDecoys {+ t.Run("missing branch, "+decoy.String(), func(t *testing.T) {+ t.Parallel()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ defaultCommit := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch(git.DefaultBranch), gittest.WithTreeEntries(file))+ decoyCommit := writeDecoy(t, cfg, repoPath, decoy, file)++ resp, err := applyExactBranchPatch(t, ctx, client, repo, "x", defaultCommit)+ require.NoError(t, err)+ require.True(t, resp.GetBranchUpdate().GetBranchCreated())+ created := resp.GetBranchUpdate().GetCommitId()+ require.Equal(t, created, exactReferenceValue(t, cfg, repoPath, "refs/heads/x"))+ require.Equal(t, defaultCommit.String(), parentsOf(t, cfg, repoPath, created), "x starts from the default branch")+ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, repoPath, decoy), "the decoy is untouched")+ })++ t.Run("missing default branch, "+strings.Replace(decoy.String(), "/x", "/"+git.DefaultBranch, 1), func(t *testing.T) {+ t.Parallel()++ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)+ // The repository has no branch, so its default branch is HEAD's, refs/heads/main, which+ // does not exist; the decoy is named for it.+ decoyRef := git.ReferenceName(strings.Replace(decoy.String(), "/x", "/"+git.DefaultBranch, 1))+ decoyCommit := writeDecoy(t, cfg, repoPath, decoyRef, file)++ _, err := applyExactBranchPatch(t, ctx, client, repo, "x", decoyCommit)+ require.ErrorContains(t, err, errNoDefaultBranch.Error())+ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, repoPath, decoyRef), "the decoy is untouched")+ require.Empty(t, exactReferenceValue(t, cfg, repoPath, "refs/heads/x"), "no branch x")+ })+ }+}diff --git a/internal/gitaly/service/operations/cherry_pick.go b/internal/gitaly/service/operations/cherry_pick.goindex 4a46950..5f17dfe 100644--- a/internal/gitaly/service/operations/cherry_pick.go+++ b/internal/gitaly/service/operations/cherry_pick.go@@ -146,7 +146,7 @@ func (s *Server) UserCherryPick(ctx context.Context, req *gitalypb.UserCherryPicWithMetadata("old_object_id", expectedOldOID)}} else {- oldrev, err = quarantineRepo.ResolveRevision(ctx, referenceName.Revision()+"^{commit}")+ oldrev, err = s.resolveBranchCommitExactly(ctx, quarantineRepo, referenceName)if errors.Is(err, git.ErrReferenceNotFound) {branchCreated = trueoldrev = objectHash.ZeroOIDdiff --git a/internal/gitaly/service/operations/ff_branch.go b/internal/gitaly/service/operations/ff_branch.goindex d94768f..14856b6 100644--- a/internal/gitaly/service/operations/ff_branch.go+++ b/internal/gitaly/service/operations/ff_branch.go@@ -55,7 +55,9 @@ func (s *Server) UserFFBranch(ctx context.Context, in *gitalypb.UserFFBranchRequWithMetadata("old_object_id", expectedOldOID)}} else {- revision, err = quarantineRepo.ResolveRevision(ctx, referenceName.Revision())+ // By its exact name: a missing branch must not resolve through a tag or another reference+ // that git's DWIM rules would try after it.+ revision, err = quarantineRepo.ResolveReferenceExactly(ctx, referenceName)if err != nil {return nil, structerr.NewInvalidArgument("%w", err)}diff --git a/internal/gitaly/service/operations/land.go b/internal/gitaly/service/operations/land.goindex 196bfa8..ab2f70d 100644--- a/internal/gitaly/service/operations/land.go+++ b/internal/gitaly/service/operations/land.go@@ -408,18 +408,12 @@ func (s *Server) landReferenceMoved(ctx context.Context, repo *localrepo.Repo, r// branches the same way (localrepo.ResolveBranchesExactly). A symbolic branch resolves to the commit// of its target.func (s *Server) landBranchTip(ctx context.Context, repo *localrepo.Repo, reference git.ReferenceName) (git.ObjectID, error) {- reader, release, err := s.catfileCache.ObjectInfoReader(ctx, repo)- if err != nil {- return "", fmt.Errorf("creating object info reader: %w", err)- }- defer release()-- branches, err := repo.ResolveBranchesExactly(ctx, reader, reference)- if err != nil {- return "", err+ tip, err := s.resolveBranchCommitExactly(ctx, repo, reference)+ if errors.Is(err, git.ErrReferenceNotFound) {+ return "", nil}- return branches[reference], nil+ return tip, err}// landMergeConflictError returns the FailedPrecondition error for a change that does not applydiff --git a/internal/gitaly/service/operations/merge_branch.go b/internal/gitaly/service/operations/merge_branch.goindex e853bb5..83afbf0 100644--- a/internal/gitaly/service/operations/merge_branch.go+++ b/internal/gitaly/service/operations/merge_branch.go@@ -74,7 +74,9 @@ func (s *Server) UserMergeBranch(stream gitalypb.OperationService_UserMergeBrancWithMetadata("old_object_id", expectedOldOID)}} else {- revision, err = quarantineRepo.ResolveRevision(ctx, referenceName.Revision())+ // By its exact name: a missing branch must not resolve through a tag or another reference+ // that git's DWIM rules would try after it.+ revision, err = quarantineRepo.ResolveReferenceExactly(ctx, referenceName)if err != nil {if errors.Is(err, git.ErrReferenceNotFound) {return structerr.NewNotFound("%w", err)diff --git a/internal/gitaly/service/operations/revert.go b/internal/gitaly/service/operations/revert.goindex f66f2eb..afb46b1 100644--- a/internal/gitaly/service/operations/revert.go+++ b/internal/gitaly/service/operations/revert.go@@ -152,7 +152,7 @@ func (s *Server) UserRevert(ctx context.Context, req *gitalypb.UserRevertRequestWithMetadata("old_object_id", expectedOldOID)}} else {- oldrev, err = quarantineRepo.ResolveRevision(ctx, referenceName.Revision()+"^{commit}")+ oldrev, err = s.resolveBranchCommitExactly(ctx, quarantineRepo, referenceName)if errors.Is(err, git.ErrReferenceNotFound) {branchCreated = trueoldrev = objectHash.ZeroOIDdiff --git a/internal/gitaly/service/operations/submodules.go b/internal/gitaly/service/operations/submodules.goindex f3d1f1c..cc2f0bc 100644--- a/internal/gitaly/service/operations/submodules.go+++ b/internal/gitaly/service/operations/submodules.go@@ -68,7 +68,9 @@ func (s *Server) UserUpdateSubmodule(ctx context.Context, req *gitalypb.UserUpdaWithMetadata("old_object_id", expectedOldOID)}} else {- oldOID, err = quarantineRepo.ResolveRevision(ctx, referenceName.Revision())+ // By its exact name: a missing branch must not resolve through a tag or another reference+ // that git's DWIM rules would try after it.+ oldOID, err = quarantineRepo.ResolveReferenceExactly(ctx, referenceName)if err != nil {if errors.Is(err, git.ErrReferenceNotFound) {return nil, structerr.NewInvalidArgument("Cannot find branch")@@ -203,11 +205,19 @@ func (l *legacyGit2GoSubmoduleAlreadyAtShaError) Error() string {func (s *Server) updateSubmodule(ctx context.Context, quarantineRepo *localrepo.Repo, req *gitalypb.UserUpdateSubmoduleRequest) (string, error) {var treeID git.ObjectID- fullTree, err := quarantineRepo.ReadTree(- ctx,- git.NewReferenceNameFromBranchName(string(req.GetBranch())).Revision(),- localrepo.WithRecursive(),- )+ // The tree and the parent of the new commit are those of the branch, read once by its exact+ // name: git's DWIM rules would resolve the branch name to a tag of the same name before the+ // branch, and a missing branch through a tag or another reference.+ currentBranchCommit, err := quarantineRepo.ResolveReferenceExactly(ctx, git.NewReferenceNameFromBranchName(string(req.GetBranch())))+ if err != nil {+ if errors.Is(err, git.ErrReferenceNotFound) {+ return "", fmt.Errorf("submodule: %s", legacyErrPrefixInvalidSubmodulePath)+ }++ return "", fmt.Errorf("resolving submodule branch: %w", err)+ }++ fullTree, err := quarantineRepo.ReadTree(ctx, currentBranchCommit.Revision(), localrepo.WithRecursive())if err != nil {if errors.Is(err, git.ErrReferenceNotFound) {return "", fmt.Errorf("submodule: %s", legacyErrPrefixInvalidSubmodulePath)@@ -258,10 +268,6 @@ func (s *Server) updateSubmodule(ctx context.Context, quarantineRepo *localrepo.}treeID = fullTree.OID- currentBranchCommit, err := quarantineRepo.ResolveRevision(ctx, git.Revision(req.GetBranch()))- if err != nil {- return "", fmt.Errorf("resolving submodule branch: %w", err)- }authorSignature, err := git.SignatureFromRequest(req)if err != nil {diff --git a/internal/gitaly/service/operations/user_delete_branch.go b/internal/gitaly/service/operations/user_delete_branch.goindex 12b3a0d..c21ee5d 100644--- a/internal/gitaly/service/operations/user_delete_branch.go+++ b/internal/gitaly/service/operations/user_delete_branch.go@@ -56,7 +56,9 @@ func (s *Server) UserDeleteBranch(ctx context.Context, req *gitalypb.UserDeleteBWithMetadata("old_object_id", expectedOldOID)}} else {- referenceValue, err = repo.ResolveRevision(ctx, referenceName.Revision())+ // By its exact name: a missing branch must not resolve through a tag or another reference+ // that git's DWIM rules would try after it.+ referenceValue, err = repo.ResolveReferenceExactly(ctx, referenceName)if err != nil {return nil, structerr.NewFailedPrecondition("branch not found: %q", req.GetBranchName())}diff --git a/internal/gitaly/service/operations/utils.go b/internal/gitaly/service/operations/utils.goindex 4fc69e3..3099904 100644--- a/internal/gitaly/service/operations/utils.go+++ b/internal/gitaly/service/operations/utils.go@@ -43,6 +43,30 @@ func validateCherryPickOrRevertRequest(ctx context.Context, locator storage.Locareturn nil}+// resolveBranchCommitExactly returns the commit of the branch reference, read by its exact name and+// peeled as `<branch>^{commit}` is (localrepo.ResolveBranchesExactly), or git.ErrReferenceNotFound+// when the branch does not exist or does not peel to a commit. git resolves `<branch>^{commit}`+// with its DWIM rules: when refs/heads/<x> is missing, refs/refs/heads/<x>, refs/tags/refs/heads/<x>,+// refs/heads/refs/heads/<x> or refs/remotes/refs/heads/<x> answers for it.+func (s *Server) resolveBranchCommitExactly(ctx context.Context, repo *localrepo.Repo, reference git.ReferenceName) (git.ObjectID, error) {+ reader, release, err := s.catfileCache.ObjectInfoReader(ctx, repo)+ if err != nil {+ return "", fmt.Errorf("creating object info reader: %w", err)+ }+ defer release()++ branches, err := repo.ResolveBranchesExactly(ctx, reader, reference)+ if err != nil {+ return "", err+ }+ commit, ok := branches[reference]+ if !ok {+ return "", git.ErrReferenceNotFound+ }++ return commit, nil+}+// resolveRevision is a helper function to call ResolveRevision on the repo if the existing commit is not equal to the ZeroOID.func resolveRevision(ctx context.Context, repo *localrepo.Repo, commit git.ObjectID) (git.ObjectID, error) {objectHash, err := repo.ObjectHash(ctx)