gitutil

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 32 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 gitutil holds the shared, isolated git queries. It is transport-agnostic: no stdout, no os.Exit, no CLI knowledge.

Every git invocation here neutralises global and system config, so a developer's ~/.gitconfig or ~/.gitignore can never change what abcd reports about a repository. Queries fail open — when git is unavailable or the directory is not a repository, nothing is claimed rather than an error raised, so a convention check degrades to "cannot tell" instead of asserting a violation it has no evidence for.

Index

Constants

View Source
const CheckoutBound = 60 * time.Minute

CheckoutBound bounds a `git worktree add` abcd makes through RunCommitCommandBounded. Its checkout writes every file of the tree through the repository's content filters, and a Git LFS smudge downloads each object it names, so its time scales with the tree and the network rather than with a person's answer. The bound is there only so a post-checkout hook that waits never holds the command forever.

View Source
const MaxWorktreeListing = 16 << 20

MaxWorktreeListing is the cap a caller listing a repository's worktrees passes ListWorktrees when it has no reason for another: a listing is a few hundred bytes a worktree, and 16 MiB bounds a planted repository without refusing a real one.

View Source
const (
	// NetTimeout is the longest one networked git command may run.
	NetTimeout = 10 * time.Minute
)

Bounds on a git command that reaches the remote.

Variables

View Source
var ErrBeforeHookedGitSet = errors.New("a check before every hooked or networked git is already set in this process, and one drive runs in a process")

ErrBeforeHookedGitSet is SetBeforeHookedGit's refusal of a second check while one is set: one drive runs in a process.

View Source
var ErrCheckoutStalled = errors.New("the checkout (its content filters, such as a Git LFS download, and its post-checkout hook) did not finish")

ErrCheckoutStalled names a `git worktree add` stopped at its bound.

View Source
var ErrConfigCap = errors.New("the key list exceeded its cap")

ErrConfigCap is a config read whose key list exceeded its cap: git read the configuration, but not all of it reached abcd.

View Source
var ErrGitTimedOut = errors.New("git did not answer in time")

