Skip to content

Git designed for AI agents.

graft repo create, FindDefaultBranchName: second review round

Federico Elia87b9f61c764e
diff --git a/cmd/graft/repo.go b/cmd/graft/repo.go
index ee4636a..93a7fa1 100644
--- a/cmd/graft/repo.go
+++ b/cmd/graft/repo.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "errors"
"flag"
"fmt"
"io"
@@ -123,8 +124,16 @@ type repoProgress struct {
done, left []string
}
-// fail reports err with what was done and what is left. A denial of the
-// server's policy says so: running the command again is denied the same way.
+// repoRefusal is a state of the repository that graft repo create does not
+// change: running the same command again fails the same way until the
+// repository or the arguments change.
+type repoRefusal struct{ reason string }
+
+func (r repoRefusal) Error() string { return r.reason }
+
+// fail reports err with what was done and what is left. A refusal and a denial
+// of the server's policy say so: running the command again fails the same way.
+// Any other failure is worth running again.
func (p *repoProgress) fail(relativePath string, err error) error {
report := ""
if len(p.done) > 0 {
@@ -133,6 +142,10 @@ func (p *repoProgress) fail(relativePath string, err error) error {
if len(p.left) > 0 {
report += "\nleft: " + strings.Join(p.left, "; ")
}
+ var refusal repoRefusal
+ if errors.As(err, &refusal) {
+ return fmt.Errorf("repository %s: %w%s", displayText(relativePath), err, report)
+ }
if sdk.Code(err) == codes.PermissionDenied {
return fmt.Errorf("repository %s: denied by the server: %w%s\nthe same command is denied again until the policy allows the user of GRAFT_USER (-user) to write these branches", displayText(relativePath), err, report)
}
@@ -198,7 +211,7 @@ func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, ar
case sdk.Code(err) == codes.FailedPrecondition && strings.HasSuffix(status.Convert(err).Message(), "repository is already locked"):
// The server's answer while another request creates or removes the
// repository (repoutil.Create, wrapped by the handler).
- return fmt.Errorf("repository %s is being created or removed by another request: %w\nrun the same command again once it is done", displayText(relativePath), err)
+ return fmt.Errorf("repository %s is locked by another request that creates or removes it, or by a lock such a request left behind: %w\nretry later; if it persists, an operator should check %s.lock on the server", displayText(relativePath), err, displayText(relativePath))
default:
return withOperatorHint(err)
}
@@ -256,17 +269,17 @@ func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, ar
}
// repoBranches validates the branch names of graft repo create with git's
-// reference name rules, before any server call, and returns the default branch
+// branch name rules, before any server call, and returns the default branch
// and the extra branches without duplicates and without the default branch.
func repoBranches(f *repoFlags) (string, []string, error) {
defaultBranch := strings.TrimPrefix(f.defaultBranch, "refs/heads/")
- if err := git.ValidateReference("refs/heads/" + defaultBranch); err != nil || defaultBranch == "" {
+ if !validBranchName(defaultBranch) {
return "", nil, usagef("repo create: invalid --default-branch %q", f.defaultBranch)
}
var branches []string
for _, branch := range f.branches {
name := strings.TrimPrefix(branch, "refs/heads/")
- if err := git.ValidateReference("refs/heads/" + name); err != nil || name == "" {
+ if !validBranchName(name) {
return "", nil, usagef("repo create: invalid --branch %q", branch)
}
if name != defaultBranch && !slices.Contains(branches, name) {
@@ -276,6 +289,14 @@ func repoBranches(f *repoFlags) (string, []string, error) {
return defaultBranch, branches, nil
}
+// validBranchName reports whether name is a valid branch name, as
+// git check-ref-format --branch decides it: a valid reference name below
+// refs/heads/ that is not HEAD and does not start with a dash.
+func validBranchName(name string) bool {
+ return name != "" && name != "HEAD" && !strings.HasPrefix(name, "-") &&
+ git.ValidateReference("refs/heads/"+name) == nil
+}
+
// ensureInitialCommit makes sure the default branch of repo has a commit and
// returns its tip, and whether this call made the commit. HEAD must point to
// the default branch. The commit is made only in a repository without any
@@ -285,11 +306,15 @@ func repoBranches(f *repoFlags) (string, []string, error) {
func ensureInitialCommit(ctx context.Context, repo *sdk.Repo, defaultBranch string, user sdk.User, author workspace.Signature) (string, bool, error) {
ref := "refs/heads/" + defaultBranch
head, err := repo.Head(ctx)
+ if sdk.Code(err) == codes.FailedPrecondition {
+ // The server's answer for a detached HEAD.
+ return "", false, repoRefusal{fmt.Sprintf("HEAD does not point to a branch (%s), so no initial commit is made", status.Convert(err).Message())}
+ }
if err != nil {
return "", false, fmt.Errorf("reading HEAD: %w", err)
}
if head != ref {
- return "", false, fmt.Errorf("HEAD points to %s, not %s: pass --default-branch %s, or no --initial-commit", displayText(head), displayText(ref), displayText(strings.TrimPrefix(head, "refs/heads/")))
+ return "", false, repoRefusal{fmt.Sprintf("HEAD points to %s, not %s: pass --default-branch %s, or no --initial-commit", displayText(head), displayText(ref), displayText(strings.TrimPrefix(head, "refs/heads/")))}
}
if tip, ok, err := branchTip(ctx, repo, ref); err != nil || ok {
@@ -305,7 +330,7 @@ func ensureInitialCommit(ctx context.Context, repo *sdk.Repo, defaultBranch stri
if tip, ok, err := branchTip(ctx, repo, ref); err != nil || ok {
return tip, false, err
}
- return "", false, fmt.Errorf("the repository has references but no %s: it is not empty, so no initial commit is made", displayText(ref))
+ return "", false, repoRefusal{fmt.Sprintf("the repository has references but no %s: it is not empty, so no initial commit is made", displayText(ref))}
}
zero, err := repo.ZeroOID(ctx)
diff --git a/cmd/graft/repo_test.go b/cmd/graft/repo_test.go
index 2688b34..91bf4b6 100644
--- a/cmd/graft/repo_test.go
+++ b/cmd/graft/repo_test.go
@@ -128,6 +128,7 @@ func TestCLIRepoCreateConverges(t *testing.T) {
code, _, stderr = repoCLI(t, server, "trunk.git", "--initial-commit")
require.Equal(t, exitError, code)
require.Contains(t, stderr, "HEAD points to refs/heads/trunk, not refs/heads/main: pass --default-branch trunk")
+ require.NotContains(t, stderr, "run the same command again", "the refusal repeats identically")
requireRefs(t, env.cfg, filepath.Join(storagePath, "trunk.git"), map[string]string{})
code, res, stderr := repoCLI(t, server, "trunk.git", "--initial-commit", "--default-branch", "trunk")
@@ -146,10 +147,25 @@ func TestCLIRepoCreateConverges(t *testing.T) {
code, _, stderr = repoCLI(t, server, rel, "--initial-commit")
require.Equal(t, exitError, code, ref)
require.Contains(t, stderr, "the repository has references but no refs/heads/main: it is not empty, so no initial commit is made", ref)
+ require.NotContains(t, stderr, "run the same command again", ref)
requireRefs(t, env.cfg, path, map[string]string{ref: commit.String()})
}
})
+ t.Run("detached HEAD", func(t *testing.T) {
+ code, _, stderr := repoCLI(t, server, "detached.git")
+ require.Equal(t, exitOK, code, stderr)
+ path := filepath.Join(storagePath, "detached.git")
+ commit := gittest.WriteCommit(t, env.cfg, path, gittest.WithReference("refs/tags/v1"))
+ gittest.Exec(t, env.cfg, "-C", path, "update-ref", "--no-deref", "HEAD", commit.String())
+
+ code, _, stderr = repoCLI(t, server, "detached.git", "--initial-commit")
+ require.Equal(t, exitError, code)
+ require.Contains(t, stderr, "repository detached.git: HEAD does not point to a branch (HEAD is detached: it does not point to a branch), so no initial commit is made")
+ require.NotContains(t, stderr, "run the same command again")
+ requireRefs(t, env.cfg, path, map[string]string{"refs/tags/v1": commit.String()})
+ })
+
t.Run("existing default branch is the initial commit", func(t *testing.T) {
code, _, stderr := repoCLI(t, server, "existing.git")
require.Equal(t, exitOK, code, stderr)
@@ -185,7 +201,8 @@ func TestCLIRepoCreateConverges(t *testing.T) {
for i := 0; i < runs; i++ {
if codes[i] != exitOK {
require.Equal(t, exitError, codes[i], "run %d: %s", i, stderrs[i])
- require.Contains(t, stderrs[i], "repository raced.git is being created or removed by another request", "run %d", i)
+ require.Contains(t, stderrs[i], "repository raced.git is locked by another request that creates or removes it, or by a lock such a request left behind", "run %d", i)
+ require.Contains(t, stderrs[i], "retry later; if it persists, an operator should check raced.git.lock on the server", "run %d", i)
continue
}
if results[i].Created {
@@ -316,22 +333,29 @@ func TestCLIRepoUsageErrorsDoNotContactServer(t *testing.T) {
nowhere := []string{"-address", "unix://" + filepath.Join(t.TempDir(), "missing.sock")}
cases := map[string][]string{
- "no subcommand": {"repo"},
- "unknown subcommand": {"repo", "delete", "a.git"},
- "no repository": {"repo", "create"},
- "two repositories": {"repo", "create", "a.git", "b.git"},
- "branch without initial commit": {"repo", "create", "a.git", "--branch", "x"},
- "unknown object format": {"repo", "create", "a.git", "--object-format", "md5"},
- "empty default branch": {"repo", "create", "a.git", "--default-branch", ""},
- "invalid default branch": {"repo", "create", "a.git", "--default-branch", "a..b"},
- "default branch HEAD": {"repo", "create", "a.git", "--default-branch", "HEAD.lock"},
- "invalid branch": {"repo", "create", "a.git", "--initial-commit", "--branch", "bad name"},
- "invalid second branch": {"repo", "create", "a.git", "--initial-commit", "--branch", "ok", "--branch", "x~1"},
- "author without name": {"repo", "create", "a.git", "-author", "<[email protected]>"},
+ "no subcommand": {"repo"},
+ "unknown subcommand": {"repo", "delete", "a.git"},
+ "no repository": {"repo", "create"},
+ "two repositories": {"repo", "create", "a.git", "b.git"},
+ "--branch without --initial-commit": {"repo", "create", "a.git", "--branch", "x"},
+ "unknown object format": {"repo", "create", "a.git", "--object-format", "md5"},
+ "empty default branch": {"repo", "create", "a.git", "--default-branch", ""},
+ "invalid default branch": {"repo", "create", "a.git", "--default-branch", "a..b"},
+ "default branch .lock": {"repo", "create", "a.git", "--default-branch", "HEAD.lock"},
+ "default branch HEAD": {"repo", "create", "a.git", "--default-branch", "HEAD"},
+ "default branch with a dash": {"repo", "create", "a.git", "--default-branch", "-x"},
+ "branch HEAD": {"repo", "create", "a.git", "--initial-commit", "--branch", "HEAD"},
+ "branch with a dash": {"repo", "create", "a.git", "--initial-commit", "--branch", "-x"},
+ "invalid branch": {"repo", "create", "a.git", "--initial-commit", "--branch", "bad name"},
+ "invalid second branch": {"repo", "create", "a.git", "--initial-commit", "--branch", "ok", "--branch", "x~1"},
+ "author without name": {"repo", "create", "a.git", "-author", "<[email protected]>"},
}
for name, args := range cases {
code, _, stderr := runCLI(t, append(args, nowhere...)...)
require.Equal(t, exitUsage, code, "%s: %s", name, stderr)
+ if strings.HasPrefix(name, "default branch") || strings.HasPrefix(name, "branch") || strings.HasPrefix(name, "invalid") {
+ require.Contains(t, stderr, "repo create: invalid --", "%s: the name is refused, not parsed as a flag", name)
+ }
}
code, _, stderr := runCLI(t, "repo", "create", "a.git", "-address", "")
diff --git a/internal/gitaly/service/ref/find_default_branch_name.go b/internal/gitaly/service/ref/find_default_branch_name.go
index 0325fc9..0e2fb54 100644
--- a/internal/gitaly/service/ref/find_default_branch_name.go
+++ b/internal/gitaly/service/ref/find_default_branch_name.go
@@ -3,6 +3,9 @@ package ref
import (
"context"
+ "github.com/feder-cr/git-ai/internal/command"
+ "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/structerr"
"github.com/feder-cr/git-ai/proto/go/gitalypb"
)
@@ -18,6 +21,9 @@ func (s *server) FindDefaultBranchName(ctx context.Context, in *gitalypb.FindDef
if in.GetHeadOnly() {
head, err := repo.HeadReference(ctx)
if err != nil {
+ if headIsDetached(ctx, repo) {
+ return nil, structerr.NewFailedPrecondition("HEAD is detached: it does not point to a branch")
+ }
return nil, structerr.NewInternal("head reference: %w", err)
}
return &gitalypb.FindDefaultBranchNameResponse{Name: []byte(head)}, nil
@@ -29,3 +35,15 @@ func (s *server) FindDefaultBranchName(ctx context.Context, in *gitalypb.FindDef
}
return &gitalypb.FindDefaultBranchNameResponse{Name: []byte(defaultBranch)}, nil
}
+
+// headIsDetached reports whether HEAD of repo is not a symbolic reference: `git symbolic-ref -q HEAD`
+// exits with 1, silently, exactly in that case.
+func headIsDetached(ctx context.Context, repo *localrepo.Repo) bool {
+ err := repo.ExecAndWait(ctx, gitcmd.Command{
+ Name: "symbolic-ref",
+ Flags: []gitcmd.Option{gitcmd.Flag{Name: "-q"}},
+ Args: []string{"HEAD"},
+ }, gitcmd.WithDisabledHooks())
+ code, ok := command.ExitStatus(err)
+ return ok && code == 1
+}
diff --git a/internal/gitaly/service/ref/find_default_branch_name_test.go b/internal/gitaly/service/ref/find_default_branch_name_test.go
index 4997c60..5d51ca7 100644
--- a/internal/gitaly/service/ref/find_default_branch_name_test.go
+++ b/internal/gitaly/service/ref/find_default_branch_name_test.go
@@ -157,6 +157,23 @@ func TestFindDefaultBranchName(t *testing.T) {
Name: []byte(git.DefaultRef),
},
},
+ {
+ desc: "detached HEAD, HEAD only",
+ setup: func(t *testing.T, ctx context.Context, cfg config.Cfg) setupData {
+ repo, repoPath := gittest.CreateRepository(t, ctx, cfg)
+
+ oid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))
+ gittest.Exec(t, cfg, "-C", repoPath, "update-ref", "--no-deref", "HEAD", oid.String())
+
+ return setupData{
+ request: &gitalypb.FindDefaultBranchNameRequest{
+ Repository: repo,
+ HeadOnly: true,
+ },
+ expectedErr: structerr.NewFailedPrecondition("HEAD is detached: it does not point to a branch"),
+ }
+ },
+ },
{
desc: "repository not provided",
setup: func(t *testing.T, ctx context.Context, cfg config.Cfg) setupData {
diff --git a/sdk/doc.go b/sdk/doc.go
index 288e196..6af4a8e 100644
--- a/sdk/doc.go
+++ b/sdk/doc.go
@@ -15,10 +15,12 @@
// calls the server answers with Unavailable (see UnavailableRetry).
// - Blame and PathHistory answer history questions from derived data.
// - Changesets and WatchChangesets read the repository's changeset log.
-// - Create creates an empty repository (operators only, with the shared
-// token). Head, HasReferences, ReferenceExists and ZeroOID are the exact
-// reads that make a repository's first commit safe to retry, and
-// CreateBranch creates a branch that must not exist yet.
+// - Create creates an empty repository. Head, HasReferences,
+// ReferenceExists and ZeroOID are the exact reads that make a
+// repository's first commit safe to retry, and CreateBranch creates a
+// branch that must not exist yet. Create, ReferenceExists and ZeroOID
+// need the shared token; agents may call Head, HasReferences and
+// CreateBranch.
//
// Errors are standard gRPC errors. Structured details of landing and commit
// failures are available through LandError, CommitFilesError and the Is*
diff --git a/sdk/repository.go b/sdk/repository.go
index 5057905..203734d 100644
--- a/sdk/repository.go
+++ b/sdk/repository.go
@@ -50,7 +50,8 @@ func (r *Repo) Create(ctx context.Context, opts CreateOptions) error {
// Head returns the full name of the reference that HEAD of the repository
// points to, for example refs/heads/main. The reference may not exist yet, as
-// in a repository without commits.
+// in a repository without commits. A detached HEAD fails with
+// FailedPrecondition. Agents may call it.
func (r *Repo) Head(ctx context.Context) (string, error) {
resp, err := gitalypb.NewRefServiceClient(r.client.conn).FindDefaultBranchName(ctx, &gitalypb.FindDefaultBranchNameRequest{
Repository: r.repository(),
@@ -64,7 +65,7 @@ func (r *Repo) Head(ctx context.Context) (string, error) {
// HasReferences reports whether the repository has any reference at all
// (branches, tags and every other namespace below refs/). It stops reading at
-// the first reference. Like Create, it needs the shared token.
+// the first reference. Agents may call it.
func (r *Repo) HasReferences(ctx context.Context) (bool, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()