gitops

package
v0.5.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gitops executes the git mechanics of the Delivery workflow (PRD §12): per-issue feature branches and worktrees, post-merge cleanup, cleanliness and protected-branch preconditions (PRD §5, §15), and base-branch checkouts for reproducing failures (PRD §16).

The package is policy-free: callers supply branch names, worktree paths, remotes, and protected-branch lists — naming and placement policy belongs to the run engine. Every operation fails closed: any git error propagates, and a destructive operation that can reach committed work requires an explicit Confirmation (PRD §15: blocked worktrees and branches are preserved). The two removals that pass --force differ only in mechanism: WithBaseWorktree force-removes the detached checkout it created itself, and RemoveDetachedWorktree refuses any worktree that is not detached, so neither can reach a branch or the commits on it.

Operations that pre-check and then act (for example AddWorktree) are not atomic; the run engine serializes potentially conflicting writes (PRD §14), so the gap is not raced in practice.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotARepo reports that the path is not inside a git work tree.
	ErrNotARepo = errors.New("not a git repository")
	// ErrNotClean reports modified, staged, or untracked files where
	// a clean tree is required (PRD §5, §15).
	ErrNotClean = errors.New("working tree is not clean")
	// ErrDetachedHead reports a detached HEAD; Delivery never
	// operates detached.
	ErrDetachedHead = errors.New("HEAD is detached")
	// ErrProtectedBranch reports that the active branch is one the
	// caller declared protected (PRD §15: never operate on main).
	ErrProtectedBranch = errors.New("active branch is a protected branch")
	// ErrBranchExists reports a branch that already exists where a
	// new one must be created (PRD §12: one fresh branch per issue).
	ErrBranchExists = errors.New("branch already exists")
	// ErrBranchNotMerged reports git refusing to delete an unmerged
	// branch; the work it holds is preserved (PRD §15).
	ErrBranchNotMerged = errors.New("branch is not fully merged")
	// ErrUnknownWorktree reports a removal target that is not a
	// registered worktree; gitops never deletes arbitrary paths.
	ErrUnknownWorktree = errors.New("path is not a registered worktree")
	// ErrNotFastForward reports diverged history where only a
	// fast-forward is allowed (PRD §12 step 20); nothing changed.
	ErrNotFastForward = errors.New("fast-forward is not possible")
	// ErrNotConfirmed reports a destructive operation attempted
	// without ExplicitConfirmation (PRD §15).
	ErrNotConfirmed = errors.New("destructive operation requires explicit confirmation")
	// ErrNotIgnored reports a path that RequireIgnored expected git to
	// ignore but does not (PRD §5: an inside-primary worktree is only
	// safe from RequireClean and isolation guarantees when git itself
	// will never report it in `status --porcelain`).
	ErrNotIgnored = errors.New("path is not git-ignored")
	// ErrNothingToCommit reports that CommitAll staged nothing: the
	// caller expected a change and an empty commit would silently hide
	// that bug rather than fail closed.
	ErrNothingToCommit = errors.New("nothing to commit")
)

Sentinel errors callers test with errors.Is. Each marks an expected fail-closed condition detected by a pre-flight plumbing check — never by parsing git's human-readable stderr, whose wording varies across versions.

Functions

This section is empty.

Types

type Confirmation

type Confirmation struct {
	// contains filtered or unexported fields
}

Confirmation proves the caller obtained explicit human approval for a destructive operation (PRD §15). The zero value fails closed; only ExplicitConfirmation constructs a valid token. gitops never prompts — collecting the approval is the CLI and run engine's job.

func ExplicitConfirmation

func ExplicitConfirmation() Confirmation

ExplicitConfirmation returns the token that authorizes one destructive gitops call. Call it only after a human approved the specific deletion (PRD §15: cleanup or abandonment deletion requires explicit confirmation).

type Git

type Git struct {
	// contains filtered or unexported fields
}

Git executes git operations against one repository through an injected execx.Runner.

func Open

func Open(ctx context.Context, r execx.Runner, repoRoot string) (*Git, error)