ErrGitTimedOut is a lookup's answer for a git that did not answer in time, for a caller that bounds a lookup with a clock of its own and reports the bound's end as git not answering (the prompt router's root-commit lookup), so it can be told from "git said no" with errors.Is. A context-bound runner here answers its context's own error instead.

View Source
var ErrGitVersionUnread = errors.New("git's version could not be read")

ErrGitVersionUnread is a partial clone's object read refused because git's version could not be read this time: unlike ErrLazyFetchFloor, a later try may clear it.

View Source
var ErrLazyFetchFloor = fmt.Errorf("the repository declares a promisor remote (a partial clone), and git older than %d.%d ignores GIT_NO_LAZY_FETCH, so reading a missing object would run the transport the repository configures: abcd reads no objects here until git is %d.%d or later",
	lazyFetchFloorMajor, lazyFetchFloorMinor, lazyFetchFloorMajor, lazyFetchFloorMinor)

ErrLazyFetchFloor is the refusal of an object read in a partial clone on a git too old to honour GIT_NO_LAZY_FETCH.

View Source
var ErrNoCheckoutRoot = errors.New("no checkout root")

ErrNoCheckoutRoot is CheckoutRoot's refusal: there is no checkout whose record store the caller's working directory belongs to, so there is no store to address. A surface maps it to an exit code and its own wording; this package never prints.

View Source
var ErrNoRootAnswer = errors.New("git gave no root commit for a repository")

ErrNoRootAnswer is a root-commit lookup that got no answer from git for a directory that is a repository by its shape: git did not start, was killed, exited in a way that names neither a root commit nor an empty history, or refused the repository. It is never "this repository has no root commit", which is ("", nil) (iss-2610051434156079).

View Source
var ErrObjectMismatch = errors.New("an object does not hash to its name")

ErrObjectMismatch is an object whose content does not hash to the name it was read by, or is not of the type the reader asked for.

View Source
var ErrShallowCheckout = errors.New("shallow checkout")

ErrShallowCheckout is RequireFullHistory's refusal: the checkout is shallow, so history past the graft is absent.

View Source
var ErrToplevelShape = errors.New("git's toplevel answer is not one absolute path containing the directory asked about and holding the git directory git found")

ErrToplevelShape is Toplevel's refusal of an answer git would never give.

View Source
var FilterRootsDisplay = abcdhome.Display("filter-roots")

FilterRootsDisplay is the filter-roots declaration's path in tilde form, so a message naming it carries no home path.

View Source
var FilterRootsRelPath = abcdhome.Rel("filter-roots")

FilterRootsRelPath is the home-scoped declaration that switches the repository's content filters back on for Status in the checkouts it lists: ~/.abcd.noindex/filter-roots, one absolute checkout path per line, "#" starting a comment. It lives in the person's home, never in the repository, because a repository could otherwise switch its own filters on.

Functions

func AliasDefinedContext

func AliasDefinedContext(ctx context.Context, root, home, name string) (bool, error)

AliasDefinedContext reports whether the configuration git reads in the directory root defines alias.<name>: the repository's own files, the global file and the system one, read with `git config --get`, which reads and runs nothing else. Every variable that selects another repository or injects configuration is scrubbed (ScrubbedEnv). Where home is not "", git reads its global file under home, as a shell whose HOME is home does, and XDG_CONFIG_HOME is left out. A clean "not set" is false; any other failure, an invalid key among them, is an error, so a caller cannot read a failed read as no alias. git is bound to ctx: it is killed when ctx ends, and the error then wraps ctx's (context.DeadlineExceeded for a deadline).

func AsStoredEnv added in v0.17.0

func AsStoredEnv(env []string) []string

AsStoredEnv is env made to read objects as stored, for a git command built outside this package as well as asStored's own: GIT_NO_REPLACE_OBJECTS=1, GIT_GRAFT_FILE naming no file, core.commitGraph false as the last entry of GIT_CONFIG_PARAMETERS, and GIT_TEST_COMMIT_GRAPH=0. A commit-graph is a cache git reads a commit's tree and parents from in place of the commit, and one written by hand can claim another tree. The entry follows whatever entries env's GIT_CONFIG_PARAMETERS carries, which stay, and the last entry wins; GIT_TEST_COMMIT_GRAPH, which loads a graph whatever the setting says, is off. This is what .githooks/pre-push sets. The variables come last and any earlier value of them is dropped. env itself is not changed.

func BuiltinMergeDriver added in v0.13.4

func BuiltinMergeDriver() string

BuiltinMergeDriver returns the merge.<name>.driver command line that makes a driver git's built-in text merge: `git merge-file` over the three versions, with the conflict-marker size git passes a driver, exiting non-zero on a conflict, as a driver must.

From git 2.44 it also passes the conflict labels and the histogram diff git's merge itself uses, so the result, clean or conflicted, is byte for byte the built-in driver's. Below 2.44 merge-file can take neither (it reads no diff algorithm from config, and a driver is not given the labels), so the driver runs merge-file's default diff with fixed labels: the repository's driver still never starts, but a conflict's markers read ours, base and theirs, and where the two diffs align a changed region differently the result can differ from git's own merge of the same commits, in where a conflict's hunks fall or in whether a region conflicts at all. A version the probe cannot read gets that form, which every git accepts.

func CheckIgnored

func CheckIgnored(root string, candidates []string) map[string]struct{}

CheckIgnored returns the subset of repo-relative candidates that git actually ignores, via a single isolated `git check-ignore -z -v --stdin`. Batching keeps one subprocess for an arbitrary number of paths.

The index is consulted (no `--no-index`), so this mirrors git's real ignore decision: git never ignores a tracked file, even one force-added against a matching pattern — reporting such a path as ignored would invert the answer for callers asking "is this file committed-durable?" or "must this be excluded from the release bundle?".

A negation record (a pattern beginning `!`) un-ignores its path and so does not count as ignored. When git is unavailable or root is not a repository the result is empty (fail open).

func CheckoutRoot added in v0.8.0

func CheckoutRoot(cwd, store string) (string, error)

CheckoutRoot answers the question every front door onto a repository-scoped record store has to ask before it builds a request: which checkout's store does a caller standing in cwd address?

It is the ONE resolution for that question, and it exists because two front doors skipped asking it and reached the same failure independently. The capture verbs handed their working directory to the ledger core as an explicit repo root, so a verb run from a subdirectory addressed a ledger that was not there: a read reported open 0 against a populated checkout, and a write minted a second ledger under the subdirectory and reported success with a repo-relative path that looked ordinary (iss-2609090951291524). `decide` did the same to the decision store, and one directory further out: run outside every repository it exited 0 and laid a full ADR store in whatever plain directory the caller stood in (iss-2609091707224329). The resolution is store-agnostic, so it lives here rather than in either store's package, and `store` — a noun phrase naming what is being addressed, "the issue ledger", "the decision store" — is the ONLY thing that varies between callers.

Three outcomes, and only the first is a root:

  • git names a toplevel: that is the answer, whoever owns the checkout.
  • git will not answer for a repo-SHAPED tree (git absent from PATH, a corrupt .git, an ownership refusal under the isolated env, or an answer Toplevel refuses for its shape, which a core.worktree setting naming a tree that does not contain cwd, or an ancestor of the checkout that does not hold its .git (iss-2610090821543020), produces): REFUSED, naming that git could not answer. RepoShapedRoot is read here as a CLASSIFIER and never as a root: it is a marker walk, which accepts any directory merely carrying the name and has neither the shape check nor the ownership gate the rules-root resolver grew (iss-2609090947359464), so returning its answer is the one change that would make that walk live. A store addressed by a guess is the defect this function closes, one directory further out.
  • nothing repo-shaped anywhere above: REFUSED. Laying a store in whatever directory the caller stood in is not a lenient fallback — the records would sit outside any checkout, committed by nothing and read by nothing, which is the same lost trail this resolution exists to prevent. Every store this resolves for is per-repository by definition.

func CheckoutRootContext added in v0.17.0

func CheckoutRootContext(ctx context.Context, cwd, store string) (string, error)

CheckoutRootContext is CheckoutRoot bound to ctx, for a hook on a deadline: the same answers, with git killed when ctx ends. A lookup ctx ended answers ctx's own error, so a caller can tell a spent deadline from a refusal.

func CommandLineConfig added in v0.11.1

func CommandLineConfig() []string

CommandLineConfig is the `git -c` configuration the parent environment carries — GIT_CONFIG_PARAMETERS and the GIT_CONFIG_COUNT/GIT_CONFIG_KEY_n/ GIT_CONFIG_VALUE_n form, the entries ScrubbedEnv strips — as "KEY=value" entries, in environment order. git hands exactly these to a command it runs (a hook, an alias), so a reader that must see the configuration git itself is running with appends them to ScrubbedEnv for its own command; no other caller's scrub changes.

func CommonDir added in v0.16.0

func CommonDir(dir string) (string, error)

CommonDir is git's common dir for the working tree whose top is dir, made absolute against dir: the directory every worktree of one repository shares, so two working trees belong to one repository exactly when their common dirs resolve to one real path. The peers reader and the worktree store's proof of belonging both ask it, of the candidate itself, never of this checkout.

It asks without --path-format=absolute, which arrived in git 2.31: an older rev-parse echoes an option it does not know to stdout and exits 0, so the answer would be the flag's text and a path on two lines, and every candidate would compare unequal. The plain form answers relative to the directory it is run in (".git" at a main working tree's top) or absolute (a linked worktree's), and anything but one line is refused rather than compared.

func CommonDirContext added in v0.17.0

func CommonDirContext(ctx context.Context, dir string) (string, error)

CommonDirContext is CommonDir bound to ctx: a git still running when ctx ends is killed, and its answer is ctx's error.

func DefaultBranchRoots added in v0.15.1

func DefaultBranchRoots(root string) ([]string, error)

DefaultBranchRoots lists every root commit of origin's default branch as last fetched (DefaultRef, when it names a ref under refs/remotes/origin/; HEAD otherwise), oldest committer date first, ties in object-name order. The history is read as stored: with replace refs off (core.useReplaceRefs=false and GIT_NO_REPLACE_OBJECTS), no graft file (noGraftFile) and no commit-graph (AsStoredEnv), so none of them can add a root or hide one.

The list only grows by a merge that brings in an unrelated history (`git subtree add`, `--allow-unrelated-histories`, an empty-diff `merge -s ours`); in an ordinary repository it holds one root, RootCommit's answer. It is read as git writes it, with no cap on its length, so one merge of many parentless commits cannot make it unreadable.

No commits to read (HEAD names no commit: `rev-parse --verify --quiet` exits 1) is an empty list and no error; any other failure of git, there or listing the roots, or a line of a shape git never writes, is an error.

func DefaultRef added in v0.11.1

func DefaultRef(root string) string

DefaultRef is the full ref name of the repository's default branch as last fetched, with no network: origin/HEAD's target, then the conventional names on the remote, then the same names locally. "" when none resolves.

It is the one resolution the readers that measure against the default branch share: the peers reader judges a branch merged into it, and the reviews board counts the commits it has moved since a review's pin. Two readers of one repository asking the same question must get one answer. A listing past its 64 KiB cap is refused whole, and the branch is then asked ref by ref, for a few more git processes; resolveDefault names where a question per ref can answer differently from the listing.

func DefaultRefContext added in v0.16.0

func DefaultRefContext(ctx context.Context, root string) string

DefaultRefContext is DefaultRef with every git question bounded by ctx (RunLimitedContext): a git still running when ctx ends is killed, and the answer is "". A caller that must tell "no default branch" from "git did not answer in time" checks ctx.Err() after it.

func DiffWorktreeArgs added in v0.17.0

func DiffWorktreeArgs(opts ...string) []string

DiffWorktreeArgs is StatusArgs for a `git diff` that compares the index with a working tree (one that names no commit): "diff", then --ignore-submodules=dirty, then opts. Such a diff, as a status does, starts a status inside each checked-out submodule whose commit is the one the index records, under that submodule's own settings; with the flag it starts nothing there. A submodule whose checked-out commit moved, and an unmerged path, are still listed. git-diff(1), --ignore-submodules: "Using dirty ignores all changes to the work tree of submodules, only changes to the commits stored in the superproject are shown".

func EachAsStoredContext added in v0.15.1

func EachAsStoredContext(ctx context.Context, root string, maxLine int, each func(line string), args ...string) error

EachAsStoredContext runs one git command as stored (asStored) under ctx, for a command whose output may run to any length (a listing of every ref under a prefix a fetch of a whole namespace can fill): each line of stdout is handed to each as it is read, without its newline, and none is kept, so no bound on the whole output applies. A line longer than maxLine bytes is handed cut to its first maxLine. git is killed when ctx ends, and ctx's error is then answered; a failure carries git's bounded stderr.

func EachWorktree added in v0.15.1

func EachWorktree(root string, fn func(Worktree)) error

EachWorktree streams every working tree of the repository at root to fn, the main one first, as ListWorktrees parses them, without capping the listing's total length: a repository with many worktrees is read whole. One field past maxWorktreeField is an error, never a record cut short.

It asks for the NUL-separated form first and falls back to the newline-separated form, as ListWorktrees does, only when git refused the first before handing over any field; a failure partway is returned.

func EmptyTree added in v0.14.2

func EmptyTree(root string) (string, error)

EmptyTree is the object name of the empty tree in the repository at root, for the repository's own object format (4b825dc6… under SHA-1, 6ef19b41… under SHA-256), written into its object store so a commit made on it can be pushed. It is the one place the name is computed: a reservation commit's tree is the empty tree, and the reader and the writer of those commits compare against this answer rather than a constant that holds for one format only.

There are two forms because writing is the writer's need alone. EmptyTree is the writer's: a commit made on the tree needs the object in the store. EmptyTreeName is the reader's: a read only compares a tip's tree with the name, so it must leave the shared object store untouched (hash-object -w writes the object, or refreshes its file's time when it is already there).

git hashes standard input, which the isolated command leaves empty, so the answer is the hash of zero bytes typed as a tree on every platform.

func EmptyTreeName added in v0.16.0

func EmptyTreeName(root string) (string, error)

EmptyTreeName is EmptyTree's name without the write: the same answer, for a reader that compares against it and must leave .git/objects as it found it. A path that commits on the empty tree uses EmptyTree. Its answer is capped as EmptyTreeNameContext's is, and refused whole past the cap.

func EmptyTreeNameContext added in v0.17.0

func EmptyTreeNameContext(ctx context.Context, root string) (string, error)

EmptyTreeNameContext is EmptyTreeName bound to ctx (RunLimitedContext's runner): a ctx already ended starts no git, and a git still running when it ends is killed, answering ctx's error. The two forms share one body (emptyTreeNamed) and one cap, so they differ in the context alone.

func ExecPins added in v0.13.4

func ExecPins() []string

ExecPins is the one list of `git -c` overrides that keep a repository's own config from making a git command abcd composes start a program the command would not otherwise run. A repository's .git/config is fully trusted by git and no environment variable switches it off, so each knob is forced on the command line, where it outranks every config file:

  • core.hooksPath=/dev/null: no hook fires.
  • core.fsmonitor=false: no fsmonitor daemon is spawned to refresh the index.
  • log.showSignature=false: `log` and `show` do not verify a signed commit's signature, which starts gpg.program (iss-2610090821531394).
  • commit.gpgsign=false: a commit or merge commit abcd composes is not signed, which would start gpg.program, gpg.ssh.program or gpg.ssh.defaultKeyCommand (iss-2610090821520843).
  • merge.verifySignatures=false: a merge does not verify the merged tip's signature, which starts gpg.program or gpg.ssh.program (iss-2610090821520843).
  • diff.submodule=short: a patch diff shows a moved submodule as its pointer change alone, never by starting a second git diff inside the submodule, which reads the submodule's own config and is passed none of the parent's --no-ext-diff/--no-textconv, so its diff.external or textconv would run and write into the text a check parses (iss-2610091935325886).

Every isolated command (Run and its siblings) carries them, and a caller that must build its own git command (one that keeps global config, say) prepends them rather than copying the list. The pins come before -C and the subcommand: after the subcommand, `-c` is that subcommand's option. A commit abcd makes in a working tree it made for the work leaves core.hooksPath, commit.gpgsign and merge.verifySignatures to the repository (WorkingTreeCommitCommand): those are how the repository commits and merges.

They do not blank content filters or diff and merge drivers, because those are keyed on a name the repository chooses; FilterOverrides covers filters for a read that must not run one, MergeDriverOverrides makes every merge driver git's built-in merge for a read-only merge (the conflict probe's merge-tree), and a diff passes --no-ext-diff and --no-textconv. A merge abcd makes in a lane runs the repository's merge drivers, as the person's own merge does.

func ExitCode added in v0.17.0

func ExitCode(err error) int

ExitCode is the exit status of the git err reports, -1 when there is none: a git that was not run (a NotRunError) has none, whatever its cause wraps, so a caller that reads a status as an answer (none, no, too old) reads it as a failed read instead.

func FilterOverrides added in v0.13.4

func FilterOverrides(root string) ([]string, error)

FilterOverrides returns the `git -c` overrides that blank every content filter the repository at root configures — `filter.<name>.clean`, `.smudge` and `.process` for each name — so a command that re-hashes the working tree (a `diff` against HEAD over a copied checkout whose index stat no longer matches) compares bytes instead of running the repository's program (iss-2610090821548169). The overrides go before the subcommand.

Config is read the way the isolated command reads it (repository config and its includes; global and system neutralised). No filter configured is an empty list, not an error. A filter git still insists on (`required = true`) with its commands blanked makes the command fail, which a caller reports as unreadable rather than clean. A name `-c` cannot carry intact (one holding `=` or a line break) is refused: blanking a different key would leave the filter live.

func FilterRootsIgnored added in v0.13.4

func FilterRootsIgnored() string

FilterRootsIgnored is the note FiltersSwitchedOn gives when a present ~/.abcd.noindex/filter-roots file fails its ownership, mode or symlink checks, naming the file and the check it failed; empty when the file is absent or was read. Which checkout is asked about does not change it: the checks are the file's, not an entry's.

func FiltersSwitchedOn added in v0.13.4

func FiltersSwitchedOn(root string) (on bool, ignored string)

FiltersSwitchedOn reports whether the person has listed root in ~/.abcd.noindex/filter-roots, switching the repository's content filters back on for Status there. The declaration is read through fsutil.HomeDeclarationNames, the reader every "declare this checkout" opt-in shares, so it is honoured only while it is a regular file this account owns that no one else can write, reached through no symlinked folder; ignored is the one-line note saying why a present declaration was not honoured, naming the file in tilde form, and is empty when there is none or it was read. Status has no output channel and drops it; FilterRootsIgnored is the reading a front door reports (iss-2610091920437492).

func GitAtLeast added in v0.15.1

func GitAtLeast(major, minor int) (bool, string)

GitAtLeast reports whether the git on PATH is at least major.minor, probed once per process, and its version as "<major>.<minor>", digits alone, "" when the probe failed or its line does not parse (below every floor).

func GitfileTarget added in v0.15.1

func GitfileTarget(dir string) (string, bool)

GitfileTarget is where the git file at dir/.git points: its first line's "gitdir: " path, joined to dir when relative, cleaned. It is read through fsutil.OpenRegular, so a symlinked, non-regular or absent .git, a first line that is no "gitdir: " line, or one running past gitfileCap bytes, answers false. It says where the file points and nothing of whether a repository is there: a worktree whose git file points nowhere is the case it exists to name, since git's own refusal names the path on some platforms and "(null)" on others.

func Gitlinks(root string) ([]string, error)

Gitlinks is the path of every gitlink (mode 160000, a submodule) in root's index, relative to the working tree's top and slash-separated. The index listing is streamed, keeping only the gitlinks, so a large index costs time, not memory beyond the gitlinks themselves; no count of them is refused.

func GitlinksWithIndex added in v0.17.0

func GitlinksWithIndex(root, index string) ([]string, error)

GitlinksWithIndex is Gitlinks of the scratch index at index (an absolute path, as RunWithIndex takes one).

func HomeInsideWorkingTree added in v0.14.0

func HomeInsideWorkingTree(home string) string

HomeInsideWorkingTree is the one rule for whether a home ($HOME, as os.UserHomeDir returns it on Unix) may serve as this machine's abcd home (iss-2609300012273350). It returns the working tree the home lies in when the home's physical path is at or below a directory carrying a .git entry (RepoShapedRoot, the crude "could a commit carry it?" answer) and the home is not the account's own, and "" otherwise.

An environment a repository can shape (a committed harness settings file whose env block sets HOME into the tree) would otherwise let a checkout supply the machine layer and the credential store. Any working tree is refused, not only the session's: the session's checkout is one place a planted HOME can point, a sibling checkout is another.

The account's own home is exempt, because a dotfiles-in-HOME account keeps its home in a working tree and that home is the person's, not a checkout's. The account's home is the one the account database names for this uid (accountHome), and never anything the environment supplies: a planted HOME must not vouch for itself. A failed lookup grants no exemption.

A home whose directory does not exist is judged on its cleaned spelling and gets no exemption, because os.Stat fails and there is no file to compare by identity. That is the intended outcome: a missing home inside a checkout is refused, and nothing is read from or written to it.

Containment is judged on the home's physical path (filepath.EvalSymlinks) and the exemption by file identity (os.SameFile), never by spelling, so a link spelled inside a checkout that leads outside every working tree is not refused, a link spelled outside that leads into one is, and a case variant or link to the account home is still the account home.

func HooksPaths added in v0.13.0

func HooksPaths(root string) ([]string, error)

HooksPaths is every core.hooksPath value git reads for the repository at root, from each scope it reads (system, global, the repository's, the worktree's), in that order and path-expanded (a leading ~ is the home), as git writes them: a relative value is relative to the working tree's root.

It is read as the person's own git reads it, so it runs under ScrubbedEnv (global and system config in force) and never under the isolated environment, whose -c core.hooksPath=/dev/null would answer for itself. Reading configuration runs no hook and starts no fsmonitor. None set is an empty answer; a git that cannot answer is an error.

A value set to the empty string is kept, as "": git reads the key as set all the same, and then runs no hook from the git directory's hooks/. A caller that places a directory from the last value handles it; one that reads the values only to name directories skips it.

func IgnoredUnder added in v0.11.1

func IgnoredUnder(root, rel string) ([]string, error)

IgnoredUnder lists the untracked paths git ignores beneath the repo-relative directory rel, in ONE isolated `git ls-files --others --ignored --exclude-standard --directory` call. A wholly ignored directory is reported once, as its own path with a trailing slash, rather than file by file, so a caller walking the tree can prune it without descending. Only untracked paths are listed: git never ignores a tracked file, so a committed file a pattern happens to match is not reported and stays the caller's to read. Paths are relative to root, slash-separated, and sorted.

Like CheckIgnored it neutralises core.excludesFile, so a developer's personal ignore file cannot change what abcd reads, and it fails open: when git is unavailable or root is not a repository the result is empty and the error nil. The one exception is the lazy-fetch floor: below git 2.44 a partial clone refuses the listing (reading the ignore rules can fetch a skip-worktree .gitignore), and that refusal is RETURNED, wrapping ErrLazyFetchFloor, so a caller that prunes by this list can say it did not rather than read the ignored tree as unpruned (iss-2610091935324732).

func InRepo

func InRepo(root string) bool

InRepo reports whether root is inside a git working tree. A convention rule uses it to tell "git says this path is not ignored" apart from "git cannot answer" (git absent, or not a repo) — the latter is "cannot tell", never "compliant".

func IsAncestor added in v0.6.8

func IsAncestor(root, ancestor, descendant string) (bool, error)

IsAncestor reports whether ancestor is an ancestor of (or equal to) descendant under root, via `git merge-base --is-ancestor`. git encodes the answer in the exit status — 0 is "yes", 1 is "no", and anything else (128 for a bad object, a missing repository) is a real failure — so a bare Run cannot be used: it folds the informative 1 into a generic error. A caller deriving a release's content commit from the receipts directory needs the three outcomes kept apart: "yes" selects a candidate, "no" skips it, and only a genuine git failure is fatal. Either name empty or starting with a dash, which git would read as an option, is refused before git runs (RefIsSafe): callers pass names read from stored state as well as from git.

func IsAncestorAsStored

func IsAncestorAsStored(root, ancestor, descendant string) (bool, error)

IsAncestorAsStored is IsAncestor reading history as stored (asStored): for an ancestry verdict a gate acts on, which a graft, a refs/replace entry or a commit-graph could otherwise give parents the commits do not store.

func IsFullSHA added in v0.10.0

func IsFullSHA(s string) bool

IsFullSHA reports whether s is a full object name as RootCommit returns one. The machine-scoped stores key a directory on the root commit, so the check is what keeps a value that arrived any other way from becoming a path segment.

func IsIgnored

func IsIgnored(root, path string) bool

IsIgnored reports whether a single repo-relative path is ignored by git. It is CheckIgnored for the one-path case; prefer CheckIgnored when asking about several paths, to keep it to one subprocess.

func IsNullOID added in v0.11.1

func IsNullOID(s string) bool

IsNullOID reports whether s is git's all-zeroes object name, under SHA-1 or SHA-256. A forge hands it to a range gate when a push has no predecessor to name — a branch the push created, or a force-push whose old tip it declines to cite. It is well formed and resolves to nothing.

func IsolatedEnv

func IsolatedEnv() []string

IsolatedEnv returns the child environment an isolated git command runs with: the parent environment scrubbed of every repo-selection and config-injection variable (GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_*, …), plus the config-file neutralisers. A front door that must run a git command this package does not already wrap — a probe needing --stdin, say — uses this instead of os.Environ() so it inherits the same isolation as Run/RunLimited. Reaching for os.Environ() directly lets an inherited GIT_DIR/GIT_WORK_TREE silently redirect the command at a DIFFERENT repository, which for a secret-hygiene gate is a real vulnerability.

func JudgesContentPrograms added in v0.17.0

func JudgesContentPrograms(verb string) bool

JudgesContentPrograms reports whether verb is a subcommand LeavesContentProgramsOn reads the options of: one that can start a content filter, a textconv or external diff program, or a merge driver.

func LazyFetchGuard added in v0.17.0

func LazyFetchGuard(ctx context.Context, root string, args []string) error

LazyFetchGuard is lazyFetchGuard for a package that builds its own git command in the isolated environment (the spot-check store's writes), so that command passes the floor every isolated command of this package passes: nil, or the refusal of args, the command line after git's pins, before git starts.

func LeavesContentProgramsOn added in v0.17.0

func LeavesContentProgramsOn(args []string) bool

LeavesContentProgramsOn reports whether a git command with args, run in the isolated environment (ExecPins, no global or system settings), can start a program the repository's settings name that ExecPins leaves on: a content filter (filter.<name>.clean, .smudge, .process) over working-tree content it reads or writes, a textconv or external diff program over content it shows, or a merge driver. It is read from the command line alone: a subcommand contentJudges holds is judged by its options as below; one startsNothing holds does not ask, unless startsInForm says the form it is given can start a program or reach the network; any other asks. The four options that switch a program on (--textconv, --ext-diff, --filters, --modified) are read in any prefix git takes for them, and -m and -u inside a bundle of short options. A word that makes a command not ask counts only where the word before it is known not to take it as a value (valued.counts).

  • hash-object of a blob from a path: unless --no-filters or FilterOverrides (standard input without --path, and a tree, commit or tag, are hashed as given).
  • cat-file: only with --filters (unless FilterOverrides) or --textconv.
  • status, archive, ls-files -m, update-index (but --cacheinfo or --index-info with no path besides --cacheinfo's value): unless FilterOverrides. A status without the blanks asks in any repository.
  • diff: when a side is the working tree (no --cached or --staged, and neither a range nor two revisions before a "--") unless FilterOverrides, and when it shows content unless --no-textconv and --no-ext-diff.
  • diff-files, and diff-index without --cached: a patch reads the working tree through its filters unless FilterOverrides; diff-tree, diff-index and diff-files run textconv or an external diff only with --textconv or --ext-diff; diff-tree also asks when it shows a signature check or its last format word can (formatAsks).
  • show: with --textconv or --ext-diff, or showing a commit's patch unless --no-textconv and --no-ext-diff (a blob, rev:path, is shown as stored unless --textconv is given; :/text and rev^{/text} name commits, not blobs), or showing a commit in a format that can show a signature check (formatAsks: a format word that names an alias, or none, since show's default is format.pretty).
  • log and reflog: with --textconv or --ext-diff, or with a patch, a stat or a content search unless --no-textconv and --no-ext-diff; either also in a format that can show a signature check (formatAsks; log with no format word, since its default is format.pretty). A deprecated command (whatchanged, pack-redundant) is on neither list, so it asks: git lets an alias stand for one (alias.* in git-config(1)).
  • blame and annotate: unless --no-textconv and, for the working tree's file, FilterOverrides.
  • grep: only with --textconv.
  • apply: with --3way, which merges through the merge drivers, whatever else it carries; otherwise unless --cached, a stat alone, or FilterOverrides.
  • merge-tree: unless MergeDriverOverrides, which pin merge.renormalize off as well as every driver.
  • add, stash, checkout, switch, restore, checkout-index, commit, rm (but --cached), reset (but --soft), read-tree -u, worktree add, am, clone: unless FilterOverrides; merge, cherry-pick, revert, rebase and pull also unless MergeDriverOverrides.

func LocalGit added in v0.15.0

func LocalGit(dir string, args ...string) (string, error)

LocalGit runs one git command that reaches no remote (a commit, a read of origin's URLs) from the checkout at dir, with the repository's hooks running under the developer's own configuration exactly as their own git runs them: ScrubbedEnv, GIT_TERMINAL_PROMPT=0 and core.quotePath=false, and nothing else, so none of Net's network settings (its low-speed bounds, which reach a hook through GIT_CONFIG_PARAMETERS, and its batch-mode ssh command) changes how a hook of the repository's runs. Its bounds and its output are Net's.

func MergeDriverOverrides added in v0.13.4

func MergeDriverOverrides(root string) ([]string, error)

MergeDriverOverrides returns the `git -c` overrides that make every merge driver the repository at root configures git's built-in text merge — `merge.<name>.driver` set to BuiltinMergeDriver for each name — and pin merge.default to the built-in text driver, so a read-only merge abcd computes (the conflict probe's merge-tree, a prediction of the forge's merge) never starts a program the repository names, whichever driver an attribute or merge.default selects (iss-2610090821510097). They also pin merge.renormalize off: with it on, a three-way content merge runs each side through the content filters the attributes select (git-config(1), merge.renormalize), and merge-tree reads it. The forge's own merge reads no setting of a person's checkout, so the prediction is the forge's either way, and no merge a person makes takes the pin. A merge made in a lane's worktree does not take them: it runs the repository's own drivers (WorkingTreeCommitCommand, iss-2610111729399920). A driver cannot be blanked as a filter is: git fails to start an empty driver command and reports every path both sides changed as a conflict. The overrides go before the subcommand.

Config is read as FilterOverrides reads it, and a name `-c` cannot carry intact is refused the same way.

func MergeDriverOverridesContext added in v0.17.0

func MergeDriverOverridesContext(ctx context.Context, root string) ([]string, error)

MergeDriverOverridesContext is MergeDriverOverrides with its config read bound to ctx, for a hook on a deadline: git is killed when ctx ends, and the read answers ctx's own error.

func MovedGitlinks(root, index string) (map[string]bool, error)

MovedGitlinks is the set of gitlinks of root's index (of the scratch index at index, an absolute path, when it is not "") whose working tree no longer holds the commit the index records: a submodule checked out at another commit, a path gone, or one that holds something else. It reads `git diff-files --ignore-submodules=dirty -z` over the whole tree, streamed, and keeps the rows whose index side is a gitlink, so neither the size of the tree nor the number of its changes bounds it.

With --ignore-submodules=dirty git starts nothing inside a submodule: it compares the commit checked out there with the index's. A file whose stat cannot tell it apart from the index (racily clean) is hashed, which runs its content filter, so every filter the repository configures is blanked on the command line and its required switch turned off (filterBlanks): what such a file hashes to changes only the file's own row, which is not kept.

func Net added in v0.14.2

func Net(dir string, args ...string) (string, error)

Net runs one git command that reaches the remote, from the checkout at dir: a fetch or a push. It is the one networked git runner, shared by the implement loop's landing, `abcd land` and the reservation on the shared remote. A git command that reaches no remote runs through LocalGit instead, so a hook it runs sees none of the network settings below.

The repository's hooks run (the pre-push gate is the point), under the developer's own configuration less any injected GIT_DIR or GIT_CONFIG_* (ScrubbedEnv), with GIT_TERMINAL_PROMPT=0 so git's own credential prompt cannot hang a session. ssh reads the terminal itself, so the ssh command Net composes runs in batch mode: a host-key question or a passphrase prompt is a failure, not a wait. A developer's own ssh command is left as it is, and whether it can prompt is theirs. A connection that stalls is cut off in about a minute rather than at NetTimeout, so a lost network is met as a failure a caller can read (iss-2610080620372731): an HTTP transfer slower than netLowSpeedLimit bytes a second for netLowSpeedTime is aborted, and ssh, unless the developer configured their own ssh command, gives up a connect after 30 seconds and a silent connection after four missed keepalives. Stdout is returned within netOutputCap, on a failure too (a porcelain push reports its rejections there); a failure's error carries git's bounded stderr. On a failure both are scrubbed of credential URLs (ScrubURLCredentials) before they are cut. Under a test binary, networked git is restricted to local transports with no credential helper (netEnv); outside one nothing about it changes.

func NetAskContext added in v0.17.0

func NetAskContext(ctx context.Context, dir string, limit int, args ...string) (string, error)

NetAskContext runs one git command that reads and writes nothing (a `config` listing, `var`, `rev-parse --git-path`) in exactly the environment Net, NetEach and NetInputContext give git: the person's own home, configuration and credentials, the repository's hooks not pinned off. It is for a caller that must know what that environment reads (the settings, the hooks directory a push runs, the attributes files), never for a command that runs a hook or reaches a remote. It is bound to ctx, git is killed when ctx ends, and its output past limit bytes is an error. The error of a git that ran and failed wraps its *exec.ExitError, so the caller can read the exit status; its stderr is bounded and scrubbed of credentials.

func NetContext added in v0.16.0

func NetContext(ctx context.Context, dir string, args ...string) (string, error)

NetContext is Net bounded by ctx as well as by NetTimeout: a caller with a deadline of its own (the shell guard reading the merge mode inside a host's hook) has git killed when ctx ends, and the error says so. It runs with the person's own configuration and credentials, as Net does, never prompting.

Unlike Net it runs none of the checkout's hooks (core.hooksPath=/dev/null): its callers read, and have no hook of the repository's to honour, so a fetch it makes runs no program the checkout chose. Once ctx ends, Wait waits netContextWaitDelay for a helper git started (a remote-https) to let go of the output, then returns, so the caller's deadline holds.

func NetEach added in v0.15.1

func NetEach(dir string, maxLine int, each func(line string), args ...string) error

NetEach is Net for a command whose output may run to any length (a listing of every ref under a prefix a pusher can fill): each line of stdout is handed to each as it is read, without its newline, and none is kept, so no bound on the whole output applies. A line longer than maxLine bytes is handed cut to its first maxLine. A failure's error carries git's bounded stderr, scrubbed, as Net's does.

func NetEnviron added in v0.17.0

func NetEnviron() []string

NetEnviron is the environment NetAskContext, Net, NetEach and NetInputContext give git, less the ssh command Net composes: for a caller that must read what that environment tells git (its home, its XDG_CONFIG_HOME, GIT_ATTR_NOSYSTEM).

func NetInputContext added in v0.17.0

func NetInputContext(ctx context.Context, dir, stdin string, args ...string) (string, error)

NetInputContext is Net with stdin fed to the command, bounded by ctx as well as by NetTimeout: a `git fetch --stdin` reads its refspecs there, one per line, so however many a fetch names, none lengthens its command line past the system's argument limit. The checkout's hooks run as Net's do (a push's pre-push hook still judges it); git is killed when ctx ends, and the error says so. stdin "" feeds the command nothing, so it serves a fetch or a push with no refspecs to feed. It is for a caller whose act may have to end with its own deadline (the sweep abcd runs on its own, through the reservations' fetch), where NetContext, which runs no hook, would skip a hook the repository asks for.

func ProveOperandDir added in v0.11.1

func ProveOperandDir(operand string) error

ProveOperandDir proves an operand directory a person named on a command line — a lifeboat, an embark target, a pack destination, an --out directory — against a symlinked ANCESTOR, which a leaf-only fsutil.IsRealDir cannot see.

The operand's declared base is the checkout it sits in: a checkout is the one place an untrusted commit can plant a link (a committed symlink beats .gitignore), so every level from that checkout's root down to the operand is proved a real directory with fsutil.ProbeRealDirAll, the read-only walk the local tier and the inbox use. A missing level ends the proof: nothing below it exists to be redirected, and a destination the verb creates starts there.

The checkout root's own entry lives in the directory above it, so it is proved by the next round rather than this one: the proof moves out to the checkout enclosing that root, if any, and proves the chain down to it the same way. That is what refuses a committed link pointing INTO another checkout, which a proof stopping at the nearest .git would take as its base.

Outside every checkout the path is the operator's own, taken as given under the trusted-worktree model: refusing there would refuse macOS's /var and /tmp links and every temporary directory, and protect nothing. The checkout is found with the .git marker walk (RepoShapedRoot) rather than git's answer: a marker read too widely only makes the proof stricter.

A refusal is an *OperandError whose Level is relative to its Checkout, which is the checkout's absolute path; a caller reporting it names the checkout by its base name, never the absolute path.

The operand is absolutised against the working directory first, whatever the caller passed: a relative path's marker walk ends at "." and never reaches the checkout above it, which would accept a link the proof exists to refuse, so the contract is held here rather than trusted to every caller (iss-2609262235543552).

func RefIsSafe added in v0.11.1

func RefIsSafe(ref string) bool

RefIsSafe reports whether a ref is safe to hand git as a POSITIONAL argument: non-empty and not option-shaped. A ref beginning with '-' parses as a flag — `--output=<path>` on a diff writes a file, `--upload-pack=<cmd>` on a fetch runs one — and no legitimate ref name starts with one, so refusing them drops only hostile or mistyped input. Every caller that interpolates a ref it did not write itself (a CI base sha, a user-named branch, a ref read out of a repository) checks it here first.

func RemoteHeadBranch added in v0.15.1

func RemoteHeadBranch(git func(dir string, args ...string) (string, error), root, remote string) (string, error)

RemoteHeadBranch asks the remote which branch is its default and returns the bare branch name: `git ls-remote --symref <remote> HEAD`, run through git, the caller's networked git runner (nil is Net: a network call, its environment scrubbed and its time bounded), read for the `ref: refs/heads/<branch>\tHEAD` line the remote advertises. A caller with a seam for its networked git (abcd land's Options.Git) passes it, so the call is the caller's to record and its answer the caller's to fake.

It is the authority for an act on the remote, unlike DefaultRef, which reads the tracked refs/remotes/origin/HEAD as this checkout last fetched it (or a conventional name), and so can be stale or missing. It never fetches and never writes: origin/HEAD stays as the repository has it.

An answer is an error, never a guess, when the remote cannot be asked, when it advertises no symref for HEAD (a detached HEAD), when the target is outside refs/heads/, when the name is empty or HEAD (whose tracking ref would be origin/HEAD itself), or when `git check-ref-format` refuses it.

func RemoteHeadTip added in v0.17.0

func RemoteHeadTip(ctx context.Context, git func(ctx context.Context, dir string, args ...string) (string, error), root, remote string) (branch, tip string, err error)

RemoteHeadTip asks the remote which branch is its default and which commit that branch's tip is: `git ls-remote --symref <remote> HEAD`, run through git, the caller's runner (nil is NetContext: the person's own configuration and credentials, none of the checkout's hooks, bounded by ctx as well as NetTimeout). NetContext buffers the whole answer in memory and judges its output cap only once git has exited, refusing an answer past the cap whole: until ctx or NetTimeout ends git, a remote can make the caller hold whatever it sends. It never fetches and never writes.

The answer is the remote's, so it is read as untrusted: it must carry exactly one symref line for HEAD, naming a branch under refs/heads/ that `git check-ref-format` accepts (asked under ctx), and exactly one object line for HEAD, a full object name. Anything else is an error, never a guess.

func RepoShaped added in v0.6.7

func RepoShaped(root string) bool

RepoShaped reports whether root sits anywhere inside a tree carrying a .git entry — a directory, or the file a worktree or submodule leaves. It is deliberately cruder than InRepo: its job is to tell "not a repository" apart from "a repository git would not answer for" (git absent from PATH, a corrupt .git, an ownership refusal under the isolated env). Only the first is safe to treat as "nothing is tracked here"; the others can commit, and nothing can say what git would answer.

It walks to the filesystem root, because git does: checking root alone answers "not a repository" for every SUBDIRECTORY of one.

func RepoShapedRoot added in v0.7.1

func RepoShapedRoot(root string) string

RepoShapedRoot is RepoShaped's walk with its answer kept: the nearest directory at or above root carrying a .git entry, or "" when there is none. It is the toplevel a caller can still bound work at when git itself will not name one — the ownership refusal under the isolated env, git absent from PATH, a corrupt .git — where the alternative is treating a real working tree as an unbounded directory.

It is a MARKER, not git's answer: it does not read .git, so it cannot tell a valid repository from a directory that merely holds the name, and for a submodule or linked worktree it reports the tree the .git file sits in (which is the working-tree root a config walk wants). A caller that needs git's own answer must ask git.

func RequireFullHistory added in v0.11.1

func RequireFullHistory(root string) error

RequireFullHistory refuses a shallow checkout. A gate that compares commits with their parents is blinded by one: past the graft a commit's parent is not present, so every change reads as a whole-file add and the check covers nothing. The probe is itself fail-closed — a git that cannot say whether the checkout is shallow is an error, never an assumed "full".

func ResolveCommit added in v0.11.1

func ResolveCommit(root, ref string) (string, error)

ResolveCommit resolves ref to the full object name of the commit it names, refusing an option-shaped ref before git sees it.

func ResolveRangeBase added in v0.11.1

func ResolveRangeBase(root, raw string) (string, bool, error)

ResolveRangeBase is the one derivation of the base a range-scoped gate checks from. raw is whatever the caller was handed — a CI event's base sha, or a ref a developer named — and there are three outcomes:

  • raw is empty (after trimming) or the null object name: there is no usable base for this event. It returns ("", false, nil), and the caller SAYS it skipped; it never reads the empty range as a clean one.
  • raw resolves to a commit: it returns that commit's full object name.
  • anything else — an option-shaped value, a name no commit answers to, a repository git cannot read — is an error. A base a gate cannot resolve is one it cannot judge from, and the error is the "refusing rather than reporting a vacuous pass" answer, never a quiet downgrade.

It exists so the zero-sha and absent-commit guard lives once, in Go, rather than hand-copied into every workflow step that runs a range gate.

func RevParseAbsPath added in v0.12.0

func RevParseAbsPath(dir, flag string) (string, error)

RevParseAbsPath asks `git rev-parse --path-format=absolute <flag>` for one path (--git-dir, --git-common-dir, --show-toplevel) and refuses any answer that is not exactly one absolute line. --path-format arrived in git 2.31: an older rev-parse echoes the option it does not know to stdout and exits 0, so its answer is the flag's text and a path on two lines, which a caller that compared it would read as a path. Refusing it keeps a resolution on an old git failing closed where it compares, never on a string that only looks like an answer.

func RevParseAbsPathContext added in v0.17.0

func RevParseAbsPathContext(ctx context.Context, dir, flag string) (string, error)

RevParseAbsPathContext is RevParseAbsPath bound to ctx, for a hook on a deadline: the same question and the same refusal, with git killed when ctx ends and the context's own error returned (RunLimitedContext).

func RootCommit added in v0.6.9

func RootCommit(root string) (string, error)

RootCommit returns the repository's canonical (first) root-commit SHA. A repository can have several root commits (an octopus of unrelated histories); the first `rev-list` reports is the canonical one, the same choice the history registry and the lifeboat probe make.

It returns ("", nil) only for the definite answers: root names no directory; git exited 128 and nothing at or above root, as written or with its symlinks resolved, carries a .git entry; or the repository has no commits yet. Every other failure is an error a caller must handle: ErrNoRootAnswer for a git that did not answer for a repository-shaped directory, and under RootCommitContext the context's own error for a git that had not answered when it ended. A failed git call is never read as an answer, since a caller keying a store on the identity would otherwise take a real repository for none (iss-2610051434156079).

The output is bounded (one object name, so the cap is generous) rather than buffered whole: a hostile repository must not be able to make an identity probe allocate. It has no deadline, so it waits for git's answer however loaded the machine is (contextWaitDelay): a slow git is never read as a repository with no root commit (iss-2610100846469473).

func RootCommitContext added in v0.13.1

func RootCommitContext(ctx context.Context, root string) (string, error)

RootCommitContext is RootCommit bound to ctx: the same answers, and a context that ends before git answers is returned as that context's error, with git killed.

func Run

func Run(root string, args ...string) (string, error)

Run executes a read-only git command under root with the developer's global and system config neutralised, returning trimmed stdout. It is the shared primitive for tooling that reads git history (the lifeboat probe's Tier-0 adapters); centralising it keeps every caller on the same isolated environment rather than re-deriving the exec plumbing. An error (git absent, not a repo, a failing subcommand) is returned verbatim so the caller can decide whether "git cannot answer" degrades to empty or is fatal.

func RunCapped

func RunCapped(root string, maxBytes int, args ...string) (string, error)

RunCapped is RunLimited for callers whose answer is only correct if it is COMPLETE. It returns an error rather than a truncated string when git's output exceeds maxBytes.

The distinction is the whole reason both exist. A truncated `git log` is not a shorter history; it is a wrong one, and a caller that cannot tell the two apart will publish the wrong one with no sign that anything was dropped. RunLimited's callers (the lifeboat probe over an archived repository) would genuinely rather have a partial answer than none, and keep that behaviour.

func RunCappedAsStored added in v0.15.1

func RunCappedAsStored(root string, maxBytes int, args ...string) (string, error)

RunCappedAsStored is RunCapped reading history as stored (asStored): for a read whose answer is a commit's parents or what a branch holds, which a replace ref or a graft could otherwise change.

func RunCappedBytes added in v0.11.1

func RunCappedBytes(root string, maxBytes int, args ...string) ([]byte, error)

RunCappedBytes is RunCapped without the trim: git's stdout exactly as written, or an error when it exceeds maxBytes. It is for a caller that reads FILE CONTENT through git — a blob's trailing blank lines and its last line's trailing whitespace are content, and a trimmed blob has a different line count from the committed one.

func RunCappedBytesAsStoredContext added in v0.15.1

func RunCappedBytesAsStoredContext(ctx context.Context, root, stdin string, maxBytes int, args ...string) ([]byte, error)

RunCappedBytesAsStoredContext is RunCappedAsStored bound to ctx, with stdin as the command's standard input ("" for none), returning stdout verbatim: for a deadline-bound read of history as stored, a batch of objects named on standard input among them. When ctx ends first, git is killed (isolatedGitContext) and the error wraps ctx's own; output past maxBytes is an error saying the cap was exceeded, never a truncated answer. git's output is read to EOF before Wait, as RunLimitedContext reads it, so a git that answered is read whole however late its output closes, until ctx ends.

func RunCappedBytesContext added in v0.16.0

func RunCappedBytesContext(ctx context.Context, root string, maxBytes int, args ...string) ([]byte, error)

RunCappedBytesContext is RunCappedBytes bound to ctx, as RunLimitedContext binds RunLimited: when ctx ends before git answers, git is killed (isolatedGitContext) and the error wraps ctx's own.

func RunCappedContext added in v0.17.0

func RunCappedContext(ctx context.Context, root string, maxBytes int, args ...string) (string, error)

RunCappedContext is RunCapped bound to ctx (RunLimitedContext's runner): an answer past maxBytes is an error, never a truncated string, and a run ctx ended answers ctx's own error.

func RunCappedExitOne added in v0.14.0

func RunCappedExitOne(root string, maxBytes int, args ...string) ([]byte, bool, error)

RunCappedExitOne is RunCappedBytes for a command whose exit status 1 is an answer rather than a failure: `merge-tree --write-tree` exits 1 when the merge conflicts, with the conflicted paths on stdout. It returns stdout verbatim and whether git exited 1; any other failure is an error carrying git's bounded stderr, and output past maxBytes is an error, never a truncated answer. git also exits 1 on some refusals (merge-tree's "not something we can merge"), so a caller checks the answer's shape.

func RunCappedExitOneAsStored added in v0.15.1

func RunCappedExitOneAsStored(root string, maxBytes int, args ...string) ([]byte, bool, error)

RunCappedExitOneAsStored is RunCappedExitOne reading history as stored (asStored).

func RunCappedExitOneAsStoredContext

func RunCappedExitOneAsStoredContext(ctx context.Context, root string, maxBytes int, args ...string) ([]byte, bool, error)

RunCappedExitOneAsStoredContext is RunCappedExitOneContext reading history as stored (asStored): for a deadline-bound ancestry verdict (`merge-base --is-ancestor`, which answers no with exit 1) that a removal or a landing acts on.

func RunCappedExitOneContext added in v0.17.0

func RunCappedExitOneContext(ctx context.Context, root string, maxBytes int, args ...string) ([]byte, bool, error)

RunCappedExitOneContext is RunCappedExitOne bound to ctx, for a hook on a deadline: git is killed when ctx ends, its output is read to EOF before Wait, and a run ctx ended answers ctx's own error, never a partial answer.

func RunCommitCommandBounded added in v0.16.0

func RunCommitCommandBounded(dir string, limit time.Duration, stalled error, args ...string) (string, error)

RunCommitCommandBounded runs WorkingTreeCommitCommand(dir, args...), so the repository's hooks, its signing and its signature checks run as on the person's own git, and bounds it: past limit git and the processes below it (its hooks, their children, a signing program it ran) are told to stop together (SIGTERM to git and each descendant, stopWithDescendants, so git removes its lock files), killed stopGrace later if they have not, and the call is refused with stalled, naming the bound. Git stays in abcd's process group, as the person's own git runs in the shell's, so a prompt on the terminal and an interrupt behave as they do there. A program a hook started that outlives a git which finished in time is not killed (the hook's own children are the repository's), but its hold on git's output is cut after stopGrace. A git that exited 0 made its change even then.

func RunCommitCommandBoundedAsStored added in v0.17.0

func RunCommitCommandBoundedAsStored(dir string, limit time.Duration, stalled error, args ...string) (string, error)

RunCommitCommandBoundedAsStored is RunCommitCommandBounded reading objects as stored (asStored): no replace ref or graft file stands another object in for one the repository stores, for git itself or for any git a hook it runs starts, since the environment is inherited. For a checkout that must write exactly the stored tree of a commit: a lane's `git worktree add`. Which hooks it runs is not the stored tree's to say: git takes the hooks directory at dir, the directory the command runs in.

func RunLimited

func RunLimited(root string, maxBytes int, args ...string) (string, error)

RunLimited is Run with a hard cap on how much stdout is buffered. A hostile or archived repository can make a read-only command (a full `git log`) emit arbitrarily much output; the unbounded `Output()` would buffer all of it. The probe uses this so a giant history cannot exhaust memory — output past maxBytes is discarded (the last retained line may be truncated, which degrades a single probe rather than crashing it). On failure the error carries git's bounded stderr — the reason, not just the exit status.

func RunLimitedContext added in v0.13.1

func RunLimitedContext(ctx context.Context, root string, maxBytes int, args ...string) (string, error)

RunLimitedContext is RunLimited bound to ctx: when ctx ends before git answers, git is killed (isolatedGitContext) and the error wraps ctx's own, so errors.Is(err, context.DeadlineExceeded) tells a caller that git did not answer in time rather than that it said no. It is the one primitive every deadline-bound git question goes through. git's output is read to EOF before Wait (contextWaitDelay), so a git that answered is read whole however late its output closes, until ctx ends.

func RunLimitedNetContext added in v0.16.0

func RunLimitedNetContext(ctx context.Context, root string, maxBytes int, args ...string) (string, error)

RunLimitedNetContext is RunLimitedContext for an isolated git command that reaches a remote (the implement loop's outage probe, an ls-remote): the same command and bounds, its environment built by netEnv, as every networked git command's is.

func RunTreeCommand added in v0.16.0

func RunTreeCommand(cmd *exec.Cmd, args []string) (string, error)

RunTreeCommand runs cmd, a WorkingTreeCommand or WorkingTreeCommitCommand built for args, and returns its stdout verbatim: a porcelain status line opens with a space when the change is unstaged, and a caller compares against the line as git wrote it. A failure names the subcommand and git's bounded stderr; output past the cap is refused rather than cut.

func RunWithIndex added in v0.13.4

func RunWithIndex(root, index string, maxBytes int, args ...string) ([]byte, error)

RunWithIndex runs one isolated git command in root against the index file index instead of the repository's own, and returns its stdout verbatim. It is how a caller stages or diffs a working tree without disturbing what the person staged: `read-tree HEAD` and `add -A` into a scratch index, then a diff of it, leave the repository's index exactly as it was. The environment is the isolated one (gitEnv), which strips any inherited GIT_INDEX_FILE, with the caller's appended after it, so it is the one git reads. index must be an absolute path, kept outside root's working tree (a scratch index inside the tree would be staged by its own `add -A`). The scratch index is written whole, never split (core.splitIndex off), so a repository set to split its index gains no shared index file in its git directory from it. Output past maxBytes is an error, never a truncated answer: a cut-short patch is a wrong one.

func RunWithIndexAsCheckedOut added in v0.17.0

func RunWithIndexAsCheckedOut(root, index string, maxBytes int, args ...string) ([]byte, error)

RunWithIndexAsCheckedOut is RunWithIndex in the environment a checkout made through RunCommitCommandBoundedAsStored was made in, for a comparison of that checkout with the commit it was made from: the person's global and system config, or in a drive the stage's (SetHookedEnv), so the content filters, attributes and line-ending settings the checkout was written under read it back; objects read as stored (AsStoredEnv); the program-starting knobs, the hooks among them, pinned off (ExecPins), as WorkingTreeCommand pins them; GIT_NO_LAZY_FETCH=1 and the lazy-fetch floor guard. Its content filters run, so the check SetBeforeHookedGit set is asked first, and git does not run on its error.

func ScrubURLCredentials added in v0.15.0

func ScrubURLCredentials(text string) string

ScrubURLCredentials applies ScrubURLUserinfo to every scheme-form URL in text (git's or the forge client's message, which can quote a remote URL carrying a token: `https://user:token@host/...`, `https://token@host/...`), and empties the value of an access_token or token query parameter (`https://host/...?access_token=...`), so none reaches what abcd prints.

func ScrubURLUserinfo added in v0.15.0

func ScrubURLUserinfo(s string) string

ScrubURLUserinfo drops any credential from a git remote URL, keeping a login the transport needs (the rule ahoy's registry and `abcd land` share, GHSA-qc3w-8pv5-crc3):

  • scheme form (`scheme://[userinfo@]host/path`): a userinfo carrying a password is dropped whole under any scheme; under http(s) a bare user is dropped too, because the forge accepts a token as the user with no password; under any other scheme (ssh, git+ssh) a bare user is the login name the transport needs, so it stays;
  • scp-like form (`[user@]host:path`): a user segment carrying a password is dropped; `git@host:path` is an SSH login and stays. The form is recognised by the host:path colon that FOLLOWS the userinfo, so a remote whose path contains an @ is not mistaken for one.

Everything else — a local path, an empty value — is returned unchanged. That includes `user:secret@host/path`, which is neither form: with no scheme and no host:path colon, git reads it as a relative local path, not a remote.

func ScrubbedEnv

func ScrubbedEnv() []string

ScrubbedEnv is IsolatedEnv without the global/system config-file neutralisers: the parent environment with every repo-selection and config-injection variable stripped (GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE, GIT_CONFIG_COUNT/PARAMETERS/ KEY_*/VALUE_*, …) but with ~/.gitconfig and the system config still in effect. It is for a git command that MUST honour the developer's real global config — the identity probe reads user.name/user.email to redact the caller's OWN identity, and those overwhelmingly live in global config, so suppressing it (as IsolatedEnv does) would blind the probe and silently stop redacting a real identity leak. Scrubbing still defeats the two attacks that matter here: an inherited GIT_DIR redirecting the probe at a different repository, and an injected GIT_CONFIG_* forging a fake identity that displaces the real one.

func SetBeforeHookedGit added in v0.17.0

func SetBeforeHookedGit(f func(args []string) error) (clear func(), err error)

SetBeforeHookedGit sets a check every git command abcd starts with the repository's hooks, merge drivers or content filters on, or that reaches a remote, asks first, before the command is built: Net, NetEach, NetInputContext, NetContext and LocalGit (runHookedContext), RunCommitCommandBounded and RunCommitCommandBoundedAsStored (runCommitBounded), WorkingTreeCommand and WorkingTreeCommandContext, and RunLimitedNetContext. An isolated command (Run and its kin) has its hooks and the other programs ExecPins names pinned off, but not content filters, textconv and external diff programs or merge drivers, so one that can start one of those (LeavesContentProgramsOn: a hash-object, a status with the filters left on, a diff of the working tree that does not blank them, a subcommand it does not know) asks too, and one that blanks them or reads no content through them does not. An error from the check is the command's, and git does not run. A drive sets it to its comparison of what it holds while it runs (implement/loop's heldBeforeGit); it is given the command's arguments. One drive runs in a process, so a check already set is not replaced: the call is refused with ErrBeforeHookedGitSet. The returned clear removes this check and only this one. The comparison's own reads never ask it, by the route they take, not by their command lines: they run through NetAskContext and WorkingTreeCommitCommand built directly, which ask nothing, and the isolated runners under a context WithinCheck marked, which do not ask. With no check set nothing changes.

func SetBeforeHookedGitAt added in v0.17.0

func SetBeforeHookedGitAt(f func(dir string, args []string) error) (clear func(), err error)

SetBeforeHookedGitAt is SetBeforeHookedGit for a check that is also given the directory the command runs in, as its runner was given it (the directory of a WorkingTreeCommand, the root of an isolated command, the dir of Net): a drive's comparison reads a lane worktree's own settings only for a git that runs in that worktree.

func SetHookedEnv added in v0.16.2

func SetHookedEnv(f func([]string) []string)

SetHookedEnv narrows the environment of the commands that run a repository's hooks on this process's behalf, the push's excepted, since a push is what needs the person's credentials; nil leaves it as it is.

func ShortRef added in v0.11.1

func ShortRef(ref string) string

ShortRef renders a full ref the way a person names it: origin/main for a remote-tracking ref, main for a local branch.

func StartsNothing added in v0.17.0

func StartsNothing(verb string) bool

StartsNothing reports whether verb is a subcommand startsNothing holds, which LeavesContentProgramsOn lets run without asking in the form abcd runs it (startsInForm judges the others).

func StatusArgs added in v0.17.0

func StatusArgs(opts ...string) []string

StatusArgs is the command line of a `git status` abcd runs, whatever runner runs it: "status", then --ignore-submodules=dirty, then opts (the caller's options and pathspecs). Status builds its own with it, and so do the status reads of the build loop (internal/core/implement/loop) and of the land verb (internal/core/landing) that name it; what it says holds for those.

Without the flag git starts a status inside each checked-out submodule (a path the index records as a submodule, with a repository under it, whether or not .gitmodules names it), under that submodule's own settings, so a content filter they name runs there. With it git starts nothing there: a submodule whose checked-out commit is not the one the index records is still listed, and uncommitted changes inside a submodule's working tree are not. git-status(1): "Using "dirty" ignores all changes to the work tree of submodules, only changes to the commits stored in the superproject are shown". The flag on the command line outranks a submodule.<name>.ignore setting and diff.ignoreSubmodules.

func StreamAsStored

func StreamAsStored(root string, w io.Writer, args ...string) error

StreamAsStored runs one git command as stored (asStored) with its stdout written to w as git writes it, for an answer the caller keeps whole rather than reads, such as a bundle written to a file the caller opened itself: no cap applies, and git never opens a path of its own for it. A failure carries git's bounded stderr.

func StreamWithIndex added in v0.16.1

func StreamWithIndex(root, index string, w io.Writer, args ...string) error

StreamWithIndex is RunWithIndex for an answer the caller reads as git writes it, such as a listing of every entry it hashes, so no cap is needed: git's stdout goes to w, and its stderr, bounded, into the error.

func StreamWithIndexAsCheckedOut added in v0.17.0

func StreamWithIndexAsCheckedOut(root, index string, w io.Writer, args ...string) error

StreamWithIndexAsCheckedOut is StreamWithIndex in RunWithIndexAsCheckedOut's environment.

func Subcommand added in v0.17.0

func Subcommand(args []string) string

Subcommand is the git subcommand args run, past git's global options and their values; "" when there is none.

func SubcommandIndex added in v0.17.0

func SubcommandIndex(args []string) int

SubcommandIndex is the index of args' subcommand, past git's global options and their values (TakesGlobalValue), -1 for none.

func SwapAccountHomeForTest added in v0.14.0

func SwapAccountHomeForTest(fn func() (string, error)) (restore func())

SwapAccountHomeForTest substitutes the account-database home lookup HomeInsideWorkingTree exempts and returns the restore. It is exported because the tests of the rule's callers live in other packages. Tests only; never called in production code, and never safe to call from a parallel test.

func SwapGitVersionForTest added in v0.13.4

func SwapGitVersionForTest(src func() (string, error)) (restore func())

SwapGitVersionForTest replaces the `git version` probe, so a test in any package can put git on either side of a floor whatever is installed; the swap moves the lazy-fetch floor and the merge driver's options together. It returns the restore, which puts the real probe back; the cached answer is cleared both ways.

func TakesGlobalValue added in v0.17.0

func TakesGlobalValue(a string) bool

TakesGlobalValue reports whether a, a word before git's subcommand, is a global option that takes the next word as its value (-c, -C, --git-dir, --work-tree, --namespace, --config-env, --super-prefix, --attr-source).

func Toplevel added in v0.11.1

func Toplevel(dir string) (string, error)

Toplevel asks git for the working-tree root that contains dir, and holds the answer to the one shape git ever gives: a single absolute line naming a directory at or above dir. Anything else (relative, several lines, empty, a directory elsewhere) is refused with ErrToplevelShape rather than handed on as a root, because every caller bounds work at the answer: it is where a ledger, a rules file or a site is read and written. It is the one call every `rev-parse --show-toplevel` in the module goes through, so the rule is kept once (iss-2608292038186663).

A git failure (not a repository, git absent, an ownership refusal under the isolated environment) is returned as git's own error; a caller that must tell "no repository" from "a repository git will not answer for" follows up with RepoShapedRoot. It has no deadline, so a slow git is waited for, never read as either (contextWaitDelay).

func ToplevelContext added in v0.13.1

func ToplevelContext(ctx context.Context, dir string) (string, error)

ToplevelContext is Toplevel bound to ctx, for a caller on a deadline (the status verb): the same question and the same shape check, with git killed when ctx ends and the context's own error returned (RunLimitedContext), so the caller can tell a slow git from "not a repository".

Containment is not enough on its own: a repo-local core.worktree is resolved by git relative to the .git directory, so `core.worktree=../..` in a copied checkout names the checkout's PARENT, which contains dir and passed the shape check, widening every record store to the parent (iss-2610090821543020). So git is asked, in the same invocation, for the git directory it discovered, and the toplevel is accepted only when it holds that directory: its .git is the directory itself, or a gitfile naming it (a linked worktree, a submodule, a --separate-git-dir checkout). An ancestor that core.worktree alone selected holds no such entry and is refused with ErrToplevelShape.

func ToplevelShaped added in v0.11.1

func ToplevelShaped(dir, top string) bool

ToplevelShaped reports whether top has the shape of git's toplevel answer for dir: one absolute line naming a directory that contains dir. It is Toplevel's check, for the callers that must run git themselves (a command that pins the git binary it runs, or asks for the path in another format).

func TrackedDefaultBranch added in v0.15.1

func TrackedDefaultBranch(root, remote string) string

TrackedDefaultBranch is the named remote's default branch as this checkout last fetched it, with no network: the remote's HEAD target, then the conventional names under the remote, and never a local branch. It is a ref under refs/remotes/<remote>/, or "" when none resolves.

It is a local reading, so it can be stale (the remote's HEAD moved since the last fetch) or guessed (no HEAD recorded, so the first conventional name present wins). It serves readers that measure against the default branch; it must never decide an act on the remote, such as which branch a push may target, which asks the remote itself. A listing past its 64 KiB cap is refused whole, and the branch is then asked ref by ref, for a few more git processes; resolveDefault names where a question per ref can answer differently from the listing.

func TrackedDefaultBranchContext added in v0.17.0

func TrackedDefaultBranchContext(ctx context.Context, root, remote string) string

TrackedDefaultBranchContext is TrackedDefaultBranch with every git question bounded by ctx, as DefaultRefContext bounds its own: a ctx already ended starts no git, a git still running when it ends is killed, and the answer is "". Its answers are capped as TrackedDefaultBranch's are. A caller that must tell "no default branch" from "git did not answer in time" checks ctx.Err() after it.

func TrackedFiles

func TrackedFiles(root string) ([]string, error)

TrackedFiles returns the repo-relative paths git tracks under root, NUL-safe so a filename with a newline cannot desync the list. Outside anything repo-shaped it returns no files and no error — a scan over committed files then degrades to "nothing to scan" rather than failing. In a repo-shaped tree git cannot answer for, and inside a repo on any other ls-files failure (a corrupt index, say), it returns an error, so a caller cannot mistake "could not read the repository" for "nothing tracked" and report a scanning rule compliant after reading zero files.

func TrackedFilesContext added in v0.16.0

func TrackedFilesContext(ctx context.Context, root string) ([]string, error)

TrackedFilesContext is TrackedFiles with both of its git calls bound to ctx; a context that ends first is git not answering, an error.

func TrackedInTreeContext added in v0.16.0

func TrackedInTreeContext(ctx context.Context, top string) ([]string, error)

TrackedInTreeContext is TrackedFilesContext for the working tree whose top is top, judged as that tree whatever core.worktree names: git is told the tree in its own environment, which changes nothing in the repository, so a core.worktree set elsewhere neither hides what the index tracks nor reads as a tree git cannot answer for.

Every state read lands here, so a listing git gives is taken as it stands and starts one git: told the tree by an absolute path and standing in it, git is inside its working tree whenever it finds a repository at all, so asking first could not change the answer. A relative top is not that case (git reads it from inside the tree), and plain TrackedFilesContext is not either: with no tree named, `ls-files` lists the index of a checkout with core.bare set, where the question answers false. Only a failed listing costs more: it asks again in full, so what a failure means (not a repository, a repository git refused, an index it cannot read) stays decided in one place.

func TreePathTypes added in v0.15.1

func TreePathTypes(root, commit string, paths []string) ([]string, error)

TreePathTypes asks ONE isolated `git cat-file --batch-check` for the type of what commit's tree holds at each path, one `<commit>:<path>` line on stdin per path, and answers in the order asked: "blob" (a file or a symbolic link, which git stores as a blob), "tree", "commit" for a submodule's gitlink, or "" for a path the tree does not hold, a path beneath a gitlink or through a symbolic link among them. Git answers a gitlink "<sha> commit" when this repository holds the commit it names, and "<sha> submodule", ignoring the format asked, when it does not (git 2.51 and later); both are "commit" here, never an error. An older git answers that absent gitlink "missing", as it answers a path the tree does not hold, so there it is "". Each path is resolved on its own, so a directory asked beside a path beneath it is still answered as a tree, and the answer is one short line per path, whatever the trees beneath hold. commit must be a full object name, and a path holding a newline or a NUL, or none at all, never reaches git. Each path is resolved in the tree commit stores (asStored), as CatFileBatch reads each object: no replace ref, graft or commit-graph stands another tree in for it.

func WithinCheck added in v0.17.0

func WithinCheck(ctx context.Context) context.Context

WithinCheck is ctx marked as the context of a read the check SetBeforeHookedGit set makes itself (implement/loop's comparison of what a drive holds): an isolated runner bound to it does not ask that check, whatever its command line is, so a change to what LeavesContentProgramsOn reads, or a value in a read's command line, can never make the check ask itself. The hooked and networked runners the check reads through (NetAskContext, WorkingTreeCommitCommand built directly) ask nothing in any case.

func WorkingTreeCommand added in v0.14.1

func WorkingTreeCommand(root string, args ...string) *exec.Cmd

WorkingTreeCommand builds a git command under root that writes or judges a working tree the way the person's own git does: it reads the person's global and system config (ScrubbedEnv), so the content filters, ignore files and line-ending settings a repository relies on there apply. A filter that a global `git lfs install` defines is the case that made it necessary: under the isolated environment a lane's `git worktree add` and a restart's `reset --hard` wrote Git LFS pointer text where the person's own git writes the files (iss-2610111729375108). The git commands that check files out into a working tree, stage it, clean it or commit from it use this; a read whose answer abcd parses stays isolated.

Only which config files git reads changes. The program-starting knobs stay pinned off (ExecPins), automatic maintenance is off on the command line (gc.auto=0, maintenance.auto=false: ScrubbedEnv does not pin them as the isolated environment does, and a commit or merge would otherwise start `gc --auto`, which runs gc.recentObjectsHook, iss-2610091935334207), GIT_NO_LAZY_FETCH=1 keeps a partial clone from fetching a missing object through its promisor remote, and the command passes the lazy-fetch floor guard every isolated command passes.

Its content filters run, so the check SetBeforeHookedGit set is asked first, before the command is built; an error from it is set as the command's Err, so Run, Output and Start return it and git never starts.

func WorkingTreeCommandContext added in v0.17.0

func WorkingTreeCommandContext(ctx context.Context, root string, args ...string) *exec.Cmd

WorkingTreeCommandContext is WorkingTreeCommand bound to ctx, for a caller on a deadline: git is killed when ctx ends (exec.CommandContext's default), so it is only for a command that writes nothing to the repository or the working tree (a status read with --no-optional-locks, an ls-files listing), whose interruption leaves nothing to repair. A command that removes or rewrites files, `git worktree remove` among them, runs unbound. It asks the check SetBeforeHookedGit set as WorkingTreeCommand does.

func WorkingTreeCommitCommand added in v0.14.1

func WorkingTreeCommitCommand(ctx context.Context, root string, args ...string) *exec.Cmd

WorkingTreeCommitCommand is WorkingTreeCommand for a git command that runs the repository's hooks on a working tree abcd makes for the work, so a lane's record commit, a merge into a lane, a lane's reset --hard and the `git worktree add` that checks the lane out all use it: the repository's hooks, its commit signing and its merge's signature check run as they do on the person's own commit, merge, reset and checkout, so it is WorkingTreeCommand without those three pins (ExecPins names them: core.hooksPath, commit.gpgsign, merge.verifySignatures). Each is the repository's own behaviour, and a program it names there runs on the person's own next commit with no abcd involved, so switching it off for abcd prevented nothing and changed how the repository works (iss-2610111729399920, principle abcd-fixes-what-it-adds). A content filter and a merge driver the repository configures run too, as they do under WorkingTreeCommand. Everything else is WorkingTreeCommand's.

A program the repository's settings start can wait on a person (a GUI pinentry, a hook that prompts), so the command is bound to ctx, which the caller gives a deadline so an unattended run is never held by one nobody answers. It sets no Cancel or WaitDelay itself, and a ctx that expires without them SIGKILLs git (exec.CommandContext's default), which leaves its lock files (index.lock) and a half-written checkout behind. So the caller sets Cancel to send SIGTERM, on which git removes its locks, and WaitDelay to bound how long a program a hook left running may hold git's output pipes once git has exited (RunCommitCommandBounded does both, and stops git's descendants with it). After a Cancel that succeeded, Wait reports the context's error even when git then exited 0, so a caller that needs to know whether git's work was made checks ProcessState.

func WorkingTreesAround

func WorkingTreesAround(dir string) []string

WorkingTreesAround is every working tree dir lies in, nearest first: each directory at or above dir that carries a .git entry (RepoShapedRoot's marker, judged at every level rather than the nearest alone), walked both as dir is spelled and at its physical path. A submodule's superproject, and a checkout that holds another checkout, are named with the tree dir is in. The account's own home is left out, as HomeInsideWorkingTree leaves it out: a dotfiles-in-HOME account keeps its home in a working tree, and that home is the person's.

It is the bound a program abcd runs is held outside of (tools.GuardForms): git's own toplevel for dir is one of these directories, since git names a toplevel only where its .git sits (ToplevelContext). It reads directory entries and git's own link files alone, starts no git and reads no repository configuration, so it answers at once whatever a repository's configuration holds, and it still names a tree git would refuse to answer for (another account's checkout, an unsafe directory). The repository's other working trees are named as well, after the trees above dir: for each tree that is a main checkout or a linked worktree, the main checkout and then every linked worktree its shared git directory lists (repositoryTrees, read from git's link files alone), so a program in any working tree of the same repository is held from every other. The account's own home is not read for its worktrees.

Types

type ArchiveEntry added in v0.11.1

type ArchiveEntry struct {
	Path string
	Mode string
}

ArchiveEntry is one file `git archive` would write for a revision: its repo-relative path and its git mode (100644, 100755 or 120000 for a link).

func ArchiveTree added in v0.11.1

func ArchiveTree(root, rev string) ([]ArchiveEntry, error)

ArchiveTree lists the files an archive of rev would carry — the release tag's view of the tree — without running `git archive` itself. `git archive` applies the repository's filter drivers, and a checkout's own .git/config is fully trusted by git, so the listing is built from the two commands that run no configured program: `ls-tree` for the committed files, and `check-attr` for the export-ignore attribute archive honours, asked of each file and of every directory above it (an ignored directory drops everything beneath it). A directory is asked as `dir/`, the form archive itself asks: only a path that ends in a slash matches the directory-only pattern (`dir/ export-ignore`), a bare pattern (`dir export-ignore`) matches it too, and where the two forms disagree (`dir export-ignore` then `dir/ -export-ignore`) the answer for `dir/` is the one archive acts on. Asking `dir` as well would drop a directory archive keeps, and the scan would miss files the tag ships. Submodules are skipped: archive carries no submodule content.

Attributes are read from rev's own .gitattributes, the files git archive reads, so neither a working-tree edit nor a staged one changes the answer (iss-2609260933592838). Where the index holds exactly rev's .gitattributes they are asked of the index (--cached), which every git answers; where they differ they are asked of rev itself (--source, git 2.40 or later), and a git that cannot is refused by name rather than answered from the index. An error is a tree git could not list — no commit at rev, not a repository, git absent — and is never reported as an empty tree.

type BatchObject added in v0.15.1

type BatchObject struct {
	Name    string
	Type    string
	Content string
	Missing bool
}

BatchObject is one object `git cat-file --batch` answered for: its type and content, or Missing when the repository holds no object of that name. Content is a slice of the batch's one answer, never a copy of it.

func CatFileBatch added in v0.15.1

func CatFileBatch(root string, objects []string, maxBytes int) ([]BatchObject, error)

CatFileBatch reads objects through ONE isolated `git cat-file --batch`, in the order asked, so a caller reading many blobs starts one process rather than one per blob. Every name must be a full object name, so nothing but names reaches git's input. maxBytes caps git's whole answer, headers included: an answer past it is an error, never a truncated one, so a caller bounds it by what it already knows of each object's size. An answer whose shape git does not document is an error too. Each object is read as stored (asStored): no replace ref stands another's bytes in for the one named.

The answer is read into one buffer sized to maxBytes up front, so it is never grown by copying, and each object's content is a slice of it: what the batch holds in memory is about maxBytes, however many objects it reads.

type ConfigEntry added in v0.14.0

type ConfigEntry struct {
	Scope   string
	Key     string
	Value   string
	NoValue bool
}

ConfigEntry is one configuration entry a repository sets: the scope git read it from ("local" for the repository's config and the files it includes, "worktree" for the working tree's own), its canonical key (section and variable lower-cased, a subsection as written) and its value. A key written with no value (a bare boolean) has an empty value and NoValue set.

func RepoConfig added in v0.14.0

func RepoConfig(root, pattern string) ([]ConfigEntry, error)

RepoConfig lists, in the order git reads them, the entries the repository at root sets whose canonical key matches pattern (an extended regular expression, as `git config --get-regexp` takes one). Config is read as configNames reads it: the repository's config and its includes, global and system neutralised. The `-c` pins every isolated command carries are abcd's own, not the repository's, and are left out, as is anything else git reads from outside the repository's own files. Nothing matching is an empty list.

A value is the repository's to keep: a credential helper's may carry a secret, so a caller that stores or prints anything about an entry keeps to its key.

type Held added in v0.17.0

type Held struct {
	// Branches maps each branch a stopped rebase or bisect started from, by
	// short name, to the git dir whose state names it: the common dir for the
	// main checkout, or <common>/worktrees/<id> for a linked worktree. These
	// are the branches `git switch` and `git worktree add` also refuse.
	Branches map[string]string
	// Rewrites maps each branch a stopped rebase's --update-refs list will
	// rewrite to that git dir in the same way: `git branch -d` and `git
	// branch -f` refuse these too, though `git switch` does not.
	Rewrites map[string]string
	// Unreadable is the first state file, or the worktrees directory, that is
	// there and could not be read through fsutil.ReadGuarded (a symlink, not a
	// regular file, past its cap) or that git would not have written; "" when
	// every one was read. The branch it names is unknown, so a caller about to
	// act counts every branch as held.
	Unreadable string
	// Common is the common dir the branches were read under, the git dir
	// Branches and Rewrites name for the main checkout.
	Common string
}

Held is every local branch a worktree holds that git's worktree listing does not name: git lists a worktree whose rebase or bisect stopped as detached, yet counts the branch the rebase or bisect started from, and each branch a rebase's --update-refs will rewrite, as in use there. It is the one rule every caller asks before it deletes a branch, moves one, or counts one as checked out, alongside the branches ListWorktrees names.

func HeldBranches added in v0.17.0

func HeldBranches(common string) Held

HeldBranches reads every branch a rebase or a bisect stopped in some worktree of the repository whose common dir is common holds: the main checkout's git dir (common itself) and each linked worktree's (common/worktrees/<id>, the entries `git worktree list` lists).

func (Held) Checkout added in v0.17.0

func (h Held) Checkout(dir string, wts []Worktree) string

Checkout is the checkout a git dir h names belongs to, for a message to point the person at: the main checkout (wts' first entry, which git lists first, unless it is bare) for the common dir itself, and for a linked worktree's <common>/worktrees/<id> the checkout its gitdir file names (that checkout's .git, relative to the admin dir when worktree.useRelativePaths wrote it), since git picks the id when the worktree is added and it can differ from the checkout's folder (a second "look" gets look1). A relative gitdir is joined to dir's real path, as git writes and reads it, so a common dir reached through a symlink still names the checkout. The path is given as wts lists it when an entry is that checkout. dir itself when it is neither, when the gitdir file cannot be read, or when its text holds a rune termsafe.Sanitize would mask (a control character, a line break, a bidi or invisible rune): that text names no folder a person could open, and the answer is printed. Every answer is passed through termsafe.Sanitize, which leaves a clean path as it is: dir and the common dir end in names read from disk unchecked (an admin dir is any folder under <common>/worktrees), so a line break or an escape in one is masked rather than printed.

type NotRunError added in v0.17.0

type NotRunError struct {
	Verb string
	Err  error
}

NotRunError is a git command abcd did not run. It has two makers: the check SetBeforeHookedGit set refused the command (askBeforeHooked, for a hooked or networked runner, and askIfContentRuns, for an isolated one), or, for a networked command, the read of core.sshCommand that decides the ssh command it runs gave no answer of git's (hookedCommand). Verb is its subcommand; Err is the check's refusal or the failed read. Whatever exit status Err wraps is not the command's: ExitCode reads none.

func (*NotRunError) Error added in v0.17.0

func (e *NotRunError) Error() string

func (*NotRunError) Unwrap added in v0.17.0

func (e *NotRunError) Unwrap() error

type OperandError added in v0.11.1

type OperandError struct {
	Checkout string
	Level    string
	Err      error
}

OperandError is ProveOperandDir's refusal: Level, a directory inside the checkout rooted at Checkout and named relative to it, could not be proved a real directory. Err is the cause with no path in it (fsutil.ErrNotRealDir for a symlink or a non-directory), so a caller tests the class with errors.Is and phrases the message itself; Checkout is absolute and is for the caller to shorten, never to print whole.

func (*OperandError) Error added in v0.11.1

func (e *OperandError) Error() string

func (*OperandError) Unwrap added in v0.11.1

func (e *OperandError) Unwrap() error

type StatusEntry added in v0.13.0

type StatusEntry struct {
	// XY is the entry's two status columns as git writes them: "??" an
	// untracked path, "!!" an ignored one, otherwise the index column and the
	// working-tree column.
	XY string
	// Path is the path as git reports it, relative to the repository's root
	// and verbatim (the -z form never quotes or escapes it). A path git
	// reports whole as a directory ends in "/": an ignored directory under
	// StatusOptions.Ignored, or an untracked nested repository.
	Path string
	// Orig is a rename's or a copy's source path, and empty for every other
	// entry.
	Orig string
}

StatusEntry is one entry of git's NUL-separated status listing (`git status --porcelain=v1 -z`).

func ParseStatus added in v0.13.0

func ParseStatus(out []byte) []StatusEntry

ParseStatus parses git's NUL-separated status listing.

The -z form is what makes it parseable: each entry is NUL-terminated and its path is never quoted or escaped, so a filename holding a space, a quote or a newline arrives verbatim and core.quotePath cannot change the format under the parser. A rename's or a copy's source follows its entry as a record of its own, and either column can declare one (`R ` a staged rename, ` R` a working-tree one); it is carried as Orig, never read as an entry.

func Status added in v0.13.0

func Status(root string, maxBytes int, opt StatusOptions) ([]StatusEntry, error)

Status is the working tree's status under root, as git lists it: `git --no-optional-locks status --porcelain=v1 -z --untracked-files=all`, run through the isolated environment and refused, never truncated, past maxBytes. It is the one reader of that listing; a caller that needs a variant adds it to StatusOptions.

--untracked-files=all is fixed: under git's default an untracked directory collapses to one entry, and a file inside a new directory is never named. --no-optional-locks keeps the read from refreshing the index, which the isolated environment's GIT_OPTIONAL_LOCKS=0 already does; it is stated on the command so the read stays read-only whatever environment runs it.

The repository's content filters are off (FilterOverrides): over a file whose saved stat no longer matches, git status re-reads it through filter.<name>.clean, a program the repository names, and these are everyday reads (iss-2610090821548169). The person switches them back on for a checkout by listing it in ~/.abcd.noindex/filter-roots (FiltersSwitchedOn). With them off, a file a filter would have rewritten can read as modified, and a filter the repository marks required fails the read. With them on, the read asks the check SetBeforeHookedGit set before git runs, as every isolated command that can start a filter does (isolatedGit); with them off it carries the blanks and asks nothing, since it starts no program. Where the repository names no filter there is nothing to blank, so the read asks all the same: the command line alone cannot show that none is named.

--ignore-submodules=dirty (StatusArgs) keeps git from starting a status inside each checked-out submodule, which reads the submodule's own config and so runs a clean filter FilterOverrides cannot see (iss-2610091935327982). The flag, not diff.ignoreSubmodules: a repository's submodule.<name>.ignore=none beats that config and loses to the flag. A moved submodule pointer is still listed; uncommitted content inside a submodule is not.

type StatusOptions added in v0.13.0

type StatusOptions struct {
	// Ignored lists ignored paths too (--ignored=matching): a file that
	// matches an ignore pattern by itself, and a directory that matches one
	// as the directory alone, never what is inside it.
	Ignored bool
	// Pathspecs, when any, narrows the listing to them.
	Pathspecs []string
}

StatusOptions are the variants of the status listing Status runs.

type TreeEntry added in v0.17.0

type TreeEntry struct{ Mode, OID string }

TreeEntry is one entry of a verified tree that is not itself a tree: a file (100644 or 100755), a symbolic link (120000) or a submodule's commit (160000), with its object name.

type VerifiedObjects added in v0.17.0

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

VerifiedObjects reads a repository's objects through one isolated `git cat-file --batch`, as stored (asStored), and re-hashes each against its name, in the repository's object format, before handing it on. git checks the hash of a commit and of a root tree when it parses them, but `git ls-tree`, `git archive` and `git cat-file` read any other object as its file holds it, so an object written over a subtree or a blob of a commit would otherwise put other files where the commit's belong. A Tree walk and the Blob reads after it share the one process.

func OpenVerifiedObjects added in v0.17.0

func OpenVerifiedObjects(ctx context.Context, root string) (*VerifiedObjects, error)

OpenVerifiedObjects starts the reader for the repository at root, git killed when ctx ends. Close ends it.

func (*VerifiedObjects) Blob added in v0.17.0

func (v *VerifiedObjects) Blob(oid string) ([]byte, error)

Blob reads the blob named oid, checked against its name.

func (*VerifiedObjects) Close added in v0.17.0

func (v *VerifiedObjects) Close()

Close ends git. A read may have stopped at a refusal with git still writing an answer nobody reads, so git is killed rather than waited for.

func (*VerifiedObjects) Tree added in v0.17.0

func (v *VerifiedObjects) Tree(commit string) (map[string]TreeEntry, error)

Tree reads commit and every tree under it, each checked against its name, and returns every entry that is not a tree by its slash-separated path. An entry named ".", ".." or holding a slash, a mode git does not write, or a tree that is not well formed is an error, as is a walk past maxVerifiedTreeObjects objects or maxVerifiedTreeBytes bytes.

type Worktree added in v0.10.0

type Worktree struct {
	Path   string
	Head   string // the object name HEAD points at; "" for a bare entry
	Branch string // the full ref ("refs/heads/…"); "" when detached or bare
	Bare   bool
	// Detached is git's `detached` attribute: HEAD names a commit, not a branch.
	Detached bool
	// Locked is git's `locked` attribute, with its reason when one was given
	// ("" for a bare `locked`): git refuses to remove or prune the worktree.
	Locked     bool
	LockReason string
	// Prunable is git's `prunable` attribute, with its reason: git would drop
	// the entry on `git worktree prune` (most often its directory is gone).
	Prunable       bool
	PrunableReason string
}

Worktree is one record of `git worktree list --porcelain`: a working tree this repository knows about, as git names it.

func ListWorktrees added in v0.10.0

func ListWorktrees(root string, maxBytes int) ([]Worktree, error)

ListWorktrees lists every working tree of the repository at root, the main one first (git documents that order), with its output capped at maxBytes as RunCapped caps it.

It asks for the NUL-separated form first, which is the only one that carries a path holding a newline intact, and falls back to the newline-separated form when git refuses it: `-z` arrived in git 2.36, and a git older than that (the 2.34 an LTS distribution still ships) answers "unknown switch" and exit 129. Falling back on any refusal rather than on that exact message keeps the fallback independent of how a given git words it; a failure the older form shares (not a repository, the cap exceeded) fails there too and is returned. The newline form is exact for every path without a newline in it, which is the only limit it carries.

func ListWorktreesContext added in v0.17.0

func ListWorktreesContext(ctx context.Context, root string, maxBytes int) ([]Worktree, error)

ListWorktreesContext is ListWorktrees bound to ctx, for a hook on a deadline: each listing is killed when ctx ends, and a listing ctx ended answers ctx's own error, never the older form's fallback.

func ParseWorktreeList added in v0.10.0

func ParseWorktreeList(out, sep string) []Worktree

ParseWorktreeList parses the porcelain output of `git worktree list`, whose attributes are separated by sep: "\x00" for the -z form, "\n" otherwise. A record opens at its `worktree <path>` attribute; an attribute before the first record, and one this reader does not know, is ignored. A `locked` or `prunable` reason is git's own text: the newline form C-quotes a reason holding a newline or a quote, and it is unquoted here (reasonOf).

Jump to

Keyboard shortcuts

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