Skip to content

Git designed for AI agents.

graft repo create: converge on the requested state with exact checks

Federico Elia075299e1be04
diff --git a/cmd/graft/repo.go b/cmd/graft/repo.go
index fac1c82..897a1db 100644
--- a/cmd/graft/repo.go
+++ b/cmd/graft/repo.go
@@ -6,10 +6,13 @@ import (
"fmt"
"io"
"path"
+ "slices"
"strings"
"google.golang.org/grpc/codes"
+ "github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/graft/workspace"
"github.com/feder-cr/git-ai/sdk"
)
@@ -19,6 +22,27 @@ const repoSynopsis = "usage: graft repo create REPO [--default-branch NAME] [--o
// repoUsage lists the subcommands of graft repo.
const repoUsage = "repo requires a subcommand: create (" + repoSynopsis + ")"
+// repoHelp explains graft repo create below its synopsis.
+const repoHelp = `Creates REPO, or completes it: the command converges on the requested state, so
+running it again after a partial failure finishes the work and changes nothing
+that is done already.
+
+- A missing repository is created. An existing one is AlreadyExists, unless
+ --initial-commit is given.
+- --initial-commit makes the first commit (README.md) on the default branch,
+ so that the repository can be cloned. On an existing repository, HEAD must
+ point to the default branch; the commit is made only when the repository
+ has no reference at all, and is not needed when the default branch exists.
+ A repository with other references but without the default branch is an
+ error.
+- --branch NAME creates NAME at the tip of the default branch, unless it
+ exists.
+
+Creating a repository needs the shared (operator) token. The initial commit
+and the branches pass the server's policy as the user of GRAFT_USER (-user).
+With the storage core in shadow mode the new repository is not tracked until
+graft storage import -repo REPO.`
+
// initialCommitMessage is the message of the commit of --initial-commit.
const initialCommitMessage = "Initial commit"
@@ -44,12 +68,18 @@ func (l *stringList) Set(value string) error {
type repoCreateResult struct {
Repository string `json:"repository"`
Storage string `json:"storage"`
- // Created is false when the repository existed already, empty, and the
- // command only added the initial commit.
- Created bool `json:"created"`
- DefaultBranch string `json:"default_branch"`
- InitialCommit string `json:"initial_commit,omitempty"`
- Branches []string `json:"branches,omitempty"`
+ // Created is false when the repository existed already.
+ Created bool `json:"created"`
+ DefaultBranch string `json:"default_branch"`
+ // InitialCommit is the tip of the default branch with --initial-commit,
+ // and InitialCommitCreated whether this run made it.
+ InitialCommit string `json:"initial_commit,omitempty"`
+ InitialCommitCreated bool `json:"initial_commit_created,omitempty"`
+ BranchesCreated []string `json:"branches_created,omitempty"`
+ BranchesExisting []string `json:"branches_existing,omitempty"`
+ // Untracked is true when the storage core runs in shadow mode and does not
+ // track the repository yet (graft storage import).
+ Untracked bool `json:"untracked,omitempty"`
}
// repoCommand returns the repo command, the operator's creation of
@@ -59,13 +89,13 @@ func repoCommand() command {
return command{
bind: func(fs *flag.FlagSet, o *options) {
fs.Usage = func() {
- fmt.Fprintf(fs.Output(), "%s\n\nCreating a repository needs the shared (operator) token.\n\nflags:\n", repoSynopsis)
+ fmt.Fprintf(fs.Output(), "%s\n\n%s\n\nflags:\n", repoSynopsis, repoHelp)
fs.PrintDefaults()
}
fs.StringVar(&f.defaultBranch, "default-branch", "main", "the branch HEAD points to, and the branch of the initial commit")
- fs.StringVar(&f.objectFormat, "object-format", "", "the object hash, sha1 or sha256 (default: the server's)")
- fs.BoolVar(&f.initialCommit, "initial-commit", false, "also make a first commit (README.md) on the default branch, so that the repository can be cloned; on an existing repository without branches, only make that commit")
- fs.Var(&f.branches, "branch", "with --initial-commit, also create this branch at the initial commit (may be repeated)")
+ fs.StringVar(&f.objectFormat, "object-format", "", "the object hash of a new repository, sha1 or sha256 (default: the server's)")
+ fs.BoolVar(&f.initialCommit, "initial-commit", false, "make sure the default branch has a commit: make the first commit (README.md) of a repository without references")
+ fs.Var(&f.branches, "branch", "with --initial-commit, make sure this branch exists: create it at the tip of the default branch (may be repeated)")
fs.BoolVar(&o.jsonOut, "json", false, "print the result as one JSON object")
},
run: func(ctx context.Context, out io.Writer, o *options, args []string) error {
@@ -86,15 +116,38 @@ func cmdRepo(ctx context.Context, out io.Writer, o *options, f *repoFlags, args
return repoCreate(ctx, out, o, f, args[1:])
}
+// repoProgress records what a run of graft repo create did and what it has
+// left, for the error of a partial failure.
+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.
+func (p *repoProgress) fail(relativePath string, err error) error {
+ report := ""
+ if len(p.done) > 0 {
+ report += "\ndone: " + strings.Join(p.done, "; ")
+ }
+ if len(p.left) > 0 {
+ report += "\nleft: " + strings.Join(p.left, "; ")
+ }
+ 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)
+ }
+ return fmt.Errorf("repository %s: %w%s\nrun the same command again to finish", displayText(relativePath), err, report)
+}
+
func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, args []string) error {
if len(args) != 1 || args[0] == "" {
return usagef("repo create takes one repository path: %s", repoSynopsis)
}
relativePath := args[0]
- defaultBranch := strings.TrimPrefix(f.defaultBranch, "refs/heads/")
+ defaultBranch, branches, err := repoBranches(f)
+ if err != nil {
+ return err
+ }
switch {
- case defaultBranch == "":
- return usagef("repo create: --default-branch must not be empty")
case f.objectFormat != "" && f.objectFormat != "sha1" && f.objectFormat != "sha256":
return usagef("repo create: --object-format must be sha1 or sha256, not %q", f.objectFormat)
case len(f.branches) > 0 && !f.initialCommit:
@@ -118,45 +171,55 @@ func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, ar
registerCloser(ctx, client)
repo := client.Repo(relativePath)
- res := repoCreateResult{Repository: relativePath, Storage: client.Storage(), Created: true, DefaultBranch: defaultBranch}
+ res := repoCreateResult{Repository: relativePath, Storage: client.Storage(), DefaultBranch: defaultBranch}
+ progress := &repoProgress{}
+ if f.initialCommit {
+ progress.left = append(progress.left, "initial commit on "+defaultBranch)
+ }
+ for _, branch := range branches {
+ progress.left = append(progress.left, "branch "+branch)
+ }
+
err = repo.Create(ctx, sdk.CreateOptions{DefaultBranch: defaultBranch, ObjectFormat: f.objectFormat})
switch {
- case sdk.IsAlreadyExists(err) && f.initialCommit:
- // A repository without branches is the one an earlier run created before
- // its initial commit failed: make that commit now.
- hasBranches, checkErr := repo.HasBranches(ctx)
- if checkErr != nil {
- return withOperatorHint(checkErr)
+ case err == nil:
+ res.Created = true
+ progress.done = append(progress.done, "created the repository")
+ // The storage core's mode is best effort: a server that cannot report
+ // it (an older one) gets the hint of the help text only.
+ if state, stateErr := repo.StorageState(ctx); stateErr == nil && state.Mode == "shadow" && !state.Tracked {
+ res.Untracked = true
}
- if hasBranches {
- return fmt.Errorf("repository %s exists already and has branches", displayText(relativePath))
- }
- res.Created = false
+ case sdk.IsAlreadyExists(err) && f.initialCommit:
+ // Complete the existing repository below.
case sdk.IsAlreadyExists(err):
return fmt.Errorf("repository %s exists already", displayText(relativePath))
- case err != nil:
+ default:
return withOperatorHint(err)
}
if f.initialCommit {
user := sdk.User{ID: pick(o.user, anonymousUser), Username: pick(o.user, anonymousUser), Name: author.Name, Email: author.Email}
- commit, err := repo.CommitFiles(ctx, sdk.CommitOptions{
- Branch: defaultBranch,
- Message: initialCommitMessage,
- Author: sdk.Signature{Name: author.Name, Email: author.Email},
- User: user,
- Actions: []sdk.Action{sdk.Put{Path: "README.md", Content: []byte("# " + repositoryName(relativePath) + "\n")}},
- })
+ tip, created, err := ensureInitialCommit(ctx, repo, defaultBranch, user, author)
if err != nil {
- return fmt.Errorf("repository %s has no initial commit: %w (run the same command again to add it)", displayText(relativePath), withUserHint(err, o.user))
+ return progress.fail(relativePath, err)
}
- res.InitialCommit = commit.CommitID
+ res.InitialCommit, res.InitialCommitCreated = tip, created
+ progress.left = progress.left[1:]
+ progress.done = append(progress.done, "initial commit "+tip+" on "+defaultBranch)
- for _, branch := range f.branches {
- if _, err := repo.Land(ctx, sdk.LandOptions{Branch: branch, Commit: commit.CommitID, CreateBranch: true, User: user}); err != nil {
- return fmt.Errorf("creating branch %s at the initial commit %s: %w", displayText(branch), commit.CommitID, withUserHint(err, o.user))
+ for _, branch := range branches {
+ created, err := ensureBranch(ctx, repo, branch, tip, user)
+ if err != nil {
+ return progress.fail(relativePath, err)
}
- res.Branches = append(res.Branches, branch)
+ if created {
+ res.BranchesCreated = append(res.BranchesCreated, branch)
+ } else {
+ res.BranchesExisting = append(res.BranchesExisting, branch)
+ }
+ progress.left = progress.left[1:]
+ progress.done = append(progress.done, "branch "+branch)
}
}
@@ -166,17 +229,137 @@ func repoCreate(ctx context.Context, out io.Writer, o *options, f *repoFlags, ar
if res.Created {
fmt.Fprintf(out, "created repository %s on storage %s\n", displayText(relativePath), displayText(res.Storage))
} else {
- fmt.Fprintf(out, "repository %s exists without branches: adding the initial commit\n", displayText(relativePath))
+ fmt.Fprintf(out, "repository %s exists\n", displayText(relativePath))
}
if res.InitialCommit != "" {
- fmt.Fprintf(out, "initial commit %s on %s\n", res.InitialCommit, displayText(defaultBranch))
+ verb := "is"
+ if res.InitialCommitCreated {
+ verb = "created as"
+ }
+ fmt.Fprintf(out, "%s %s %s\n", displayText(defaultBranch), verb, res.InitialCommit)
}
- for _, branch := range res.Branches {
+ for _, branch := range res.BranchesCreated {
fmt.Fprintf(out, "created branch %s at %s\n", displayText(branch), res.InitialCommit)
}
+ for _, branch := range res.BranchesExisting {
+ fmt.Fprintf(out, "branch %s exists\n", displayText(branch))
+ }
+ if res.Untracked {
+ fmt.Fprintf(out, "the storage core runs in shadow mode: run graft storage import -repo %s to track the repository\n", displayText(relativePath))
+ }
return nil
}
+// repoBranches validates the branch names of graft repo create with git's
+// reference 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 == "" {
+ 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 == "" {
+ return "", nil, usagef("repo create: invalid --branch %q", branch)
+ }
+ if name != defaultBranch && !slices.Contains(branches, name) {
+ branches = append(branches, name)
+ }
+ }
+ return defaultBranch, branches, 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
+// reference, and only if the default branch still does not exist when it is
+// written (ExpectedOldOID is the zero object ID): a concurrent run that made it
+// first is found by reading the branch again.
+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 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/")))
+ }
+
+ if tip, ok, err := branchTip(ctx, repo, ref); err != nil || ok {
+ return tip, false, err
+ }
+ hasReferences, err := repo.HasReferences(ctx)
+ if err != nil {
+ return "", false, fmt.Errorf("listing references: %w", err)
+ }
+ if hasReferences {
+ // A concurrent run may have made the initial commit since the branch was
+ // read: its references are the default branch's.
+ 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))
+ }
+
+ zero, err := repo.ZeroOID(ctx)
+ if err != nil {
+ return "", false, fmt.Errorf("reading the object format: %w", err)
+ }
+ commit, commitErr := repo.CommitFiles(ctx, sdk.CommitOptions{
+ Branch: defaultBranch,
+ ExpectedOldOID: zero,
+ Message: initialCommitMessage,
+ Author: sdk.Signature{Name: author.Name, Email: author.Email},
+ User: user,
+ Actions: []sdk.Action{sdk.Put{Path: "README.md", Content: []byte("# " + repositoryName(repo.RelativePath()) + "\n")}},
+ })
+ if commitErr == nil {
+ return commit.CommitID, true, nil
+ }
+ if tip, ok, err := branchTip(ctx, repo, ref); err == nil && ok {
+ return tip, false, nil
+ }
+ return "", false, fmt.Errorf("initial commit on %s: %w", displayText(defaultBranch), commitErr)
+}
+
+// ensureBranch makes sure branch exists, creating it at tip, and reports
+// whether this call created it. A branch created concurrently is found by
+// checking again after a failed creation.
+func ensureBranch(ctx context.Context, repo *sdk.Repo, branch, tip string, user sdk.User) (bool, error) {
+ ref := "refs/heads/" + branch
+ exists, err := repo.ReferenceExists(ctx, ref)
+ if err != nil {
+ return false, fmt.Errorf("checking branch %s: %w", displayText(branch), err)
+ }
+ if exists {
+ return false, nil
+ }
+ createErr := repo.CreateBranch(ctx, sdk.CreateBranchOptions{Branch: branch, StartPoint: tip, User: user})
+ if createErr == nil {
+ return true, nil
+ }
+ if exists, err := repo.ReferenceExists(ctx, ref); err == nil && exists {
+ return false, nil
+ }
+ return false, fmt.Errorf("creating branch %s: %w", displayText(branch), createErr)
+}
+
+// branchTip returns the commit of the branch ref (a full name), read by its
+// exact name, and whether it exists.
+func branchTip(ctx context.Context, repo *sdk.Repo, ref string) (string, bool, error) {
+ exists, err := repo.ReferenceExists(ctx, ref)
+ if err != nil || !exists {
+ return "", false, err
+ }
+ tip, err := repo.ResolveRevision(ctx, ref)
+ if err != nil {
+ return "", false, fmt.Errorf("reading %s: %w", displayText(ref), err)
+ }
+ return tip, true, nil
+}
+
// repositoryName is the name of the repository at relativePath, for its
// README: the last path element without .git.
func repositoryName(relativePath string) string {
diff --git a/cmd/graft/repo_test.go b/cmd/graft/repo_test.go
index 7bc24fb..255e992 100644
--- a/cmd/graft/repo_test.go
+++ b/cmd/graft/repo_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"path/filepath"
"strings"
+ "sync"
"testing"
"github.com/stretchr/testify/require"
@@ -21,59 +22,66 @@ import (
"github.com/feder-cr/git-ai/sdk"
)
-// repoCreated is the JSON output of graft repo create.
-type repoCreated struct {
- Repository string `json:"repository"`
- Storage string `json:"storage"`
- Created bool `json:"created"`
- DefaultBranch string `json:"default_branch"`
- InitialCommit string `json:"initial_commit"`
- Branches []string `json:"branches"`
+// repoCLI runs graft repo create against server and decodes its JSON output
+// when the command succeeds.
+func repoCLI(t *testing.T, server []string, args ...string) (int, repoCreateResult, string) {
+ t.Helper()
+ code, stdout, stderr := runCLI(t, append(append(append([]string{"repo", "create"}, args...), server...), "--json")...)
+ var res repoCreateResult
+ if code == exitOK {
+ require.NoError(t, json.Unmarshal([]byte(stdout), &res), stdout)
+ }
+ return code, res, stderr
+}
+
+// requireRefs checks the references of the repository at path: name to commit.
+func requireRefs(t *testing.T, cfg config.Cfg, path string, want map[string]string) {
+ t.Helper()
+ out := gittest.Exec(t, cfg, "-C", path, "for-each-ref", "--format=%(refname) %(objectname)")
+ got := map[string]string{}
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ if name, oid, ok := strings.Cut(line, " "); ok {
+ got[name] = oid
+ }
+ }
+ require.Equal(t, want, got)
}
// TestCLIRepoCreateAgainstServer drives graft repo create against a server
-// without a storage core: an empty repository, a repository that exists
-// already, a repository with its initial commit and a second branch that the
-// CLI then clones, and the retry that adds the initial commit to an existing
-// empty repository. It runs serially because the CLI tests share the
-// package-level backend factory.
+// without a storage core: an empty repository, AlreadyExists, a repository
+// with its initial commit and a second branch that the CLI then clones, and a
+// run on the complete repository that changes nothing. It runs serially because
+// the CLI tests share the package-level backend factory.
func TestCLIRepoCreateAgainstServer(t *testing.T) {
env := startServer(t)
server := []string{"-address", env.addr, "-storage", env.storage}
- create := func(args ...string) (int, string, string) {
- return runCLI(t, append(append([]string{"repo", "create"}, args...), server...)...)
- }
- b := env.backend(t)
+ storagePath := env.cfg.Storages[0].Path
- code, stdout, stderr := create("empty.git")
+ code, stdout, stderr := runCLI(t, append([]string{"repo", "create", "empty.git"}, server...)...)
require.Equal(t, exitOK, code, stderr)
require.Equal(t, "created repository empty.git on storage "+env.storage+"\n", stdout)
- require.DirExists(t, filepath.Join(env.cfg.Storages[0].Path, "empty.git"))
+ requireRefs(t, env.cfg, filepath.Join(storagePath, "empty.git"), map[string]string{})
- code, _, stderr = create("empty.git")
+ code, _, stderr = repoCLI(t, server, "empty.git")
require.Equal(t, exitError, code)
require.Contains(t, stderr, "repository empty.git exists already\n")
// The initial commit and a second branch make the repository clonable.
- code, stdout, stderr = create("seeded.git", "--initial-commit", "--branch", "feature/demo", "--json")
+ code, seeded, stderr := repoCLI(t, server, "seeded.git", "--initial-commit", "--branch", "feature/demo")
require.Equal(t, exitOK, code, stderr)
- var seeded repoCreated
- require.NoError(t, json.Unmarshal([]byte(stdout), &seeded))
- require.Equal(t, repoCreated{
- Repository: "seeded.git",
- Storage: env.storage,
- Created: true,
- DefaultBranch: "main",
- InitialCommit: seeded.InitialCommit,
- Branches: []string{"feature/demo"},
+ require.Equal(t, repoCreateResult{
+ Repository: "seeded.git",
+ Storage: env.storage,
+ Created: true,
+ DefaultBranch: "main",
+ InitialCommit: seeded.InitialCommit,
+ InitialCommitCreated: true,
+ BranchesCreated: []string{"feature/demo"},
}, seeded)
- repo := b.client.Repo("seeded.git")
- for _, branch := range []string{"main", "feature/demo"} {
- commit, err := repo.ResolveRevision(env.ctx, branch)
- require.NoError(t, err, branch)
- require.Equal(t, seeded.InitialCommit, commit, branch)
- }
- readme, err := repo.ReadFile(env.ctx, "main", "README.md")
+ requireRefs(t, env.cfg, filepath.Join(storagePath, "seeded.git"), map[string]string{
+ "refs/heads/main": seeded.InitialCommit, "refs/heads/feature/demo": seeded.InitialCommit,
+ })
+ readme, err := env.backend(t).client.Repo("seeded.git").ReadFile(env.ctx, "main", "README.md")
require.NoError(t, err)
require.Equal(t, "# seeded\n", string(readme))
@@ -82,33 +90,119 @@ func TestCLIRepoCreateAgainstServer(t *testing.T) {
require.Equal(t, exitOK, code, stderr)
require.FileExists(t, filepath.Join(dir, "README.md"))
- // An earlier run that created the repository but not its initial commit is
- // completed by running the command again.
- code, _, stderr = create("empty.git", "--initial-commit")
- require.Equal(t, exitOK, code, stderr)
- code, stdout, stderr = create("resumed.git")
+ // The same command again converges: nothing is created.
+ code, stdout, stderr = runCLI(t, append([]string{"repo", "create", "seeded.git", "--initial-commit", "--branch", "feature/demo"}, server...)...)
require.Equal(t, exitOK, code, stderr)
- code, stdout, stderr = create("resumed.git", "--initial-commit", "--default-branch", "trunk")
- require.Equal(t, exitOK, code, stderr)
- require.Regexp(t, `^repository resumed.git exists without branches: adding the initial commit\ninitial commit [0-9a-f]+ on trunk\n$`, stdout)
- _, err = b.client.Repo("resumed.git").ResolveRevision(env.ctx, "trunk")
- require.NoError(t, err)
+ require.Equal(t, "repository seeded.git exists\nmain is "+seeded.InitialCommit+"\nbranch feature/demo exists\n", stdout)
- // A repository with branches is not touched again.
- code, _, stderr = create("resumed.git", "--initial-commit")
- require.Equal(t, exitError, code)
- require.Contains(t, stderr, "repository resumed.git exists already and has branches\n")
-
- code, stdout, stderr = create("sha256.git", "--object-format", "sha256", "--initial-commit", "--json")
+ code, sha256Repo, stderr := repoCLI(t, server, "sha256.git", "--object-format", "sha256", "--initial-commit")
require.Equal(t, exitOK, code, stderr)
- var sha256Repo repoCreated
- require.NoError(t, json.Unmarshal([]byte(stdout), &sha256Repo))
require.Len(t, sha256Repo.InitialCommit, 64)
}
+// TestCLIRepoCreateConverges runs graft repo create on existing repositories in
+// the states that a partial failure or another client leaves, and checks that it
+// completes them exactly or refuses without writing anything.
+func TestCLIRepoCreateConverges(t *testing.T) {
+ env := startServer(t)
+ server := []string{"-address", env.addr, "-storage", env.storage}
+ storagePath := env.cfg.Storages[0].Path
+
+ t.Run("empty repository gets its initial commit", func(t *testing.T) {
+ code, _, stderr := repoCLI(t, server, "resumed.git")
+ require.Equal(t, exitOK, code, stderr)
+ code, res, stderr := repoCLI(t, server, "resumed.git", "--initial-commit", "--branch", "next")
+ require.Equal(t, exitOK, code, stderr)
+ require.False(t, res.Created)
+ require.True(t, res.InitialCommitCreated)
+ requireRefs(t, env.cfg, filepath.Join(storagePath, "resumed.git"), map[string]string{
+ "refs/heads/main": res.InitialCommit, "refs/heads/next": res.InitialCommit,
+ })
+ })
+
+ t.Run("HEAD on another branch", func(t *testing.T) {
+ code, _, stderr := repoCLI(t, server, "trunk.git", "--default-branch", "trunk")
+ require.Equal(t, exitOK, code, stderr)
+
+ // The default branch of the command is main, but HEAD points to trunk.
+ 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")
+ 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")
+ require.Equal(t, exitOK, code, stderr)
+ requireRefs(t, env.cfg, filepath.Join(storagePath, "trunk.git"), map[string]string{"refs/heads/trunk": res.InitialCommit})
+ })
+
+ t.Run("references but no default branch", func(t *testing.T) {
+ for _, ref := range []string{"refs/tags/v1", "refs/merge-requests/1/head"} {
+ rel := strings.ReplaceAll(ref, "/", "-") + ".git"
+ code, _, stderr := repoCLI(t, server, rel)
+ require.Equal(t, exitOK, code, stderr)
+ path := filepath.Join(storagePath, rel)
+ commit := gittest.WriteCommit(t, env.cfg, path, gittest.WithReference(ref))
+
+ 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)
+ requireRefs(t, env.cfg, path, map[string]string{ref: 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)
+ path := filepath.Join(storagePath, "existing.git")
+ commit := gittest.WriteCommit(t, env.cfg, path, gittest.WithBranch("main"))
+
+ code, res, stderr := repoCLI(t, server, "existing.git", "--initial-commit", "--branch", "side", "--branch", "side", "--branch", "main")
+ require.Equal(t, exitOK, code, stderr)
+ require.Equal(t, commit.String(), res.InitialCommit)
+ require.False(t, res.InitialCommitCreated)
+ require.Equal(t, []string{"side"}, res.BranchesCreated, "duplicates and the default branch are dropped")
+ requireRefs(t, env.cfg, path, map[string]string{"refs/heads/main": commit.String(), "refs/heads/side": commit.String()})
+ })
+
+ t.Run("concurrent runs converge", func(t *testing.T) {
+ const runs = 4
+ var wg sync.WaitGroup
+ results := make([]repoCreateResult, runs)
+ codes := make([]int, runs)
+ stderrs := make([]string, runs)
+ for i := 0; i < runs; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ codes[i], results[i], stderrs[i] = repoCLI(t, server, "raced.git", "--initial-commit", "--branch", "feature")
+ }(i)
+ }
+ wg.Wait()
+
+ path := filepath.Join(storagePath, "raced.git")
+ tip := strings.TrimSpace(string(gittest.Exec(t, env.cfg, "-C", path, "rev-parse", "refs/heads/main")))
+ created, commits := 0, 0
+ for i := 0; i < runs; i++ {
+ require.Equal(t, exitOK, codes[i], "run %d: %s", i, stderrs[i])
+ require.Equal(t, tip, results[i].InitialCommit, "run %d", i)
+ if results[i].Created {
+ created++
+ }
+ if results[i].InitialCommitCreated {
+ commits++
+ }
+ }
+ require.Equal(t, 1, created, "one run created the repository")
+ require.Equal(t, 1, commits, "one run made the initial commit")
+ requireRefs(t, env.cfg, path, map[string]string{"refs/heads/main": tip, "refs/heads/feature": tip})
+ })
+}
+
// TestCLIRepoCreateOperatorOnly checks that only the shared token creates a
-// repository: an agent token is refused with a hint, and the operator's initial
-// commit passes the access policy as the configured user.
+// repository, that the initial commit and the branches pass the access policy
+// as the configured user, and that a branch the policy denies is reported as a
+// denial with what is done and left, and is completed by the same command with
+// a user the policy allows.
func TestCLIRepoCreateOperatorOnly(t *testing.T) {
ctx := featureflag.OutgoingCtxWithFeatureFlag(testhelper.Context(t), featureflag.GPGSigning, false)
cfg := testcfg.Build(t)
@@ -117,6 +211,7 @@ func TestCLIRepoCreateOperatorOnly(t *testing.T) {
cfg.Graft.Agents = []config.GraftAgent{{Name: "alice", Token: "alice-secret"}}
cfg.Graft.Policy = []config.GraftPolicyRule{
{Actor: "alice", Refs: []string{"refs/heads/main"}, Allow: true},
+ {Actor: "bob", Refs: []string{"refs/heads/release"}, Allow: true},
{Actor: "*", Allow: false},
}
testcfg.BuildGitalySSH(t, cfg)
@@ -124,16 +219,29 @@ func TestCLIRepoCreateOperatorOnly(t *testing.T) {
addr := testserver.RunGitalyServer(t, cfg, setup.RegisterAll,
testserver.WithGitLabClient(gitlab.NewStandaloneClient(cfg.Graft, testhelper.SharedLogger(t))))
server := []string{"-address", addr, "-storage", cfg.Storages[0].Name}
+ path := filepath.Join(cfg.Storages[0].Path, "a.git")
- code, _, stderr := runCLI(t, append([]string{"repo", "create", "a.git", "-token", "alice-secret"}, server...)...)
+ code, _, stderr := repoCLI(t, append([]string{"-token", "alice-secret"}, server...), "a.git")
require.Equal(t, exitError, code)
require.Contains(t, stderr, "PermissionDenied")
require.Contains(t, stderr, "hint: creating a repository needs the shared (operator) token")
- require.NoDirExists(t, filepath.Join(cfg.Storages[0].Path, "a.git"))
+ require.NoDirExists(t, path)
+
+ operator := append([]string{"-token", "operator-secret"}, server...)
+ code, _, stderr = repoCLI(t, append([]string{"-user", "alice"}, operator...), "a.git", "--initial-commit", "--branch", "release")
+ require.Equal(t, exitError, code)
+ require.Contains(t, stderr, "repository a.git: denied by the server: ")
+ require.Contains(t, stderr, "\ndone: created the repository; initial commit ")
+ require.Contains(t, stderr, "\nleft: branch release\n")
+ require.Contains(t, stderr, "the same command is denied again until the policy allows")
+ require.NotContains(t, stderr, "run the same command again")
- code, stdout, stderr := runCLI(t, append([]string{"repo", "create", "a.git", "--initial-commit", "-token", "operator-secret", "-user", "alice"}, server...)...)
+ code, res, stderr := repoCLI(t, append([]string{"-user", "bob"}, operator...), "a.git", "--initial-commit", "--branch", "release")
require.Equal(t, exitOK, code, stderr)
- require.Contains(t, stdout, "created repository a.git")
+ require.False(t, res.Created)
+ require.False(t, res.InitialCommitCreated)
+ require.Equal(t, []string{"release"}, res.BranchesCreated)
+ requireRefs(t, cfg, path, map[string]string{"refs/heads/main": res.InitialCommit, "refs/heads/release": res.InitialCommit})
client, err := sdk.Dial(ctx, addr, sdk.WithStorage(cfg.Storages[0].Name), sdk.WithAgentToken("alice-secret"))
require.NoError(t, err)
@@ -143,42 +251,50 @@ func TestCLIRepoCreateOperatorOnly(t *testing.T) {
require.Equal(t, "# a\n", string(readme))
}
-// TestCLIRepoCreateAuthoritative checks that a repository created by graft repo
-// create on a server whose storage core is authoritative is registered there,
-// with its initial commit, and that the storage core's verification finds the
-// local copy equal to the database. It runs serially because the CLI tests
-// share the package-level backend factory.
-func TestCLIRepoCreateAuthoritative(t *testing.T) {
- cfg := testcfg.Build(t)
- cfg.Graft.Standalone = true
- testcfg.BuildGitalySSH(t, cfg)
- testcfg.BuildGitalyHooks(t, cfg)
- core := coretest.Open(t, coretest.Options{Mode: corestore.ModeAuthoritative})
- addr := testserver.RunGitalyServer(t, cfg, setup.RegisterAll, testserver.WithGraftStorage(core))
- target := []string{"-address", addr, "-storage", cfg.Storages[0].Name}
+// TestCLIRepoCreateStorageCore checks graft repo create with a storage core: in
+// authoritative mode the repository is registered with its initial commit and
+// the verification finds the local copy equal to the database; in shadow mode
+// the command says that the repository is not tracked yet. It runs serially
+// because the CLI tests share the package-level backend factory.
+func TestCLIRepoCreateStorageCore(t *testing.T) {
+ for _, mode := range []corestore.Mode{corestore.ModeAuthoritative, corestore.ModeShadow} {
+ t.Run(string(mode), func(t *testing.T) {
+ cfg := testcfg.Build(t)
+ cfg.Graft.Standalone = true
+ testcfg.BuildGitalySSH(t, cfg)
+ testcfg.BuildGitalyHooks(t, cfg)
+ core := coretest.Open(t, coretest.Options{Mode: mode})
+ addr := testserver.RunGitalyServer(t, cfg, setup.RegisterAll, testserver.WithGraftStorage(core))
+ target := []string{"-address", addr, "-storage", cfg.Storages[0].Name}
- code, stdout, stderr := runCLI(t, append([]string{"repo", "create", "core.git", "--initial-commit", "--branch", "feature/demo", "--json"}, target...)...)
- require.Equal(t, exitOK, code, stderr)
- var created repoCreated
- require.NoError(t, json.Unmarshal([]byte(stdout), &created))
+ code, stdout, stderr := runCLI(t, append([]string{"repo", "create", "core.git", "--initial-commit", "--branch", "feature/demo"}, target...)...)
+ require.Equal(t, exitOK, code, stderr)
+ hint := "the storage core runs in shadow mode: run graft storage import -repo core.git to track the repository\n"
+ if mode == corestore.ModeShadow {
+ require.Contains(t, stdout, hint)
+ return
+ }
+ require.NotContains(t, stdout, hint)
- code, stdout, stderr = runCLI(t, append([]string{"storage", "state", "--json", "-repo", "core.git"}, target...)...)
- require.Equal(t, exitOK, code, stderr)
- var state sdk.StorageState
- require.NoError(t, json.Unmarshal([]byte(stdout), &state))
- require.True(t, state.Tracked)
- require.EqualValues(t, 3, state.HeadSequence, "the creation, the initial commit and the branch")
+ code, stdout, stderr = runCLI(t, append([]string{"storage", "state", "--json", "-repo", "core.git"}, target...)...)
+ require.Equal(t, exitOK, code, stderr)
+ var state sdk.StorageState
+ require.NoError(t, json.Unmarshal([]byte(stdout), &state))
+ require.True(t, state.Tracked)
+ require.EqualValues(t, 3, state.HeadSequence, "the creation, the initial commit and the branch")
- code, stdout, stderr = runCLI(t, append([]string{"storage", "verify", "--connectivity", "-repo", "core.git"}, target...)...)
- require.Equal(t, exitOK, code, stderr)
- require.Equal(t, "head sequence 3\nconnectivity ok\nconsistent\n", stdout)
- format := gittest.Exec(t, cfg, "-C", filepath.Join(cfg.Storages[0].Path, "core.git"), "rev-parse", "--show-ref-format")
- require.Equal(t, "reftable", strings.TrimSpace(string(format)), "authoritative mode creates reftable repositories")
+ code, stdout, stderr = runCLI(t, append([]string{"storage", "verify", "--connectivity", "-repo", "core.git"}, target...)...)
+ require.Equal(t, exitOK, code, stderr)
+ require.Equal(t, "head sequence 3\nconnectivity ok\nconsistent\n", stdout)
+ format := gittest.Exec(t, cfg, "-C", filepath.Join(cfg.Storages[0].Path, "core.git"), "rev-parse", "--show-ref-format")
+ require.Equal(t, "reftable", strings.TrimSpace(string(format)), "authoritative mode creates reftable repositories")
+ })
+ }
}
-// TestCLIRepoUsageErrorsDoNotContactServer checks the arguments of graft repo
-// before any server call: the address points nowhere, so a server call would
-// fail with a different error.
+// TestCLIRepoUsageErrorsDoNotContactServer checks the arguments of graft repo,
+// the branch names included, before any server call: the address points
+// nowhere, so a server call would fail with a different error.
func TestCLIRepoUsageErrorsDoNotContactServer(t *testing.T) {
nowhere := []string{"-address", "unix://" + filepath.Join(t.TempDir(), "missing.sock")}
@@ -190,6 +306,10 @@ func TestCLIRepoUsageErrorsDoNotContactServer(t *testing.T) {
"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]>"},
}
for name, args := range cases {
@@ -203,7 +323,7 @@ func TestCLIRepoUsageErrorsDoNotContactServer(t *testing.T) {
}
// TestCLIRepoHelp checks that graft help lists the repo command and that its
-// help shows the synopsis.
+// help shows the synopsis and the rules.
func TestCLIRepoHelp(t *testing.T) {
code, stdout, _ := runCLI(t, "help")
require.Equal(t, exitOK, code)
@@ -213,6 +333,7 @@ func TestCLIRepoHelp(t *testing.T) {
require.Equal(t, exitOK, code, stderr)
require.Contains(t, stderr, repoSynopsis)
require.Contains(t, stderr, "shared (operator) token")
+ require.Contains(t, stderr, "graft storage import -repo REPO")
code, _, stderr = runCLI(t, "repo")
require.Equal(t, exitUsage, code, stderr)
diff --git a/doc/graft/LIMITATIONS.md b/doc/graft/LIMITATIONS.md
index 0fa7f15..84c7b18 100644
--- a/doc/graft/LIMITATIONS.md
+++ b/doc/graft/LIMITATIONS.md
@@ -138,9 +138,7 @@ Git hooks use private.
the shared token: agents may not create repositories. In shadow mode the new
repository is not tracked until `graft storage import`.
- `graft clone` needs the branch to exist. An empty repository cannot be cloned:
- `graft repo create --initial-commit` gives it a first commit. The CLI and the
- workspace cannot make the first commit of a repository created without it;
- the SDK can (`CommitFiles` onto the default branch, without `StartRev`).
+ `graft repo create --initial-commit` gives it a first commit.
- Durability of written objects assumes a local journaling filesystem, ext4 (in
any `data=` mode) or xfs, not NFS. The objects of a write are made durable by
their writer, and the migration of the write's quarantine into the repository
diff --git a/doc/graft/QUICKSTART.md b/doc/graft/QUICKSTART.md
index 7d00589..a3c59a0 100644
--- a/doc/graft/QUICKSTART.md
+++ b/doc/graft/QUICKSTART.md
@@ -78,8 +78,9 @@ graft repo create demo.git --initial-commit --branch feature/demo
The initial commit passes the policy like any write, as the user of
`GRAFT_USER`: here `planner`, who may write `main`. `--branch feature/demo`
also creates `feature/demo` at the initial commit, which the builder lands on
-below. If the initial commit fails, run the same command again: on a
-repository without branches it only adds the commit.
+below. The command converges on the state it asks for: if it fails part way,
+run it again, and it does only what is left (`graft repo create -h` has the
+rules).
## 5. Start the cache daemon
diff --git a/examples/graft/quickstart.sh b/examples/graft/quickstart.sh
index c72853c..798992a 100644
--- a/examples/graft/quickstart.sh
+++ b/examples/graft/quickstart.sh
@@ -6,7 +6,8 @@
# Usage: examples/graft/quickstart.sh [WORKDIR]
# Requires: the Gitaly build dependencies (Go, make, and what the bundled Git
# needs to compile, see "Installation" in the Gitaly part of README.md),
-# openssl, and curl (optional, for the cache statistics).
+# git (make build uses it), openssl, and curl (optional, for the cache
+# statistics).
# WORKDIR defaults to a fresh temporary directory.
#
# The steps mirror doc/graft/QUICKSTART.md. The script assumes a Git checkout
diff --git a/internal/gitaly/server/auth/agent_allowlist_test.go b/internal/gitaly/server/auth/agent_allowlist_test.go
index 6181ee7..6ffecd6 100644
--- a/internal/gitaly/server/auth/agent_allowlist_test.go
+++ b/internal/gitaly/server/auth/agent_allowlist_test.go
@@ -448,17 +448,32 @@ func TestAgentAllowlist_ConcurrentDecisions(t *testing.T) {
var sdkCLIDriftAllowance = map[string]string{}
// operatorOnlySources lists the SDK and CLI files whose calls are operator actions
-// rather than agent actions, with the gRPC service they may use outside the agent
-// allowlist. The storage core's administration (`graft storage import|state|verify`,
-// sdk/storage.go) runs with the server's shared token (doc/graft/STORAGE.md), so
-// agents are not meant to be allowed its RPCs. So does the creation of a repository
-// (`graft repo create`, sdk/repository.go), which agents may never call. The scan
-// checks these files separately: every RPC they call must be agent-allowed or belong
-// to the listed service, and each file must still call that service (so an entry
+// rather than agent actions, with the RPCs they may call outside the agent
+// allowlist: a whole gRPC service ("gitaly.StorageCoreService") or one method
+// ("gitaly.RepositoryService/CreateRepository"). The storage core's administration
+// (`graft storage import|state|verify`, sdk/storage.go) runs with the server's shared
+// token (doc/graft/STORAGE.md), so agents are not meant to be allowed its RPCs. So
+// does the creation of a repository (`graft repo create`, sdk/repository.go): agents
+// may never create one, and its exact checks read the object format and whether a
+// reference exists. The scan checks these files separately: every RPC they call must
+// be agent-allowed or listed here, and each entry must still be called (so an entry
// cannot go stale).
-var operatorOnlySources = map[string]string{
- "sdk/storage.go": "gitaly.StorageCoreService",
- "sdk/repository.go": "gitaly.RepositoryService",
+var operatorOnlySources = map[string][]string{
+ "sdk/storage.go": {"gitaly.StorageCoreService"},
+ "sdk/repository.go": {
+ "gitaly.RepositoryService/CreateRepository",
+ "gitaly.RepositoryService/ObjectFormat",
+ "gitaly.RefService/RefExists",
+ },
+}
+
+// operatorScopeCovers reports whether fullMethod is the method, or a method of the
+// service, that scope names in operatorOnlySources.
+func operatorScopeCovers(scope, fullMethod string) bool {
+ if strings.Contains(scope, "/") {
+ return fullMethod == "/"+scope
+ }
+ return strings.HasPrefix(fullMethod, "/"+scope+"/")
}
// sourceMethodCall matches a Go method call such as `refs.DeleteRefs(ctx, ...)`
@@ -492,19 +507,26 @@ func TestAgentAllowlist_SourceScanMatchesSDKAndCLI(t *testing.T) {
methodsByName[name] = append(methodsByName[name], fullMethod)
}
- for file, service := range operatorOnlySources {
- usesService := false
+ for file, scopes := range operatorOnlySources {
+ used := map[string]bool{}
for name := range operatorCalls[file] {
for _, fullMethod := range methodsByName[name] {
- if strings.HasPrefix(fullMethod, "/"+service+"/") {
- usesService = true
+ covered := false
+ for _, scope := range scopes {
+ if operatorScopeCovers(scope, fullMethod) {
+ used[scope], covered = true, true
+ }
+ }
+ if covered {
continue
}
require.True(t, allowlist.mayCall(fullMethod),
- "%s is an operator-only source for %s but also calls %s, which agents may not call", file, service, fullMethod)
+ "%s is an operator-only source for %v but also calls %s, which agents may not call", file, scopes, fullMethod)
}
}
- require.True(t, usesService, "%s is in operatorOnlySources but no longer calls %s; remove the entry", file, service)
+ for _, scope := range scopes {
+ require.True(t, used[scope], "%s is in operatorOnlySources for %s but no longer calls it; remove the entry", file, scope)
+ }
}
var denied []string
diff --git a/internal/graft/e2e/repo_create_test.go b/internal/graft/e2e/repo_create_test.go
index c422703..86dbcd5 100644
--- a/internal/graft/e2e/repo_create_test.go
+++ b/internal/graft/e2e/repo_create_test.go
@@ -47,7 +47,7 @@ func TestRepoCreateWithTheCLI(t *testing.T) {
Created bool `json:"created"`
DefaultBranch string `json:"default_branch"`
InitialCommit string `json:"initial_commit"`
- Branches []string `json:"branches"`
+ Branches []string `json:"branches_created"`
}
out := runGraft(t, bin, operator, "repo", "create", rel, "--initial-commit", "--branch", "feature/demo", "--json")
require.NoError(t, json.Unmarshal([]byte(out), &created))
diff --git a/sdk/doc.go b/sdk/doc.go
index 43adcb1..288e196 100644
--- a/sdk/doc.go
+++ b/sdk/doc.go
@@ -15,9 +15,10 @@
// 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, and HasBranches tells whether it
-// is still empty (RepositoryService; operators only, with the shared
-// token).
+// - 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.
//
// 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 f462bb9..5057905 100644
--- a/sdk/repository.go
+++ b/sdk/repository.go
@@ -2,6 +2,9 @@ package sdk
import (
"context"
+ "errors"
+ "io"
+ "strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -45,12 +48,58 @@ func (r *Repo) Create(ctx context.Context, opts CreateOptions) error {
return err
}
-// HasBranches reports whether the repository has at least one branch. It
-// fails with NotFound if the repository does not exist. Like Create, it needs
-// the shared token.
-func (r *Repo) HasBranches(ctx context.Context) (bool, error) {
- resp, err := r.repositories().HasLocalBranches(ctx, &gitalypb.HasLocalBranchesRequest{
+// 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.
+func (r *Repo) Head(ctx context.Context) (string, error) {
+ resp, err := gitalypb.NewRefServiceClient(r.client.conn).FindDefaultBranchName(ctx, &gitalypb.FindDefaultBranchNameRequest{
Repository: r.repository(),
+ HeadOnly: true,
+ })
+ if err != nil {
+ return "", err
+ }
+ return string(resp.GetName()), nil
+}
+
+// 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.
+func (r *Repo) HasReferences(ctx context.Context) (bool, error) {
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ stream, err := gitalypb.NewRefServiceClient(r.client.conn).ListRefs(ctx, &gitalypb.ListRefsRequest{
+ Repository: r.repository(),
+ Patterns: [][]byte{[]byte("refs/")},
+ })
+ if err != nil {
+ return false, err
+ }
+ for {
+ resp, err := stream.Recv()
+ if errors.Is(err, io.EOF) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ if len(resp.GetReferences()) > 0 {
+ return true, nil
+ }
+ }
+}
+
+// ReferenceExists reports whether the reference with the full name name (for
+// example refs/heads/main) exists, by its exact name. Like Create, it needs the
+// shared token.
+func (r *Repo) ReferenceExists(ctx context.Context, name string) (bool, error) {
+ if !strings.HasPrefix(name, "refs/") {
+ return false, status.Errorf(codes.InvalidArgument, "reference %q: want a full name below refs/", name)
+ }
+ resp, err := gitalypb.NewRefServiceClient(r.client.conn).RefExists(ctx, &gitalypb.RefExistsRequest{
+ Repository: r.repository(),
+ Ref: []byte(name),
})
if err != nil {
return false, err
@@ -58,6 +107,50 @@ func (r *Repo) HasBranches(ctx context.Context) (bool, error) {
return resp.GetValue(), nil
}
+// ZeroOID returns the zero object ID of the repository's object hash: as
+// CommitOptions.ExpectedOldOID it requires that the branch does not exist yet.
+// Like Create, it needs the shared token.
+func (r *Repo) ZeroOID(ctx context.Context) (string, error) {
+ resp, err := r.repositories().ObjectFormat(ctx, &gitalypb.ObjectFormatRequest{Repository: r.repository()})
+ if err != nil {
+ return "", err
+ }
+ switch resp.GetFormat() {
+ case gitalypb.ObjectFormat_OBJECT_FORMAT_SHA1:
+ return strings.Repeat("0", 40), nil
+ case gitalypb.ObjectFormat_OBJECT_FORMAT_SHA256:
+ return strings.Repeat("0", 64), nil
+ default:
+ return "", status.Errorf(codes.Internal, "unknown object format %v", resp.GetFormat())
+ }
+}
+
+// CreateBranchOptions describes a branch created by CreateBranch.
+type CreateBranchOptions struct {
+ // Branch is the new branch, without the refs/heads/ prefix.
+ Branch string
+ // StartPoint is the commit the branch points to.
+ StartPoint string
+ // User is the acting user, which the server's access policy checks.
+ User User
+}
+
+// CreateBranch creates a branch that must not exist yet. It fails with
+// FailedPrecondition when the branch exists, and with PermissionDenied when
+// the server's policy refuses the update.
+func (r *Repo) CreateBranch(ctx context.Context, opts CreateBranchOptions) error {
+ if trimBranchPrefix(opts.Branch) == "" || opts.StartPoint == "" {
+ return status.Error(codes.InvalidArgument, "branch and start point are required")
+ }
+ _, err := r.client.operations.UserCreateBranch(ctx, &gitalypb.UserCreateBranchRequest{
+ Repository: r.repository(),
+ BranchName: []byte(trimBranchPrefix(opts.Branch)),
+ User: opts.User.toProto(),
+ StartPoint: []byte(opts.StartPoint),
+ })
+ return err
+}
+
// objectFormat maps the object format of CreateOptions to its protobuf value.
func objectFormat(format string) (gitalypb.ObjectFormat, error) {
switch format {