Open binds to the repository whose primary checkout root is repoRoot — the directory holding .orchestrator/. It verifies that repoRoot is inside a git work tree and that git's top level equals repoRoot: .orchestrator/ must live at the git root, otherwise the containment guarantees of PRD §15 would not hold.

func (*Git) AddDetachedWorktree added in v0.5.5

func (g *Git) AddDetachedWorktree(ctx context.Context, path, commit string) (*Worktree, error)

AddDetachedWorktree checks commit out into a new worktree at path with a detached HEAD: it creates no branch and checks none out, so the checkout holds no ref that another worktree could contend for or move under it. It runs prepareWorktreePath's clobber and inside-primary checks first and never uses --force, exactly as AddWorktree does; only the branch handling differs.

The returned Worktree carries the commit HEAD actually resolved to, read back from the new checkout rather than echoed from commit, so an abbreviated commit-ish is reported in full and the caller can report what it got rather than what it asked for.

func (*Git) AddWorktree

func (g *Git) AddWorktree(ctx context.Context, path, branch, startPoint string) (*Worktree, error)

AddWorktree creates branch at startPoint together with a new worktree at path (PRD §12 step 7: one branch/worktree per issue). It fails closed before touching git when path already exists (never clobber), when the branch already exists (ErrBranchExists), or when path lies inside the primary checkout and is not git-ignored (prepareWorktreePath). Never uses --force.

func (*Git) CommitAll

func (g *Git) CommitAll(ctx context.Context, dir, message string) error

CommitAll stages every change in dir (`git add -A`) and commits it with message. It is the mechanical-commit primitive `orch init --bootstrap` (internal/bootstrap) uses to capture its generated files in the disposable worktree it just populated: a caller that reaches CommitAll always expects a real change, so an empty commit — nothing staged after `git add -A` — is a bug, not a benign no-op, and CommitAll fails closed with ErrNothingToCommit rather than create one (`git commit --allow-empty` is never used here).

func (*Git) CommitsAhead

func (g *Git) CommitsAhead(ctx context.Context, dir, base, branch string) (int, error)

CommitsAhead returns how many commits branch carries that base does not, as `git rev-list --count base..branch` run in dir. pr-open uses it to refuse an empty PR (PRD §16: no PR without work) after fast-forwarding the base at dispatch.

func (*Git) CurrentBranch

func (g *Git) CurrentBranch(ctx context.Context) (string, error)

CurrentBranch returns the branch checked out in the primary checkout. A detached HEAD wraps ErrDetachedHead: Delivery never operates detached, so callers fail closed.

func (*Git) DeleteBranch

func (g *Git) DeleteBranch(ctx context.Context, branch string, c Confirmation) error

DeleteBranch deletes a local branch that is fully merged into the current HEAD; an unmerged branch wraps ErrBranchNotMerged and is preserved (PRD §15). After a squash merge the local branch is never "merged" in git's ancestry terms — use ForceDeleteBranch once the merge has been verified through the GitHub API.

func (*Git) DeleteRemoteBranch

func (g *Git) DeleteRemoteBranch(ctx context.Context, remote, branch string, c Confirmation) error

DeleteRemoteBranch deletes the merged remote branch (PRD §12 step 18) with `git push <remote> --delete <branch>` — the same credential path that pushed the branch in the first place.

func (*Git) FastForward

func (g *Git) FastForward(ctx context.Context, remote, branch string) error

FastForward advances the primary checkout to remote's tip of branch (PRD §12 step 20). Fail-closed gates: branch must be the branch checked out in the primary checkout, and the tree must be clean. Diverged history wraps ErrNotFastForward and changes nothing.

func (*Git) FastForwardIn

func (g *Git) FastForwardIn(ctx context.Context, dir, ref string) error

FastForwardIn advances the branch checked out in dir to ref with `git merge --ff-only ref`. dispatch uses it to bring an issue branch up to origin/<default> inside its worktree before work begins; a pre-dispatch branch has no commits by construction, so any divergence is a fail-closed signal (ErrNotFastForward) and nothing changes.

