Git designed for AI agents.
operations: a reflog start point needs the reference's own reflog
Federico Elia8180f98a0d7a
diff --git a/internal/git/gitcmd/command_description.go b/internal/git/gitcmd/command_description.goindex 16ffa42..1b826da 100644--- a/internal/git/gitcmd/command_description.go+++ b/internal/git/gitcmd/command_description.go@@ -295,6 +295,10 @@ var commandDescriptions = map[string]commandDescription{}, hiddenReceivePackRefPrefixes(ctx)...), receiveFsckConfiguration(ctx)...), packConfiguration(ctx)...)},},+ "reflog": {+ // Only `reflog exists` is run, which reads the reflog of one reference.+ flags: scNoRefUpdates,+ },"remote": {// While git-remote(1)'s `add` subcommand does support `--end-of-options`,// `remove` doesn't.diff --git a/internal/git/localrepo/refs.go b/internal/git/localrepo/refs.goindex a7b554f..38918bd 100644--- a/internal/git/localrepo/refs.go+++ b/internal/git/localrepo/refs.go@@ -203,6 +203,25 @@ func (repo *Repo) ResolveReferenceExactly(ctx context.Context, reference git.Refreturn git.ObjectID(value), nil}+// ReflogExists reports whether the reference named reference has a reflog, with `git reflog+// exists`, which reads that one reference's log: no DWIM rule.+func (repo *Repo) ReflogExists(ctx context.Context, reference git.ReferenceName) (bool, error) {+ var stderr bytes.Buffer+ err := repo.ExecAndWait(ctx, gitcmd.Command{+ Name: "reflog",+ Action: "exists",+ Args: []string{reference.String()},+ }, gitcmd.WithStderr(&stderr))+ if err == nil {+ return true, nil+ }+ // reflog exists exits 1 for a reference without a reflog.+ if code, ok := command.ExitStatus(err); ok && code == 1 {+ return false, nil+ }+ return false, fmt.Errorf("reflog exists %q: %w, stderr: %q", reference, err, stderr.String())+}+// 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) {diff --git a/internal/gitaly/service/operations/branch_exact_test.go b/internal/gitaly/service/operations/branch_exact_test.goindex 0fbc393..0056470 100644--- a/internal/gitaly/service/operations/branch_exact_test.go+++ b/internal/gitaly/service/operations/branch_exact_test.go@@ -806,6 +806,36 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {})}+ t.Run("cherry-pick, main@{1} with a reflog of its own", func(t *testing.T) {+ t.Parallel()++ // main's reflog holds other, then base: main@{1} is other.+ setup := setupCherryPickOrRevert(t, ctx, cfg)+ other := gittest.WriteCommit(t, cfg, setup.repoPath, gittest.WithMessage("other"), gittest.WithParents(setup.base),+ gittest.WithTreeEntries(baseFile, gittest.TreeEntry{Path: "other", Mode: "100644", Content: "other\n"}))+ gittest.Exec(t, cfg, "-C", setup.repoPath, "update-ref", "--create-reflog", git.DefaultRef.String(), other.String())+ gittest.Exec(t, cfg, "-C", setup.repoPath, "update-ref", "--create-reflog", git.DefaultRef.String(), setup.base.String())++ resp, err := cherryPick(setup, git.DefaultBranch+"@{1}")+ require.NoError(t, err)+ require.Equal(t, other.String(), parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()))+ })++ t.Run("cherry-pick, main@{1} with only a decoy's reflog", func(t *testing.T) {+ t.Parallel()++ // main has no reflog, and refs/refs/heads/main has one, which git would read for+ // refs/heads/main@{1}.+ setup := setupCherryPickOrRevert(t, ctx, cfg)+ decoy := writeDecoy(t, cfg, setup.repoPath, "refs/refs/heads/main", baseFile)+ gittest.Exec(t, cfg, "-C", setup.repoPath, "update-ref", "--create-reflog", "refs/refs/heads/main", decoy.String())+ gittest.Exec(t, cfg, "-C", setup.repoPath, "update-ref", "--create-reflog", "refs/refs/heads/main", setup.base.String())++ _, err := cherryPick(setup, git.DefaultBranch+"@{1}")+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)+ require.ErrorContains(t, err, "has no reflog")+ })+t.Run("cherry-pick, a dangling symbolic branch by its full name", func(t *testing.T) {t.Parallel()@@ -890,6 +920,8 @@ func TestResolveStartBranch(t *testing.T) {expected string// noLookup tells that the name must not be looked up as a reference.noLookup bool+ // reflogs are the references that have a reflog of their own.+ reflogs []string}{{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}"},@@ -917,8 +949,15 @@ func TestResolveStartBranch(t *testing.T) {{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}"},+ // A reflog suffix needs the name, which is read again afterwards, and a reflog of the+ // reference's own: without one, git would read the reflog of a decoy.+ {+ name: "main@{1}",+ refs: []string{"refs/tags/main", "refs/heads/main"},+ reflogs: []string{"refs/heads/main"},+ expected: "refs/heads/main@{1}^{commit}",+ },+ {name: "main@{1}", refs: []string{"refs/heads/main", "refs/refs/heads/main"}, reflogs: []string{"refs/refs/heads/main"}, expected: "not found"},{name: "refs/heads/x", refs: []string{"refs/refs/heads/x"}, expected: "not found"},{name: "abc1234", expected: "abc1234^{commit}"},{name: "@", expected: "@^{commit}"},@@ -952,7 +991,16 @@ func TestResolveStartBranch(t *testing.T) {return git.ObjectID(revision), nil}- resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, read, resolve)+ reflogExists := func(name git.ReferenceName) (bool, error) {+ for _, reflog := range tc.reflogs {+ if git.ReferenceName(reflog) == name {+ return true, nil+ }+ }+ return false, nil+ }++ resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, read, reflogExists, resolve)if tc.expected == "not found" {require.ErrorIs(t, err, git.ErrReferenceNotFound)} else {@@ -978,8 +1026,14 @@ func TestResolveStartBranch(t *testing.T) {return git.ObjectID(revision), nil}- _, err := resolveStartBranch("main@{1}", git.ObjectHashSHA1, read, resolve)- require.ErrorContains(t, err, "changed while its reflog was read")+ reflogExists := func(git.ReferenceName) (bool, error) { return true, nil }++ _, err := resolveStartBranch("main@{1}", git.ObjectHashSHA1, read, reflogExists, resolve)+ require.ErrorIs(t, err, errStartReferenceChanged)+ // The caller sees a failed precondition, which a retry may not meet, unlike the invalid+ // argument of a start branch that does not resolve.+ testhelper.RequireGrpcCode(t, startRefError(err), codes.FailedPrecondition)+ testhelper.RequireGrpcCode(t, startRefError(git.ErrReferenceNotFound), codes.InvalidArgument)})}diff --git a/internal/gitaly/service/operations/revert.go b/internal/gitaly/service/operations/revert.goindex 1e0713a..0e0a451 100644--- a/internal/gitaly/service/operations/revert.go+++ b/internal/gitaly/service/operations/revert.go@@ -228,12 +228,15 @@ func (s *Server) UserRevert(ctx context.Context, req *gitalypb.UserRevertRequest//// 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.+// yields a decoy. A reflog suffix (@{n}) needs the name: the reference must have a reflog of its+// own (reflogExists), since git would otherwise read the reflog of a decoy such as+// refs/refs/heads/x; it is then resolved by the full name, and the reference must still have the+// value read, else the request fails with errStartReferenceChanged, which a retry may not meet.func resolveStartBranch(name string,objectHash git.ObjectHash,read func(git.ReferenceName) (git.ObjectID, error),+ reflogExists func(git.ReferenceName) (bool, error),resolve func(git.Revision) (git.ObjectID, error),) (git.ObjectID, error) {base, suffix := splitRevisionSuffix(name)@@ -254,20 +257,36 @@ func resolveStartBranch(return resolve(git.Revision(value.String() + suffix + "^{commit}"))}- commit, err := resolve(git.Revision(reference.String() + suffix + "^{commit}"))+ hasReflog, err := reflogExists(reference)if err != nil {return "", err}- again, err := read(reference)+ if !hasReflog {+ return "", fmt.Errorf("reference %q has no reflog: %w", reference, git.ErrReferenceNotFound)+ }+ commit, err := resolve(git.Revision(reference.String() + suffix + "^{commit}"))if err != nil {return "", err}- if again != value {- return "", fmt.Errorf("reference %q changed while its reflog was read", reference)+ if again, err := read(reference); err != nil || again != value {+ return "", fmt.Errorf("reference %q: %w", reference, errStartReferenceChanged)}return commit, nil}+// errStartReferenceChanged is the error of a start reference that changed while its reflog was read.+var errStartReferenceChanged = errors.New("the reference changed while its reflog was read")++// startRefError returns the error of a start branch that resolveStartBranch failed to resolve: a+// start reference that changed meanwhile is a failed precondition, which a retry may not meet, and+// anything else an invalid argument.+func startRefError(err error) error {+ if errors.Is(err, errStartReferenceChanged) {+ return structerr.NewFailedPrecondition("resolve start ref: %w", err)+ }+ return structerr.NewInvalidArgument("resolve start ref: %w", err)+}+// 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) {@@ -368,6 +387,9 @@ func (s *Server) fetchStartRevision(read := func(name git.ReferenceName) (git.ObjectID, error) {return localRepo.ResolveReferenceExactly(ctx, name)}+ reflogExists := func(name git.ReferenceName) (bool, error) {+ return localRepo.ReflogExists(ctx, name)+ }resolve := func(revision git.Revision) (git.ObjectID, error) {return localRepo.ResolveRevision(ctx, revision)}@@ -380,6 +402,11 @@ func (s *Server) fetchStartRevision(read = func(name git.ReferenceName) (git.ObjectID, error) {return remoteRepo.ReadReference(ctx, name)}+ // No RPC tells whether a reference of the start repository has a reflog of its own, so a+ // reflog entry of one is not taken there: git could read a decoy's reflog for it.+ reflogExists = func(git.ReferenceName) (bool, error) {+ return false, nil+ }resolve = func(revision git.Revision) (git.ObjectID, error) {return remoteRepo.ResolveRevision(ctx, revision)}@@ -389,9 +416,9 @@ func (s *Server) fetchStartRevision(return "", structerr.NewInternal("detecting object hash: %w", err)}- startRevision, err := resolveStartBranch(string(startBranchName), objectHash, read, resolve)+ startRevision, err := resolveStartBranch(string(startBranchName), objectHash, read, reflogExists, resolve)if err != nil {- return "", structerr.NewInvalidArgument("resolve start ref: %w", err)+ return "", startRefError(err)}if req.GetStartRepository() == nil {