Skip to content

Git designed for AI agents.

operations: start points agree locally and remotely, and are never paths

Federico Eliaf445be3109a2
diff --git a/internal/git/remoterepo/repository.go b/internal/git/remoterepo/repository.go
index 1641a3a..c899508 100644
--- a/internal/git/remoterepo/repository.go
+++ b/internal/git/remoterepo/repository.go
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
- "io"
"strings"
"sync"
@@ -13,6 +12,7 @@ import (
"github.com/feder-cr/git-ai/internal/grpc/client"
"github.com/feder-cr/git-ai/proto/go/gitalypb"
"google.golang.org/grpc"
+ "google.golang.org/grpc/status"
)
// Repo represents a Git repository on a different Gitaly storage
@@ -108,24 +108,24 @@ 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)
+ commit, exists, err := rr.exactCommit(ctx, name)
if err != nil {
return "", err
}
- if target == "" {
+ if !exists || commit == "" {
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 commit, nil
}
+// ErrNotACommit is returned by ReadReference for a reference that exists but does not point to a
+// commit (another object, or an object that is missing).
+var ErrNotACommit = errors.New("the reference does not point to a commit")
+
// 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
+// name, to the commit it points to. It returns git.ErrReferenceNotFound when the reference does not
+// exist (a dangling symbolic reference included), and ErrNotACommit when it exists but does not
+// point to a commit, as a local read of its value would then fail to peel it. 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) {
@@ -136,49 +136,47 @@ func (rr *Repo) ReadReference(ctx context.Context, name git.ReferenceName) (git.
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() {
+ commit, exists, err := rr.exactCommit(ctx, name)
+ switch {
+ case err != nil:
+ return "", err
+ case !exists:
return "", git.ErrReferenceNotFound
+ case commit == "":
+ return "", fmt.Errorf("%q: %w", name, ErrNotACommit)
}
-
- return rr.ResolveRevision(ctx, name.Revision())
+ return commit, nil
}
-// 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{
+// exactCommit reads the reference named name by its exact name: exists tells whether it exists,
+// and commit is the commit it points to, empty when it points to another object or to one that is
+// missing. RefExists checks the exact name (show-ref --verify, without listing the references below
+// it; a dangling symbolic reference does not exist), and only then FindCommit resolves it, by the
+// full name, which is the first name git's DWIM rules try.
+func (rr *Repo) exactCommit(ctx context.Context, name git.ReferenceName) (commit git.ObjectID, exists bool, returnedErr error) {
+ resp, err := gitalypb.NewRefServiceClient(rr.conn).RefExists(ctx, &gitalypb.RefExistsRequest{
Repository: rr.Repository,
- Patterns: [][]byte{[]byte(name)},
+ Ref: []byte(name),
})
if err != nil {
- return "", fmt.Errorf("list refs: %w", err)
- }
- var target string
- for {
- resp, err := stream.Recv()
- if err != nil {
- if errors.Is(err, io.EOF) {
- break
- }
- return "", fmt.Errorf("list refs: %w", err)
- }
- for _, ref := range resp.GetReferences() {
- if git.ReferenceName(ref.GetName()) == name {
- target = ref.GetTarget()
+ // A reference whose object is missing is answered with this detail; any other error,
+ // the detail missing included, is a failure.
+ for _, detail := range status.Convert(err).Details() {
+ if refErr, ok := detail.(*gitalypb.RefExistsError); ok && refErr.GetUnresolvableReference() != nil {
+ return "", true, nil
}
}
+ return "", false, fmt.Errorf("ref exists: %w", err)
+ }
+ if !resp.GetValue() {
+ return "", false, nil
}
- return target, nil
+ commit, err = rr.ResolveRevision(ctx, name.Revision())
+ if errors.Is(err, git.ErrReferenceNotFound) {
+ return "", true, nil
+ }
+ return commit, true, err
}
// 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.go
index 0056470..93ab216 100644
--- a/internal/gitaly/service/operations/branch_exact_test.go
+++ b/internal/gitaly/service/operations/branch_exact_test.go
@@ -904,6 +904,83 @@ func TestStartBranchResolvesTheBranchFirst(t *testing.T) {
})
}
+// TestStartBranchLocalAndRemoteAgree runs the same start points in the repository of the request
+// and through a start repository, the same repository read over RPC: a reference that exists but
+// does not point to a commit fails the request on both paths, with the same code, instead of being
+// skipped for a later reference on one of them.
+func TestStartBranchLocalAndRemoteAgree(t *testing.T) {
+ t.Parallel()
+
+ ctx, cfg, client := setupExactBranchService(t)
+
+ for _, tc := range []struct {
+ desc string
+ // refs writes the references of the case and returns the parent the cherry-pick must have,
+ // empty when it must fail.
+ refs func(t *testing.T, setup cherryPickOrRevertSetup) string
+ }{
+ {
+ desc: "a branch",
+ refs: func(t *testing.T, setup cherryPickOrRevertSetup) string {
+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/heads/x", setup.base)
+ return setup.base.String()
+ },
+ },
+ {
+ desc: "a tag at a tree, before a remote-tracking branch",
+ refs: func(t *testing.T, setup cherryPickOrRevertSetup) string {
+ tree := strings.TrimSpace(string(gittest.Exec(t, cfg, "-C", setup.repoPath, "rev-parse", setup.base.String()+"^{tree}")))
+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/tags/x", git.ObjectID(tree))
+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/remotes/x", setup.base)
+ return ""
+ },
+ },
+ {
+ desc: "a branch at a missing object",
+ refs: func(t *testing.T, setup cherryPickOrRevertSetup) string {
+ doomed := gittest.WriteCommit(t, cfg, setup.repoPath, gittest.WithMessage("doomed"))
+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/heads/x", doomed)
+ require.NoError(t, os.Remove(filepath.Join(setup.repoPath, "objects", doomed.String()[:2], doomed.String()[2:])))
+ gittest.WriteRef(t, cfg, setup.repoPath, "refs/remotes/x", setup.base)
+ return ""
+ },
+ },
+ } {
+ for _, remote := range []bool{false, true} {
+ desc := tc.desc + ", local"
+ if remote {
+ desc = tc.desc + ", through a start repository"
+ }
+ t.Run(desc, func(t *testing.T) {
+ t.Parallel()
+
+ setup := setupCherryPickOrRevert(t, ctx, cfg)
+ parent := tc.refs(t, setup)
+ request := &gitalypb.UserCherryPickRequest{
+ Repository: setup.repo,
+ User: gittest.TestUser,
+ Commit: setup.commit,
+ BranchName: []byte("new"),
+ StartBranchName: []byte("x"),
+ Message: []byte("cherry-pick onto new"),
+ }
+ if remote {
+ request.StartRepository = setup.repo
+ }
+
+ resp, err := client.UserCherryPick(ctx, request)
+ if parent == "" {
+ testhelper.RequireGrpcCode(t, err, codes.InvalidArgument)
+ require.ErrorContains(t, err, "resolve start ref")
+ return
+ }
+ require.NoError(t, err)
+ require.Equal(t, parent, parentsOf(t, cfg, setup.repoPath, resp.GetBranchUpdate().GetCommitId()))
+ })
+ }
+ }
+}
+
// 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)
@@ -947,7 +1024,16 @@ func TestResolveStartBranch(t *testing.T) {
{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}"},
+ // A path is not a start point; a colon inside braces is not a path.
+ {name: "main:file", refs: []string{"refs/heads/main"}, expected: "path"},
+ {name: ":path", expected: "path", noLookup: true},
+ {name: "main^{/fix: x}", refs: []string{"refs/heads/main"}, expected: "v(refs/heads/main)^{/fix: x}^{commit}"},
+ {
+ name: "main@{2024-01-01 10:00:00}",
+ refs: []string{"refs/heads/main"},
+ reflogs: []string{"refs/heads/main"},
+ expected: "refs/heads/main@{2024-01-01 10:00:00}^{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, and a reflog of the
// reference's own: without one, git would read the reflog of a decoy.
@@ -971,7 +1057,6 @@ func TestResolveStartBranch(t *testing.T) {
{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) {
@@ -1001,9 +1086,12 @@ func TestResolveStartBranch(t *testing.T) {
}
resolved, err := resolveStartBranch(tc.name, git.ObjectHashSHA1, read, reflogExists, resolve)
- if tc.expected == "not found" {
+ switch tc.expected {
+ case "not found":
require.ErrorIs(t, err, git.ErrReferenceNotFound)
- } else {
+ case "path":
+ require.ErrorIs(t, err, errStartPointPath)
+ default:
require.NoError(t, err)
require.Equal(t, tc.expected, resolved.String())
}
diff --git a/internal/gitaly/service/operations/commit_files_exact_test.go b/internal/gitaly/service/operations/commit_files_exact_test.go
index 7518ead..a803d2c 100644
--- a/internal/gitaly/service/operations/commit_files_exact_test.go
+++ b/internal/gitaly/service/operations/commit_files_exact_test.go
@@ -139,4 +139,27 @@ func TestUserCommitFilesResolvesStartRepositoryBranchesExactly(t *testing.T) {
})
}
}
+
+ t.Run("a start branch with branches below its name", func(t *testing.T) {
+ // refs/heads/x/y is below the name x, which a listing by prefix would match: x itself does
+ // not exist.
+ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)
+ gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("master"))
+
+ startRepo, startRepoPath := gittest.CreateRepository(t, ctx, cfg)
+ gittest.WriteCommit(t, cfg, startRepoPath, gittest.WithBranch("main"))
+ gittest.WriteCommit(t, cfg, startRepoPath, gittest.WithBranch("x/y"))
+
+ header := headerRequest(repo, gittest.TestUser, "new", []byte("message"), "x", "")
+ setStartRepository(header, startRepo)
+
+ stream, err := client.UserCommitFiles(ctx)
+ require.NoError(t, err)
+ require.NoError(t, stream.Send(header))
+ require.NoError(t, stream.Send(createFileHeaderRequest("file")))
+ require.NoError(t, stream.Send(actionContentRequest("content\n")))
+ _, err = stream.CloseAndRecv()
+ require.ErrorContains(t, err, "reference not found")
+ require.NotContains(t, string(gittest.Exec(t, cfg, "-C", repoPath, "for-each-ref", "refs/heads/")), "refs/heads/new")
+ })
}
diff --git a/internal/gitaly/service/operations/revert.go b/internal/gitaly/service/operations/revert.go
index 0e0a451..dcc50df 100644
--- a/internal/gitaly/service/operations/revert.go
+++ b/internal/gitaly/service/operations/revert.go
@@ -240,7 +240,12 @@ func resolveStartBranch(
resolve func(git.Revision) (git.ObjectID, error),
) (git.ObjectID, error) {
base, suffix := splitRevisionSuffix(name)
- // A revision that starts with its suffix (@{-1}, :path) names no reference.
+ // A start point is a commit, and <revision>:path names a blob or a tree; git would parse a
+ // ^{commit} after it as part of the path.
+ if namesPath(suffix) {
+ return "", errStartPointPath
+ }
+ // A revision that starts with its suffix (@{-1}) names no reference.
if base == "" || isFullObjectID(base, objectHash) {
return resolve(git.Revision(name + "^{commit}"))
}
@@ -274,6 +279,30 @@ func resolveStartBranch(
return commit, nil
}
+// errStartPointPath is the error of a start point that names a path (<revision>:path), not a commit.
+var errStartPointPath = errors.New("the start point names a path, not a commit")
+
+// namesPath reports whether the suffix of a revision names a path: a colon outside braces, where
+// @{<date>} and ^{/<text>} may hold one.
+func namesPath(suffix string) bool {
+ depth := 0
+ for _, c := range suffix {
+ switch c {
+ case '{':
+ depth++
+ case '}':
+ if depth > 0 {
+ depth--
+ }
+ case ':':
+ if depth == 0 {
+ return true
+ }
+ }
+ }
+ return false
+}
+
// 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")