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
- Variables
- func BuiltinMergeDriver() string
- func CheckIgnored(root string, candidates []string) map[string]struct{}
- func CheckoutRoot(cwd, store string) (string, error)
- func CommandLineConfig() []string
- func DefaultBranchRoots(root string) ([]string, error)
- func DefaultRef(root string) string
- func EachAsStoredContext(ctx context.Context, root string, maxLine int, each func(line string), ...) error
- func EachWorktree(root string, fn func(Worktree)) error
- func EmptyTree(root string) (string, error)
- func ExecPins() []string
- func FilterOverrides(root string) ([]string, error)
- func FilterRootsIgnored() string
- func FiltersSwitchedOn(root string) (on bool, ignored string)
- func GitAtLeast(major, minor int) (bool, string)
- func GitfileTarget(dir string) (string, bool)
- func Gitlinks(root string) ([]string, error)
- func HomeInsideWorkingTree(home string) string
- func HooksPaths(root string) ([]string, error)
- func IgnoredUnder(root, rel string) ([]string, error)
- func InRepo(root string) bool
- func IsAncestor(root, ancestor, descendant string) (bool, error)
- func IsFullSHA(s string) bool
- func IsIgnored(root, path string) bool
- func IsNullOID(s string) bool
- func IsolatedEnv() []string
- func LocalGit(dir string, args ...string) (string, error)
- func MergeDriverOverrides(root string) ([]string, error)
- func Net(dir string, args ...string) (string, error)
- func NetEach(dir string, maxLine int, each func(line string), args ...string) error
- func NetInput(dir, stdin string, args ...string) (string, error)
- func ProveOperandDir(operand string) error
- func RefIsSafe(ref string) bool
- func RemoteHeadBranch(root, remote string) (string, error)
- func RepoShaped(root string) bool
- func RepoShapedRoot(root string) string
- func RequireFullHistory(root string) error
- func ResolveCommit(root, ref string) (string, error)
- func ResolveRangeBase(root, raw string) (string, bool, error)
- func RevParseAbsPath(dir, flag string) (string, error)
- func RootCommit(root string) string
- func RootCommitContext(ctx context.Context, root string) (string, error)
- func Run(root string, args ...string) (string, error)
- func RunCapped(root string, maxBytes int, args ...string) (string, error)
- func RunCappedAsStored(root string, maxBytes int, args ...string) (string, error)
- func RunCappedBytes(root string, maxBytes int, args ...string) ([]byte, error)
- func RunCappedBytesAsStoredContext(ctx context.Context, root, stdin string, maxBytes int, args ...string) ([]byte, error)
- func RunCappedExitOne(root string, maxBytes int, args ...string) ([]byte, bool, error)
- func RunCappedExitOneAsStored(root string, maxBytes int, args ...string) ([]byte, bool, error)
- func RunLimited(root string, maxBytes int, args ...string) (string, error)
- func RunLimitedContext(ctx context.Context, root string, maxBytes int, args ...string) (string, error)
- func RunWithIndex(root, index string, maxBytes int, args ...string) ([]byte, error)
- func ScrubURLCredentials(text string) string
- func ScrubURLUserinfo(s string) string
- func ScrubbedEnv() []string
- func ShortRef(ref string) string
- func SwapAccountHomeForTest(fn func() (string, error)) (restore func())
- func SwapGitVersionForTest(src func() (string, error)) (restore func())
- func Toplevel(dir string) (string, error)
- func ToplevelContext(ctx context.Context, dir string) (string, error)
- func ToplevelShaped(dir, top string) bool
- func TrackedDefaultBranch(root, remote string) string
- func TrackedFiles(root string) ([]string, error)
- func TreePathTypes(root, commit string, paths []string) ([]string, error)
- func WorkingTreeCommand(root string, args ...string) *exec.Cmd
- func WorkingTreeCommitCommand(ctx context.Context, root string, args ...string) *exec.Cmd
- type ArchiveEntry
- type BatchObject
- type ConfigEntry
- type OperandError
- type StatusEntry
- type StatusOptions
- type Worktree
Constants ¶
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.
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 ¶
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.
var ErrGitTimedOut = errors.New("git did not answer in time")
ErrGitTimedOut is RunLimitedContext's answer for a git whose output was still open when the wait for it ran out (exec.ErrWaitDelay), on a retry as well as the first time. Nothing cancelled it; git may well have answered. On a heavily loaded machine the copy of git's output can miss the runner's WaitDelay after git exits, and a caller that read that error as git's answer turned it into "not a repository" or "no root commit" (iss-2610100846469473). A caller that must tell "git said no" from "git did not answer" checks for it with errors.Is; the exec error it came from stays wrapped.
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.
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.
var ErrShallowCheckout = errors.New("shallow checkout")
ErrShallowCheckout is RequireFullHistory's refusal: the checkout is shallow, so history past the graft is absent.
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.
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.
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 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 ¶
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
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 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 DefaultBranchRoots ¶ added in v0.15.1
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) and no graft file (noGraftFile), so neither 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
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.
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
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
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.
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 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 FilterOverrides ¶ added in v0.13.4
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
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
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
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 ¶ added in v0.14.1
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.
func HomeInsideWorkingTree ¶ added in v0.14.0
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
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
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 ¶
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
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.
func IsFullSHA ¶ added in v0.10.0
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 ¶
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
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 LocalGit ¶ added in v0.15.0
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
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). 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 Net ¶ added in v0.14.2
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.
func NetEach ¶ added in v0.15.1
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 NetInput ¶ added in v0.15.1
NetInput is Net with stdin fed to the command: 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.
func ProveOperandDir ¶ added in v0.11.1
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
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
RemoteHeadBranch asks the remote which branch is its default and returns the bare branch name: `git ls-remote --symref <remote> HEAD`, through Net (a network call, its environment scrubbed and its time bounded), read for the `ref: refs/heads/<branch>\tHEAD` line the remote advertises.
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 RepoShaped ¶ added in v0.6.7
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
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
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
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
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
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 RootCommit ¶ added in v0.6.9
RootCommit returns the repository's canonical (first) root-commit SHA, or "" when it cannot be derived — git absent, not a repository, no commits. It is total: a caller keying a store or a marker on the repository's identity gets "" rather than an error, and decides for itself what an unidentified repository means. 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.
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
RootCommitContext is RootCommit bound to ctx: the same answer, total in the same way, except that git not answering in time is returned as its own error — a context that ends before git answers (wrapped, with git killed), or a git whose output missed the runner's WaitDelay twice (ErrGitTimedOut) — so a caller can tell "this repository has no root commit" from "git did not answer in time".
func Run ¶
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 ¶
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
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
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. A WaitDelay miss over a git that answered is asked once more, as RunLimitedContext asks it, and a second miss is ErrGitTimedOut.
func RunCappedExitOne ¶ added in v0.14.0
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
RunCappedExitOneAsStored is RunCappedExitOne reading history as stored (asStored).
func RunLimited ¶
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.
Under a context that can end, the WaitDelay that bounds a killed git's pipes also starts when git exits on its own (contextWaitDelay), so on a loaded machine a git that answered can still come back as exec.ErrWaitDelay, its output not yet copied. That miss is asked once more; a second miss is returned as ErrGitTimedOut, never as git's answer.
func RunWithIndex ¶ added in v0.13.4
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`). Output past maxBytes is an error, never a truncated answer: a cut-short patch is a wrong one.
func ScrubURLCredentials ¶ added in v0.15.0
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
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 ShortRef ¶ added in v0.11.1
ShortRef renders a full ref the way a person names it: origin/main for a remote-tracking ref, main for a local branch.
func SwapAccountHomeForTest ¶ added in v0.14.0
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
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 Toplevel ¶ added in v0.11.1
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
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
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
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.
func TrackedFiles ¶
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 TreePathTypes ¶ added in v0.15.1
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.52); both are "commit" here, never an error. 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.
func WorkingTreeCommand ¶ added in v0.14.1
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.
func WorkingTreeCommitCommand ¶ added in v0.14.1
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 (loop.boundedGit 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.
Types ¶
type ArchiveEntry ¶ added in v0.11.1
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
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.
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
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 OperandError ¶ added in v0.11.1
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.
--ignore-submodules=dirty 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 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
}
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
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 ParseWorktreeList ¶ added in v0.10.0
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 use (locked, prunable, detached), is ignored.