func (*Git) Fetch

func (g *Git) Fetch(ctx context.Context, remote string, refspecs ...string) error

Fetch updates refs from remote; callers use it before FastForward or before reproducing a failure against a remote base ref.

func (*Git) ForceDeleteBranch

func (g *Git) ForceDeleteBranch(ctx context.Context, branch string, c Confirmation) error

ForceDeleteBranch deletes a local branch with -D. It exists solely for the squash-merge default (PRD §16), where the branch never becomes an ancestor of the base: the caller MUST have verified the PR merged before calling. It refuses to delete a branch checked out in any worktree, including the primary checkout.

func (*Git) ListWorktrees

func (g *Git) ListWorktrees(ctx context.Context) ([]Worktree, error)

ListWorktrees returns every worktree registered with the repository, primary checkout first (git guarantees that order).

func (*Git) PruneWorktrees

func (g *Git) PruneWorktrees(ctx context.Context) error

PruneWorktrees removes stale worktree bookkeeping whose directories are already gone. It deletes no working files, so it needs no Confirmation.

func (*Git) Push

func (g *Git) Push(ctx context.Context, dir, remote, branch string) error

Push publishes branch to remote from the working tree at dir, setting the upstream (`git push -u`). pr-open runs it inside the issue's worktree so the push uses that checkout's commits (PRD §12 step 9).

func (*Git) RemoteBranchExists

func (g *Git) RemoteBranchExists(ctx context.Context, remote, branch string) (bool, error)

RemoteBranchExists reports whether branch is present on remote, via `git ls-remote --heads`. cleanup uses it to make remote-branch deletion idempotent, so a crashed cleanup re-runs cleanly.

func (*Git) RemoveDetachedWorktree added in v0.5.5

func (g *Git) RemoveDetachedWorktree(ctx context.Context, path string) error

RemoveDetachedWorktree removes the registered detached worktree at path, discarding whatever modified or untracked files it holds, and prunes stale metadata. Fail-closed gates, in order: the canonical path must match a registered worktree (ErrUnknownWorktree — the same "never delete an arbitrary directory" rule RemoveWorktree obeys); it must not be the primary checkout, which is refused even when its own HEAD happens to be detached; and it must be detached, so a worktree holding a branch is refused by name.

It takes no Confirmation, for the reason WithBaseWorktree's forced removal takes none: what PRD §15 protects from a forced removal is committed work, which lives on a branch, and the detached gate above makes "holds no branch" a checked precondition rather than a promise — a branch worktree can never reach the removal below. What is lost is uncommitted scratch inside a disposable checkout, which is what disposable means. A caller removing a worktree that may hold work must use RemoveWorktree, which is confirmed and refuses a dirty tree.

func (*Git) RemoveWorktree

func (g *Git) RemoveWorktree(ctx context.Context, path string, c Confirmation) error

RemoveWorktree removes the registered worktree at path and prunes stale metadata (PRD §12 step 19). Fail-closed gates, in order: the Confirmation token must be valid (ErrNotConfirmed); the canonical path must match a registered non-primary worktree (ErrUnknownWorktree — never delete an arbitrary directory); and the worktree must be clean including untracked files (ErrNotClean — blocked work is preserved, PRD §15). Never uses --force.

func (*Git) RequireClean

func (g *Git) RequireClean(ctx context.Context, dir string) error

RequireClean returns nil only when dir's working tree has no modified, staged, or untracked files (PRD §5 Delivery prerequisites; §15 preservation checks). dir "" means the primary checkout. The error names the offending paths so the operator knows what to commit or stash.

func (*Git) RequireIgnored

func (g *Git) RequireIgnored(ctx context.Context, path string) error

RequireIgnored returns nil only when path is git-ignored relative to the primary checkout (F1: an inside-primary worktree relaxation is only safe because an ignored path never appears in `status --porcelain`, so RequireClean and isolation guarantees still hold). It works for paths that do not yet exist — `git check-ignore` matches by pattern, not by filesystem presence. path may be absolute or relative; either way it is canonicalized and expressed relative to root before the check. A path outside root is an error: this check only makes sense for a candidate inside-primary location.

