Git designed for AI agents.
operations: read the start branch as a branch first
Federico Eliaeb5257e7ed7e
diff --git a/internal/git/remoterepo/repository.go b/internal/git/remoterepo/repository.goindex 8a63543..834a37c 100644--- a/internal/git/remoterepo/repository.go+++ b/internal/git/remoterepo/repository.go@@ -99,8 +99,14 @@ func (rr *Repo) ResolveRevision(ctx context.Context, revision git.Revision) (git// another reference. It returns git.ErrReferenceNotFound when the branch does not exist (also// when branches below its name do, refs/heads/<branch>/x) or does not peel to a commit.func (rr *Repo) ResolveBranch(ctx context.Context, branch string) (git.ObjectID, error) {- name := git.NewReferenceNameFromBranchName(branch)+ return rr.ResolveReference(ctx, git.NewReferenceNameFromBranchName(branch))+}+// ResolveReference is ResolveBranch for a reference given by its full name: it resolves name by+// its exact reference name to the commit it points to, as `<name>^{commit}` peels it, and returns+// 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) {// 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,@@ -128,7 +134,7 @@ func (rr *Repo) ResolveBranch(ctx context.Context, branch string) (git.ObjectID,return "", git.ErrReferenceNotFound}- // The object ID read above, peeled as `<branch>^{commit}` is: an object ID is never+ // 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}")}diff --git a/internal/gitaly/service/operations/branch_exact_test.go b/internal/gitaly/service/operations/branch_exact_test.goindex fda9674..3462d90 100644--- a/internal/gitaly/service/operations/branch_exact_test.go+++ b/internal/gitaly/service/operations/branch_exact_test.go@@ -3,6 +3,7 @@ package operationsimport ("context""fmt"+ "io""strings""testing"@@ -422,3 +423,120 @@ func TestUserApplyPatchResolvesBranchesExactly(t *testing.T) {})}}++// TestStartBranchResolvesTheBranchFirst checks the start branch of UserCherryPick, UserRevert and+// UserRebaseConfirmable (resolveStartBranch): a name is read as the branch of that name first, so a+// tag named like an existing start branch does not answer for it; a name without a branch keeps+// git's resolution, so a SHA or a tag still works as a start point; and a full reference name is+// read exactly as given, so a missing one does not resolve through a decoy.+func TestStartBranchResolvesTheBranchFirst(t *testing.T) {+ t.Parallel()++ ctx, cfg, client := setupExactBranchService(t)++ cherryPick := func(setup cherryPickOrRevertSetup, startBranch string) (*gitalypb.UserCherryPickResponse, error) {+ return client.UserCherryPick(ctx, &gitalypb.UserCherryPickRequest{+ Repository: setup.repo,+ User: gittest.TestUser,+ Commit: setup.commit,+ BranchName: []byte("new"),+ StartBranchName: []byte(startBranch),+ Message: []byte("cherry-pick onto new"),+ })+ }++ t.Run("cherry-pick, start branch with a tag of its name", func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ writeDecoy(t, cfg, setup.repoPath, git.ReferenceName("refs/tags/"+git.DefaultBranch))++ resp, err := cherryPick(setup, git.DefaultBranch)+ require.NoError(t, err)+ require.Equal(t, setup.base.String(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()),+ "the start branch, not the tag of its name, is the parent")+ })++ t.Run("cherry-pick, a SHA as the start", func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)++ resp, err := cherryPick(setup, setup.base.String())+ require.NoError(t, err)+ require.Equal(t, setup.base.String(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()))+ })++ t.Run("cherry-pick, a tag without a branch of its name as the start", func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/tags/v1", setup.base)++ resp, err := cherryPick(setup, "v1")+ require.NoError(t, err)+ require.Equal(t, setup.base.String(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()))+ })++ for _, decoy := range exactBranchDecoys {+ t.Run("cherry-pick, a missing full reference name, "+decoy.String(), func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ decoyCommit := writeDecoy(t, cfg, setup.repoPath, decoy)++ _, err := cherryPick(setup, "refs/heads/x")+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)+ require.ErrorContains(t, err, "resolve start ref")+ require.Empty(t, exactReferenceValue(t, cfg, setup.repoPath, "refs/heads/new"), "no branch new")+ require.Equal(t, decoyCommit.String(), exactReferenceValue(t, cfg, setup.repoPath, decoy), "the decoy is untouched")+ })+ }++ t.Run("revert, start branch with a tag of its name", func(t *testing.T) {+ t.Parallel()++ setup := setupCherryPickOrRevert(t, ctx, cfg)+ gittest.WriteRef(t, cfg, setup.repoPath, git.DefaultRef, git.ObjectID(setup.commit.GetId()))+ // The tag's tree holds the file that the revert removes, so that the revert applies onto it+ // too: only the parent tells which of the two it started from.+ writeDecoy(t, cfg, setup.repoPath, git.ReferenceName("refs/tags/"+git.DefaultBranch),+ gittest.TreeEntry{Path: "base", Mode: "100644", Content: "base\n"},+ gittest.TreeEntry{Path: "picked", Mode: "100644", Content: "picked\n"})++ resp, err := client.UserRevert(ctx, &gitalypb.UserRevertRequest{+ Repository: setup.repo,+ User: gittest.TestUser,+ Commit: setup.commit,+ BranchName: []byte("new"),+ StartBranchName: []byte(git.DefaultBranch),+ Message: []byte("revert onto new"),+ })+ require.NoError(t, err)+ require.Equal(t, setup.commit.GetId(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()),+ "the start branch, not the tag of its name, is the parent")+ })++ t.Run("rebase onto a remote branch with a tag of its name", func(t *testing.T) {+ t.Parallel()++ setup := setupRebasableRepositories(t, ctx, cfg, true)+ writeDecoy(t, cfg, setup.remoteRepoPath, git.ReferenceName("refs/tags/"+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)))+ second, err := stream.Recv()+ require.NoError(t, err)+ require.True(t, second.GetRebaseApplied())+ _, err = stream.Recv()+ require.Equal(t, io.EOF, err)++ require.Equal(t, setup.remoteCommit.String(), parentsOf(t, cfg, setup.localRepoPath, first.GetRebaseSha()),+ "the rebase is onto the remote branch, not onto the tag of its name")+ })+}diff --git a/internal/gitaly/service/operations/revert.go b/internal/gitaly/service/operations/revert.goindex afb46b1..737f96f 100644--- a/internal/gitaly/service/operations/revert.go+++ b/internal/gitaly/service/operations/revert.go@@ -4,9 +4,9 @@ import ("context""errors""fmt"+ "strings""github.com/feder-cr/git-ai/internal/git"- "github.com/feder-cr/git-ai/internal/git/gitcmd""github.com/feder-cr/git-ai/internal/git/localrepo""github.com/feder-cr/git-ai/internal/git/remoterepo""github.com/feder-cr/git-ai/internal/gitaly/hook/updateref"@@ -206,6 +206,33 @@ func (s *Server) UserRevert(ctx context.Context, req *gitalypb.UserRevertRequest}, nil}+// resolveStartBranch resolves the start branch name of a request to its commit. exact reads a+// reference by its exact name, peeled to its commit, and resolve is git's resolution of a revision,+// both in the repository the start branch is read from.+//+// 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. A name x is therefore read as the branch+// refs/heads/x first. When there is no such branch, the name 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. 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.+func resolveStartBranch(+ name string,+ exact func(git.ReferenceName) (git.ObjectID, error),+ resolve func(git.Revision) (git.ObjectID, error),+) (git.ObjectID, error) {+ if strings.HasPrefix(name, "refs/") {+ return exact(git.ReferenceName(name))+ }++ commit, err := exact(git.NewReferenceNameFromBranchName(name))+ if !errors.Is(err, git.ErrReferenceNotFound) {+ return commit, err+ }++ return resolve(git.Revision(name + "^{commit}"))+}+type requestFetchingStartRevision interface {GetBranchName() []byteGetStartRepository() *gitalypb.Repository@@ -222,16 +249,27 @@ func (s *Server) fetchStartRevision(startBranchName = req.GetBranchName()}- var remoteRepo gitcmd.Repository = localRepo+ // The start branch is read in the start repository, or in the local one without it.+ exact := func(name git.ReferenceName) (git.ObjectID, error) {+ return s.resolveBranchCommitExactly(ctx, localRepo, name)+ }+ resolve := func(revision git.Revision) (git.ObjectID, error) {+ return localRepo.ResolveRevision(ctx, revision)+ }if startRepository := req.GetStartRepository(); startRepository != nil {- var err error- remoteRepo, err = remoterepo.New(ctx, startRepository, s.conns)+ remoteRepo, err := remoterepo.New(ctx, startRepository, s.conns)if err != nil {return "", structerr.NewInternal("%w", err)}+ exact = func(name git.ReferenceName) (git.ObjectID, error) {+ return remoteRepo.ResolveReference(ctx, name)+ }+ resolve = func(revision git.Revision) (git.ObjectID, error) {+ return remoteRepo.ResolveRevision(ctx, revision)+ }}- startRevision, err := remoteRepo.ResolveRevision(ctx, git.Revision(fmt.Sprintf("%s^{commit}", startBranchName)))+ startRevision, err := resolveStartBranch(string(startBranchName), exact, resolve)if err != nil {return "", structerr.NewInvalidArgument("resolve start ref: %w", err)}