The queries sent to git are not path itself but synthetic children of it — path plus "/" plus each of requireIgnoredProbes in turn, never path alone with a bare trailing slash. All probes must come back ignored for RequireIgnored to return nil; any one reporting not-ignored is decisive proof path is not covered and short-circuits the rest. Three properties are all needed, and a trailing slash on path alone provides only the first while silently breaking the other two:

  • Every caller passes a directory (a worktree or its container). A directory-only .gitignore pattern (the common case, e.g. "foo/") does not match a path that does not yet exist on disk unless git is told the path is a directory. Querying a child path inside the directory accomplishes that without needing a trailing slash on path itself, and the match still holds when the directory is nested several levels deep under the pattern (verified against real git).
  • A bare trailing slash on path (e.g. "foo/") produces a query whose final path component is empty. Git does not always skip a blank .gitignore line before turning it into a pattern: a line that is empty except for a trailing CRLF, and a line containing only whitespace under a plain LF file, both trim down to an empty pattern rather than being dropped — on any OS, since neither case depends on how the file itself is line-ended. An empty pattern matches an empty basename, so a trailing-slash-only query comes back "ignored" against such a .gitignore regardless of whether path is covered by any real pattern (verified against real git 2.53). Giving the query a non-empty basename closes this off: an empty pattern can never match a non-empty basename.
  • A single fixed, non-empty probe basename is not enough by itself: it reopens the same class of bug through a different trigger. A .gitignore line unrelated to path — "orch-*", "orch*", "*probe*", or the literal probe basename itself, none of them contrived for a binary named orch — matches that one basename by coincidence and reports every uncovered directory in the repository "ignored" (verified against real git). Querying two probes that share no prefix, suffix, or substring and requiring both to match closes this off too: a single unrelated pattern would need to separately and coincidentally match both an orch-namespaced, multi-word name and a bare digit to reproduce the failure, which no realistic .gitignore line does. A pattern that legitimately matches everything under path (e.g. a bare "*") still matches both probes and is correctly treated as ignored.

func (*Git) RequireNotOn

func (g *Git) RequireNotOn(ctx context.Context, protected ...string) error

RequireNotOn enforces PRD §15's "the active branch must not be main": the caller names the protected branches (that list is policy, owned by the run engine), gitops enforces it mechanically.

func (*Git) RevParse

func (g *Git) RevParse(ctx context.Context, ref string) (string, error)

RevParse resolves ref to a full commit hash, for audit manifests (PRD §13) and verification.

func (*Git) Root

func (g *Git) Root() string

Root returns the canonical primary-checkout root.

func (*Git) WithBaseWorktree

func (g *Git) WithBaseWorktree(ctx context.Context, ref string, fn func(dir string) error) (err error)

WithBaseWorktree checks ref out into a disposable detached worktree and calls fn with its directory, then always removes it. It is the substrate for PRD §16's "a failure is pre-existing only when reproduced on the base branch": the run engine runs the failing verification command inside fn and interprets the exit code; gitops only provides the checkout.

Cleanup is the one place gitops uses `worktree remove --force`: reproduction commands legitimately leave untracked build artifacts, and the checkout is disposable by construction — detached, holding no branch and no user work, at a path this function generated — so forced removal cannot destroy work (PRD §15 still holds). A cleanup failure is joined with fn's error, never swallowed (PRD §16: cleanup failures keep the run incomplete).

type Worktree

type Worktree struct {
	// Path is the canonical worktree directory.
	Path string
	// Branch is the checked-out branch, "" when detached.
	Branch string
	// Head is the checked-out commit hash.
	Head string
	// Detached reports a detached HEAD.
	Detached bool
	// Primary marks the main working tree, which is never removed.
	Primary bool
}

Worktree describes one entry of `git worktree list --porcelain`.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL