vcs

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: Apache-2.0 Imports: 11 Imported by: 0 modules, 0 packages

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

Documentation

Overview

The guard that belongs to FORMWORK_GIT_ENV=inherit itself.

The hatch turns off the scrub, and with it the divergence guard env.go arms when the scrub removes something — that guard arbitrates between two candidate repositories, and under the hatch there is nothing to arbitrate about the variables the operator deliberately set. What was not measured until now is that turning the arbitration off ALSO turns off the only thing standing between formwork and a repository nobody named: with the hatch on and GIT_DIR naming an unrelated repository, `check --lane pre-commit --staged` run inside a repository with a staged violation reported "0 path(s) requested by --staged, 0 file(s) scanned" and exited 0.

THE POLICY. Under the hatch, formwork answers only about the repository -C names: the environment is honoured where it names a WORK TREE, that work tree IS -C, and -C is not a repository in its own right — and everything else refuses. The hatch means "honour the environment I set", not "answer about a repository I did not name".

THE THIRD CLAUSE WAS MISSING AND THE PROSE WAS NOT (#306). The first version of this paragraph already said the incoherent case must refuse — "-C naming one repository while the environment names another" — while the code asked only the first two questions, and GIT_WORK_TREE=<root> answers both of them whatever GIT_DIR names, because naming a work tree is what MOVES the top-level answer. Measured: `check --lane pre-commit` over a committed violation went from exit 1 to "1/1 rules passed" at exit 0.

STATING IT AS "-C AND THE ENVIRONMENT MUST AGREE ABOUT THE REPOSITORY" IS WHAT WENT WRONG, and the wording is kept here as a warning rather than dropped: it invites the question "is root a repository", which is a different question that git answers from an ANCESTOR. See below.

THE MOTIVATING LAYOUT SURVIVES IT UNTOUCHED, which is the whole justification and is measured rather than argued: TestGitEnvInheritHonoursADetachedWorkTree runs the bare-repo-plus-worktree layout through both exec sites, TestGitEnvInheritHonoursADetachedWorkTreeInsideAnotherRepository runs it one directory deeper, and TestGitEnvInheritHonoursADetachedWorkTreeHoweverRootIsSpelled runs the three spellings of -C this repository's history says break a path comparison.

THE EXEMPTION IS POSITIVE, AND THE FIRST VERSION OF IT WAS NOT. That version exempted a root git resolves no repository for — "the work tree holds no .git, so scrubbed there is nothing to disagree" — and it was wrong in both directions at once, each measured:

  • Too WIDE. GIT_DIR set ALONE, with -C a plain directory, is not a layout this hatch is for: with no work tree named, git makes the current directory the work tree, so the files come from -C while the index, the ignore rules and the changeset come from the other repository. Root names no repository, so that exemption waved it through — the whole defect, back under a different spelling.
  • Too NARROW. git's discovery ASCENDS, and a detached work tree routinely sits inside another repository (`~/work/wt` under a dotfiles repo at $HOME). The scrubbed run then answers from the ANCESTOR at exit 0, the two identities differ by construction, and the layout the hatch exists for was REFUSED — a working gate turned into an exit 2. env.go records that same premise as false where it argues the scrub; this is the other side of it.

So the exemption asks what the layout actually is: THE ENVIRONMENT NAMES A WORK TREE, AND IT IS -C. GIT_WORK_TREE is what names one — with GIT_DIR alone git falls back to the current directory, which is not the operator saying anything about a work tree — and git's own answer must then be root itself. Everything else refuses, including the incoherent case that started this: -C naming one repository while the environment names another. A vacuous pass over "0 paths scanned" is not an answer about the named repository either.

Package vcs is formwork's thin, fail-closed git seam: it turns a working tree plus a change selector (staged, or a commit range) into the set of changed paths a lane should scan (spec §8). Every git failure is an error — callers must never fall back to scanning the whole tree, which could let a gate pass by looking at the wrong file set.

Index

Constants

View Source
const (
	ModeBlob       = "100644"
	ModeExecutable = "100755"
	ModeSymlink    = "120000"
	ModeGitlink    = "160000"
)

INDEX ENTRY modes, as git records them. Those four are the whole set an index entry can carry. A TREE is a wider vocabulary — it also holds 040000 for a subtree — so this is deliberately not stated as "what git stores"; RangeModes below reads tree-side modes and would make that sentence false.

View Source
const (
	GitEnvVar = "FORMWORK_GIT_ENV"
)

GitEnvVar is the escape hatch for the scrub policy (scrubenv.go), and gitEnvInherit is the only value it accepts.

It is an environment variable rather than a flag because the problem it solves lives in the environment: the layout it exists for is expressed by exporting GIT_DIR and GIT_WORK_TREE, so the correction belongs beside them and needs no plumbing through every subcommand's flag set.

View Source
const IndexEnvVar = "GIT_INDEX_FILE"

IndexEnvVar is the variable that decides which index git answers from. It is deliberately NOT in scrubbedGitVars: git points it at a temporary index during a partial commit and then runs pre-commit, so removing it would make --staged judge a file set that is not the one being committed (env.go records the measurement, TestGitCallsPreserveGitIndexFile pins it).

This file is the other half of that decision. Preserving the variable is right for the CHANGESET question — "what is about to be committed" — and wrong for the two questions that are about what the REPOSITORY tracks: the PRUNE question, "what may the walk decline to read" (IgnoredUnder, CheckIgnored), and the TRACKED-SET question the scan-ignore-tracked check asks (TrackedUnder, vcs.go). #175 is that difference: with GIT_INDEX_FILE naming a well-formed empty index, git reports nothing tracked, `check-ignore` calls a COMMITTED file ignored, and `check` exits 0 over it.

Those three are every answer in this package that reads an index; the remaining GIT_INDEX_FILE readers (StagedPaths, StagedModes and their callers) are the changeset question and must keep the ambient answer. The two verdicts below run in OPPOSITE directions — keepAgreedPrunes intersects, unionTracked unions — because fail-closed follows the consumer, not the variable; each says why at its own doc.

Variables

View Source
var (
	// HooksPathQuestion is HooksPath's: where git will run hooks.
	HooksPathQuestion = ConfigEnvQuestion{What: "where git runs hooks", /* contains filtered or unexported fields */}
	// TopLevelQuestion is TopLevel's: which directory is the repository top
	// level, and how far below it the caller's root sits.
	TopLevelQuestion = ConfigEnvQuestion{What: "the repository top level", /* contains filtered or unexported fields */}
	// CommonDirQuestion is CommonDir's: the git directory every worktree shares,
	// which is where the hooks git runs by default live.
	CommonDirQuestion = ConfigEnvQuestion{What: "the git directory worktrees share", /* contains filtered or unexported fields */}
)

The questions, each paired with the exported function that asks it. Sharing the argv is what makes the pairing a fact rather than a comment.

View Source
var ErrGitEnv = errors.New("the git environment policy refused")

ErrGitEnv marks an error as gitEnvFor's own refusal rather than an answer git gave. errors.Is against it is the only way to tell the two apart, because those refusals carry git's failures inside their text.

IT EXISTS FOR CALLERS THAT EXEMPT A GIT FAILURE FROM BEING AN ERROR. Such an exemption is always argued from something git DID — internal/hooks' verify exempts the HooksPath call for a worktree git has already reported prunable, on the ground that git's refusal to answer for that directory IS the diagnosis it already made at exit 0. No such argument survives here: where this policy refuses, git was never run, so the exemption would render an engine error as a wiring problem.

A CALLER THAT DOES NOT DISTINGUISH NEEDS NOTHING. Every error gitEnvFor returns still reads exactly as it did — the tag adds a predicate, not a wrapper an operator sees — so the ordinary path, where a git failure is an error either way, is unchanged.

Functions

func CommonDir

func CommonDir(root string) (string, error)

CommonDir returns the absolute path of the git directory SHARED by every worktree of the repository containing root — the directory holding the hooks git falls back to when core.hooksPath is unset.

`--git-common-dir`, never `--git-dir`. In a linked worktree the latter names the per-worktree directory, whose `hooks/` does not exist, while the hooks git would actually run live under the common directory — measured on git 2.50.1, where `--git-common-dir` from a linked worktree answers the MAIN repository's absolute `.git`. A caller reading the per-worktree answer concludes the repository has no hooks of its own, which is the wrong answer in the dangerous direction: it is a decision about whether someone else's gate is about to be overridden.

The same IsAbs branch as HooksPath, for the same reason and with the same measurements behind it: from a subdirectory the answer is the relative `../.git`, from a linked worktree it is absolute. It absolutises through the same absJoin, so "the absolute path" above is a promise both arms keep rather than one the relative arm quietly broke.

func Diff

func Diff(root, rng string) (string, error)

Diff returns the raw unified diff for a range (e.g. "A..B" or "origin/main HEAD"), or an error on any git failure. root must be the repository top-level.

func EnsureNoInheritedHistoryEnv

func EnsureNoInheritedHistoryEnv() error

EnsureNoInheritedHistoryEnv refuses when any of the OBJECT-STORE family is set in the ambient environment (#213).

It exists for internal/rules/command, and it is deliberately a REFUSAL rather than the scrub this package applies to its own git calls (#176). The two callers are not in the same position. internal/vcs runs formwork's OWN git commands, so removing a variable it never meant to honour is free. `command` runs the OPERATOR's argv under the disclosed contract that the environment is inherited unchanged; deleting variables there would be formwork deciding on the tool's behalf, and would change what an already-working rule sees.

WHY A REFUSAL IS NEEDED AT ALL, given no comparison can see these. That is exactly why. scrubbedHistoryVars' own comment says no identity comparison can see them, so command's ensureRepositoryAgreement — an identity question — is structurally blind here. Measured before this existed: a rule `cmd: [git, cat-file, -e, SHA]` for a SHA present only in another repository FAILS at exit 1 with a clean environment and PASSES at exit 0 under an ambient GIT_ALTERNATE_OBJECT_DIRECTORIES naming that repository's object store. A pass earned over objects nobody named is the failure this refuses.

PRESENCE IS THE TRIGGER, not a comparison, because there is nothing to compare against — and that is affordable only because these are rare where formwork runs: gitEnvFor's measurement records that git does not set any of the six in this position. Where an operator does mean one — the receive-pack quarantine is the real case — GitEnvVar=inherit is the answer, the same hatch #176 and #177 use rather than a second one that would have to be discovered separately.

The error is tagged ErrGitEnv like every other refusal in this file, so a caller can tell policy from a git failure, and it NAMES the variable: an operator cannot cure what the message does not identify.

func EnsureTopLevel

func EnsureTopLevel(root string) error

EnsureTopLevel errors unless root resolves to the git repository top-level. File-set modes align git's repo-relative paths with the scan's root-relative paths only when root IS the top-level; enforcing it keeps the intersection honest instead of silently matching nothing (a fail-open hazard).

func GetConfig

func GetConfig(root, key string) (string, error)

GetConfig returns a git config value, or an error when the key is unset.

func GetConfigBool

func GetConfigBool(root, key string) (bool, error)

GetConfigBool returns a git config value normalized through git's own boolean parser (--type=bool prints "true" for yes/on/1/True and "false" for their negations), or an error when the key is unset. Callers gating behavior on a boolean key must use this, not GetConfig: --get returns the value AS SPELLED, so `ignorecase = yes` would compare unequal to "true" and silently flip the gate (#90 review — proven fail-open).

func GitEnvNotice

func GitEnvNotice() (string, error)

GitEnvNotice returns the line an operator must see when the hatch is in force, empty when it is not, and an error for a value gitEnvInheriting refuses.

IT RETURNS THE TEXT RATHER THAN PRINTING IT. The hatch is a fact about the environment, which this package owns; a stream to write it to is a fact about the command surface, which it does not — nothing else in this package writes to stdout or stderr, and giving it a first opinion about output would put a diagnostic in front of every library consumer.

The announcement is owed because the hatch turns a guard off from the environment, so an invocation running under it is indistinguishable, in a shell or a CI log, from one that is not.

THE TEXT CARVES OUT `command:` RULES, AND SO DOES gitEnvInheriting's REFUSAL ABOVE (#335). Both used to say the variables are removed from "every git command formwork runs", which was one command short of true from the day it was written: internal/rules/command builds its own exec.Command with cmd.Dir and no cmd.Env, so a `command:` rule shelling out to git keeps every one of them whatever this package decides. Measured against a repository whose only rule echoes its environment: with GIT_DIR and GIT_WORK_TREE set to that repository the tool printed both intact, and the rule was not refused.

THE SENTENCE WAS STALE IN THE OTHER DIRECTION TOO, and the earlier version of this paragraph said so while deferring the correction to "#177's fix", on the grounds that operator-facing text should not move ahead of the fix that decides what it says. #177 and #213 both closed COMPLETED on 2026-08-24, and what they added for a command rule is a REFUSAL rather than a scrub: ensureRepositoryAgreement asks vcs.EnsureNoInheritedHistoryEnv for the object-store six and vcs.CommonDir for the pointer three. Measured, again in that repository: an ambient GIT_ALTERNATE_OBJECT_DIRECTORIES and a GIT_DIR naming an unrelated repository each stop the rule at exit 2, naming the variable. So the old sentence described neither the behaviour it had nor the one that closed the hole, and the correction it waited for had landed.

WHAT EACH TEXT NOW SAYS is scoped to "the git commands formwork ITSELF runs" and then names the carve-out in the words docs/quickstart.md already uses to operators. TestTheHatchTextDoesNotClaimTheScrubReachesACommandRule pins both texts, and refuses both spellings of the universal so an edit cannot restore it by reflex.

func HooksPath

func HooksPath(root string) (string, error)

HooksPath returns the absolute directory git will actually run hooks from in the repository containing root.

It asks `rev-parse --git-path hooks` rather than reading core.hooksPath, because the question a caller has is "what will git DO", not "what string is configured". git resolves the key across every scope, applies its own default when nothing is set, and answers for the repository it lands in. There is no unset case to disambiguate: measured on git 2.50.1, a repository that never set core.hooksPath answers `.git/hooks` rather than failing.

THE filepath.IsAbs BRANCH IS LOAD-BEARING, not defensive. git's answer is sometimes relative and sometimes absolute, and the absolute case arrives without anyone configuring an absolute path — measured on git 2.50.1, inside a linked worktree with core.hooksPath unset the answer is the MAIN repository's absolute `.git/hooks`, while the main worktree returns the relative `.git/hooks`. filepath.Join(root, "/abs/path") concatenates the two into a directory that cannot exist, so a caller reading files there is looking somewhere that was never real.

`--path-format=absolute` would remove the branch and is deliberately not used: it needs git >= 2.31, and rev-parse ECHOES an option it does not recognise rather than failing, so on an older git the flag would come back as part of the answer instead of announcing the version floor.

Any git failure is an error (package contract): a caller must never fall back to a guessed directory, since certifying hooks at the wrong directory is the whole defect this exists to close.

The result is a path to OPEN, and it is absolute in BOTH arms — the relative one through absJoin, which is there because callers do compare these strings even though they cannot be compared as identities.

AN IDENTITY IS WHAT THIS IS NOT. Both arms normalise lexically only, so a `..` component traversing a symlink resolves differently here than the kernel resolves it for git. That is the hazard EnsureTopLevel documents in vcs.go at its filepath.Abs/EvalSymlinks note. Normalising makes the two arms agree on one spelling, which a diagnostic line needs; a caller that needs to know whether two of these name the same directory resolves symlinks itself, as internal/hooks does in resolvedKey.

func MovedRepository

func MovedRepository(removed []string) []string

MovedRepository keeps the names in removed that belong to the POINTER family — the only ones the identity probe can be about.

IT IS WHAT ARMS THAT PROBE, and the distinction is load-bearing rather than tidy: a history variable is scrubbed and then nothing more is owed, because git answers about the same repository under both environments and the comparison would be two identical answers at the cost of two forks. Naming one in the probe's refusal would also be false — that message says the variable "moves the repository git resolves", and this family does not.

The caller passes the names IT removed rather than asking for the family, so the arming decision is about this environment and not about the policy in the abstract.

func RangeModes

func RangeModes(root, rng string) (map[string]string, error)

RangeModes returns the mode each path changed by rng has AT THE RANGE'S END, keyed by path — the analogue of StagedModes for a commit range, and the same question asked of the tree that range is about.

It reads `diff --raw`, whose destination mode is exactly that, rather than `ls-tree` at an endpoint this package would have to derive. A range string is arbitrary — "A..B", "A...B", "origin/main HEAD", any of them with a legal `-- <pathspec>` tail — so parsing out "the endpoint" is a guess, and a wrong guess here silently reports the wrong mode. --raw hands the whole spec to git and reads the answer git resolved, exactly as RangePaths does.

The filter matches RangePaths, so the paths reported here are the paths reported there. Records are `:<srcmode> <dstmode> <srcsha> <dstsha> <status>\0<path>\0`, and a rename or copy carries TWO path fields — source then destination. The destination is what is keyed, because it is what --name-only reports and therefore what the caller is holding.

func RangePaths

func RangePaths(root, rng string) ([]string, error)

RangePaths returns the paths changed across a commit range (e.g. "A..B" or "origin/main HEAD"), added/copied/modified/renamed only. The range string is tokenized into separate git arguments by splitRange (rangespec.go), which honours shell-style quoting so a `-- <pathspec>` tail can name a path containing a space; an unclosed quote is an error, never a guess (#99). root must be the top-level.

Same split as StagedPaths: this is the readable-paths answer. See RangePathsAnyStatus for the classify-a-change one.

func RangePathsAnyStatus

func RangePathsAnyStatus(root, rng string) ([]string, error)

RangePathsAnyStatus is RangePaths without the status filter and with rename detection off — the range analogue of StagedPathsAnyStatus, widened both ways for that function's reasons.

func RepoConfig

func RepoConfig(root, key string) (string, bool, error)

RepoConfig answers a different question from GetConfig: not "what value does git resolve for key" but whether the CONFIG FILE BODY of this repository's local (or worktree) scope sets one. It returns the value, whether that scope sets it at all, and an error when git could not answer.

THAT IS NARROWER THAN "DID THIS REPOSITORY DECLARE ONE", and the difference is NOT closed here. `git config --local --get` defaults to --no-includes, so a key this repository declares in its own .git/config through `include.path` reads back unset from this function while git resolves and acts on it — measured on git 2.50.1 with core.hooksPath: `rev-parse --git-path hooks` answers the included value, this function answers unset. Folding --includes in would make this function report as "declared here" settings that scoping was chosen to exclude: an include may name a file anywhere on the machine. RepoConfigWithIncludes below is the other half of the answer instead — the two together tell a caller that a declaration exists AND that it arrives through an include, which is what internal/hooks needs to stop attributing the project's own wiring to something outside the repository (#173).

It exists because GetConfig's `--get` returns the EFFECTIVE value across system, global and local scope, so a machine-global core.hooksPath equal to formwork's own directory answers "yes, that value is in force" for a repository that never mentioned it. A caller deciding who OWNS a piece of wiring — this project, or a machine-wide default it must not silently take over — cannot ask that question with GetConfig at all.

THE THREE-VALUED ANSWER IS LOAD-BEARING. Unset is a normal answer here, not a fault: measured on git 2.50.1, `--get` on an unset key exits 1 while a repository git cannot read (unparseable config, no repository) exits 128, and only the second is a failure. A (string, error) signature has to spend one of its two states on unset, and either choice loses information the caller needs — an unset key is not an error, and the empty string is a value a repository can genuinely declare (`hooksPath =` is exit 0 with empty output, measured).

PRECONDITION: key must be a well-formed `section.name`. git spends exit 1 on an invalid key spelling too — `bogus`, `core.`, `core..x`, measured — so such a key arrives here indistinguishable from unset, and the last of those prints nothing on stderr, which rules out splitting the two on git's diagnostics.

SCOPE IS local PLUS worktree, and the second is not redundant. With extensions.worktreeConfig enabled the declaration lives in .git/config.worktree, where `--local --get` reports it unset and git nevertheless runs hooks from it (measured: `rev-parse --git-path hooks` answers the config.worktree value) — so local-only would call a repository's own wiring somebody else's. Worktree scope also WINS over local, which is why it is asked first.

The worktree read is GATED rather than unconditional, on a measurement: with the extension absent and more than one working tree registered, `git config --worktree --get` is `fatal: --worktree cannot be used with multiple working trees`, exit 128. Unconditional, that turns every ordinary repository that has run `git worktree add` into one whose config cannot be read. The gate is read from `--local` scope because that is where git honours it: a global extensions.worktreeConfig is ignored, measured — git answered `.git/hooks` with one set and a .git/config.worktree present.

func RepoConfigWithIncludes

func RepoConfigWithIncludes(root, key string) (bool, error)

RepoConfigWithIncludes asks RepoConfig's question with git's `include.path` directives FOLLOWED, and reports only whether the answer exists — never what it is.

THE PAIR IS THE POINT. `--local --get` defaults to --no-includes, so this function answering where RepoConfig does not means one thing: the key is declared through an include from this repository's own config. That two-answer test is all its caller needs, and it needs no policy about WHERE an include points, which is why the value is deliberately not returned — measured on git 2.50.1, an include reaches outside the repository through both spellings, an absolute path to a file elsewhere on the machine and a relative `../../up.cfg` out of .git. Returning the value would make this a reader of configuration formwork was never pointed at, and hand a caller a string to act on.

THE SCOPES MIRROR RepoConfig, worktree-first and worktree GATED, for that function's reasons: with more than one working tree registered and the extension absent, `--worktree` is `fatal: --worktree cannot be used with multiple working trees` (exit 128), and adding --includes does not change that — measured. The second scope is not redundant here either, and it is what a fix written to the local scope alone misses: an include inside .git/config.worktree reads back UNSET from `--local --includes --get` while git runs hooks from it (measured on git 2.50.1; `rev-parse --git-path hooks` answers the included value).

The gate itself reads WITHOUT includes, as RepoConfig's does, and that matches git rather than merely reusing a helper: measured on git 2.50.1, an extensions.worktreeConfig arriving through an include is not honoured at all — .git/config.worktree stayed unread and `rev-parse --git-path hooks` answered the default. Following includes for the gate would open a worktree scope git itself does not.

func ScrubEnviron

func ScrubEnviron(env []string) (kept, removed []string)

ScrubEnviron splits env into the entries a git command keeps and the sorted names of scrubbedGitVars it removed. It is the mechanism of the scrub, with no opinion about whether the caller is scrubbing: gitEnv applies it to a real run, and ensureHatchNamesRootsRepository (hatch.go) builds the comparison environment with it under the hatch, where the real run is not scrubbed at all.

The removed names are returned rather than discarded because a caller that removed something owes the operator the name of it — empty when none of them were set, which is the ordinary case and the one gitEnvFor uses to skip its probe entirely.

An entry with no "=" is not a variable this can be about, so it is kept rather than parsed further.

Names are compared EXACTLY, which is what the environment is on unix. A Windows port would need a case fold here instead: Windows resolves environment names case-insensitively, so `Git_Dir` would survive this loop and git would honour it anyway.

func ScrubbedGitVars

func ScrubbedGitVars() []string

ScrubbedGitVars returns the sorted names ScrubEnviron removes. It is what operator-facing text names — gitEnvInheriting's refusal and GitEnvNotice both print it — so a caller announcing the policy and a caller applying it cannot describe different sets.

The slice is a copy: the policy is not a caller's to edit.

func SetConfig

func SetConfig(root, key, val string) error

SetConfig sets a key in the local config of the repository git RESOLVES for root — which is not the same as "the repository at root".

GIT_DIR MOVES IT OUT FROM UNDER THIS FUNCTION. --local names the local scope of whatever repository git resolved, and GIT_DIR beats -C at that resolution. Measured on git 2.50.1: with GIT_DIR pointing at repository B, `git -C A config --local core.hooksPath …` writes to B and leaves A's config unset, so a caller that wrote shims into A reports a wiring it made somewhere else. That is #167.

--local IS EXPLICIT, and it is not only a spelling. Measured on git 2.50.1: with GIT_CONFIG set in the environment, a bare `git config <key> <val>` writes to THAT file and exits 0, leaving the repository's config untouched — a caller reports a wiring it never made. `--local` refuses the ambiguity instead (`error: only one config file at a time`, exit 129), which is the loud direction. It also pins the scope against a future git changing where an unqualified write lands: repo-local is the only scope this function may write, and saying so in the argv is cheaper than trusting a default.

func StagedModes

func StagedModes(root string, paths []string) (map[string]string, error)

StagedModes returns the mode git has recorded in the INDEX for each of paths, keyed by path. Paths with no index entry are absent from the result rather than defaulted, so a caller can tell "git says symlink" from "git says nothing" — those must not read alike in a fail-closed check.

It exists because the worktree and the index disagree, and under --staged it is the INDEX that is about to become a commit. A caller deciding whether a path is a file worth scanning cannot ask os.Lstat: replace a staged regular blob with a directory or a symlink on disk and the worktree answers for an entry that will never be committed (#158 review round 1).

A merge conflict lists one record per stage, and the fold below keeps the LAST non-pointer mode seen — so stages [100644, 100755] yield 100755, not the regular blob. What it guarantees is only that a pointer stage never displaces a file stage, which is the direction that matters. THAT BRANCH DOES NOT FIRE THROUGH TODAY'S ONLY CALLER, and the comment says so rather than implying otherwise: StagedPaths filters --diff-filter=ACMR, which excludes unmerged (U) entries, so a conflicted path never reaches this function. It is kept because this is an exported helper whose contract is "the mode git recorded", a second caller need not filter the same way, and the fold is the fail-closed direction — it can only keep a caller scanning, never excuse a path. It is untested for the same reason it is unreachable.

The pathspec is scoped to the caller's paths and terminated with `--`, so a path that begins with a dash cannot be read as an option. Empty input makes no git call: `ls-files` with an empty pathspec after `--` lists the whole index, which would be a silently much larger answer than was asked for.

root must be the repository top-level, checked here rather than assumed — like the other CHANGESET helpers (StagedPaths, RangePaths, TrackedPaths, RangeModes, Diff), whose output is intersected with repo-root-relative scan paths. Not like the ...Under family, which is root-relative by design and must stay that way; see TrackedUnder.

The production caller has already run StagedPaths, which checks it — but relying on that makes correctness depend on call ORDER in another package, and a future caller reaching this first would get subdir-relative keys that match no scan path and silently look like "git recorded nothing".

func StagedPaths

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

StagedPaths returns the repo-root-relative, slash-separated paths staged for commit (git index vs HEAD), added/copied/modified/renamed only — a deleted file cannot be scanned. root must be the repository top-level.

The ACMR filter answers "which paths can be read", which is the question a scanner asks. A caller that classifies a CHANGE rather than reading one wants StagedPathsAnyStatus instead: deleting a source file is a change, and the filter hides it (#147).

func StagedPathsAnyStatus

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

StagedPathsAnyStatus is StagedPaths without the status filter, and with rename detection off: every path git reports as differing between index and HEAD, deletions and type changes included, and for a rename BOTH the source and the destination.

Unfiltered is the fail-closed direction for its callers, and that is why the filter is absent rather than widened to a longer letter list. Every status this admits and ACMR excludes is a difference in the INDEX against HEAD — a deletion, a typechange, or an unmerged entry, which git reports even where the "ours" stage matches HEAD byte for byte. A caller deciding how much to check from this set can only be made more cautious by seeing more of them, never less, and that is the property this rests on.

--no-renames is the same argument reached by a different mechanism, and it is why dropping the filter alone was not enough. With detection on, git reports a rename as ONE path — the destination — so the source is not filtered out, it is never emitted: `git mv src/api.go docs/api.md` came back as docs/api.md alone, and the renamed-away .go file went unseen. Worse, detection is operator configuration (diff.renames), so identical bytes gave different answers on different machines; --no-renames pins the widening spelling.

func Submodules

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

Submodules lists the repository's registered submodule paths (gitlink entries, mode 160000), sorted, repo-relative and slash-separated. The guidance layer prefilters its check-ignore candidates through this list: check-ignore FATALS (exit 128, "Pathspec ... is in submodule") on any pathspec under a registered submodule — even one whose working tree was removed — while formwork's walk is submodule-OBLIVIOUS: it scans whatever plain files sit there and IgnoredUnder never prunes them, so for this engine a path under a submodule is simply not git-ignored. An unanswerable question (no repository, no git) is an error, never "no submodules".

func TopLevel

func TopLevel(root string) (top, prefix string, err error)

TopLevel reports the repository top level git resolves for root, and the prefix — the subdirectory git landed in, which is empty if and only if root IS that top level.

ASK GIT, IN GIT'S OWN FRAME. `--show-prefix` is empty if and only if the directory git ran in IS the top level. A subdirectory, a `..` that traverses a symlink, or GIT_WORK_TREE pointing elsewhere all come back with a non-empty prefix naming where git actually landed.

Both answers come from ONE invocation so they cannot disagree about which repository they describe — which is also why this is a function rather than two callers each asking their own half. `--show-toplevel` stays in the command because a bare repository fails it outright (exit 128) while `--show-prefix` alone reports "" for one and would wave it through.

It is the verdict EnsureTopLevel is built on, and it is exported because internal/hooks needs the same predicate for a different reason: install refuses a subdirectory root because git resolves core.hooksPath from the top level, not because a file-set intersection has to align. Sharing the invocation keeps one parse of git's answer; sharing EnsureTopLevel's message would have put "file-set modes require" in front of an operator running `hooks install`, which is a sentence about a command they did not type.

func TrackedPaths

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

TrackedPaths returns every file git tracks under root (git ls-files), repo-relative and forward-slashed. Whole-tree-invariant rules are evaluated over this tracked set under a --staged/--range scan, so a pre-commit hook never false-fails on an untracked working-tree file the developer is not committing (#4). root must be the repository top-level.

func TrackedUnder

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

TrackedUnder returns every git-tracked file at or below root, relative to root and forward-slashed. Unlike TrackedPaths it does not require root to be the repository top-level: git ls-files reports paths relative to its cwd, which is exactly the root-relative frame lint's scan uses (and keeps the check usable if lint ever runs over a corpus that is a repo subdir, #89). git -C resolves to the NEAREST ancestor repository, so a root that is not itself a repo answers for the repo that contains it — truthfully empty when nothing is tracked under root.

The output is read with -z (NUL-terminated): default core.quotePath C-quotes any path carrying a non-ASCII or control byte, and a line-split parser would return the quoted spelling — a string that can never match a scan path, which for this function's caller means a silently passed bypass (#90 review). --stage exposes the mode so submodule gitlinks (160000) are excluded — they are pointers, not files of this repo — and merge-conflict stage duplicates collapse via the dedup.

Index semantics: a staged-but-uncommitted file is tracked. Any git failure is an error; callers must fail, never fall back to "nothing tracked" (package contract).

WHICH index, though, is decided by GIT_INDEX_FILE — the #175 defect, and this is its third seam alongside IgnoredUnder and CheckIgnored. Under an index that tracks less than the repository's, a committed file drops out of this answer and scan-ignore-tracked (#90) reports clean over it. Where the variable is set, the question is asked again with it removed and the two answers are UNIONED (unionTracked, indexguard.go) — not intersected as the prune side is; see there for why the fail-closed direction is opposite. Unset, nothing is compared and no extra git call is made.

Types

type ConfigEnvEffect

type ConfigEnvEffect struct {
	// Question is the What of the question that was asked.
	Question string
	// Changed reports that the two runs disagreed.
	Changed bool
	// Ambient is git's answer with the environment MeasureConfigEnv was given —
	// the caller's, less env.go's scrubbedGitVars, because the ambient run is
	// built from gitEnv() so that both runs differ in the config family alone.
	// Under FORMWORK_GIT_ENV=inherit gitEnv removes nothing, and it is then the
	// caller's environment unchanged.
	Ambient string
	// Scrubbed is git's answer with the GIT_CONFIG family removed.
	Scrubbed string
	// Removed names the variables the probe actually removed — the ones both
	// present in the environment and inside the family. Empty when none were set,
	// which is ORDINARILY the state where Changed cannot be true: with nothing
	// removed the two runs are the same invocation under the same environment.
	// It is not a guarantee, and an earlier version of this sentence stated it as
	// one — git answering the same question differently across two consecutive
	// forks reaches empty-and-Changed, and internal/hooks' configEnvLine has a
	// live branch for exactly that state rather than a message naming no variable.
	Removed []string
}

ConfigEnvEffect is what one question answered twice reports.

Ambient and Scrubbed are for the operator to READ, not for a caller to compare — Changed is the comparison, made on git's exit status as well as its output, and a run that failed renders here as its error rather than as an empty answer. Comparing the display strings instead would call two different failures the same answer.

func MeasureConfigEnv

func MeasureConfigEnv(root string, q ConfigEnvQuestion) (ConfigEnvEffect, error)

MeasureConfigEnv asks git one question twice — once with the environment as it is, once with the GIT_CONFIG family removed — and reports whether the answers differ.

IT CHANGES NOTHING ABOUT A REAL RUN. The removal lives inside the second invocation's own environment; os.Environ is not modified, no other git command this package runs is affected, and a caller that ignores the result behaves exactly as before. That is why FORMWORK_GIT_ENV=inherit does not turn this off: the hatch exists so an operator can stop env.go REMOVING variables from the commands formwork runs, and nothing here removes one from a command anybody asked for.

AN ERROR MEANS THE COMPARISON WAS NOT PERFORMED, which is not the same as "nothing changed" and must not be read as one: both runs failing is the state where git could not answer at all. Where the two runs fail DIFFERENTLY — one exit status, one answer — that is a difference, and it is reported as one; an environment the answer depends on for whether git works at all is exactly what a caller is asking about.

type ConfigEnvQuestion

type ConfigEnvQuestion struct {
	// What names the question in git's terms, for a message an operator reads.
	What string
	// contains filtered or unexported fields
}

ConfigEnvQuestion is one question this package asks git, in the form a caller names when it wants to know whether the environment moved the answer.

THE ARGV IS UNEXPORTED AND SHARED WITH THE FUNCTION THAT ASKS IT. A caller outside this package cannot spell a question of its own, which keeps two things true: a probe cannot drift into asking about something adjacent to what the caller actually reads, and the questions stay enumerable here rather than scattered across consumers. The zero value asks nothing and MeasureConfigEnv refuses it — a question with no argv would run bare `git` twice and report "nothing changed" for every environment there is.

type IgnoredPath

type IgnoredPath struct {
	Path    string
	Dir     bool
	Source  string // the ignore file that decided it, e.g. ".gitignore"
	Line    int    // 1-based line number within Source
	Pattern string // the pattern on that line
}

IgnoredPath is one path git ignores, with the ignore rule responsible for it. Path is repo-relative and slash-separated with NO trailing slash; Dir says whether it names a directory, which the walk may prune without descending.

func CheckIgnored

func CheckIgnored(root string, paths []string) ([]IgnoredPath, error)

CheckIgnored asks git whether it would ignore each of the given paths — which need not exist. IgnoredUnder snapshots the paths that exist in the working tree, so it can never answer for a file about to be written; check-ignore evaluates the ignore patterns for any pathname, closing that gap (#122's ghost frame), and one --stdin call serves the whole batch. A path absent from the result is the "not ignored" verdict. The tracked carve-out IgnoredUnder leans on holds here for the same reason: no --no-index, so git refuses to call a tracked path ignored — subject to the same #175 qualification IgnoredUnder carries, and closed the same way: where GIT_INDEX_FILE moves the index, the answer is the paths BOTH indexes call ignored. There is no ls-files step to repeat here, because the candidates come from the caller rather than from a listing. An unanswerable question (no repository, no git) is an error, never "not ignored" (package contract).

func IgnoredUnder

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

IgnoredUnder returns every path git ignores at or below root, sorted by Path, each carrying the ignore rule responsible for it. Like TrackedUnder it does not require root to be the repository top-level: git reports paths relative to its cwd, which is the frame the scan's root-relative paths use.

WHY THIS IS THE IGNORED SET AND NOT THE UNTRACKED SET. An untracked file is still compiled by the toolchain and is usually someone's work in progress, so skipping it would be a rule bypass on the file most likely to matter (#80, #54). An IGNORED file is different in kind: git will not accept it without an edit to .gitignore or an explicit `add -f`, so no rule can be evading anything by declining to read it. This function draws exactly that line and no wider one.

TWO CALLS, AND THE SECOND IS THE SAFETY PROPERTY.

  1. `ls-files --others --ignored --exclude-standard --directory` proposes candidates. --directory collapses a wholly-untracked directory to a single entry so a caller can prune the subtree without enumerating it — the whole reason this is affordable on a tree carrying many ignored checkouts.
  2. `check-ignore` confirms each candidate, and only confirmed paths are returned.

The confirmation is not belt-and-braces; step 1 over-reports in two ways that would each be a silent coverage hole:

  • --directory collapses a directory that is merely untracked-throughout, not ignored. A tree holding only a/b/ignored/ reports a/ and a/b/ as well, and pruning those would skip paths no .gitignore line matches.
  • check-ignore WITHOUT --no-index refuses to call a tracked path ignored. That is git's own rule, and leaning on it means a force-added file under an ignored directory cannot be pruned by any bug in this package. Never add --no-index here: it turns the guarantee off.

Both git calls are -z. With default core.quotePath git C-quotes any path holding a non-ASCII or control byte, and a quoted spelling can never match a scan path — the same silent-miss #96 found in the --staged/--range listing.

BOTH ALSO READ AN INDEX, AND GIT_INDEX_FILE MOVES IT (#175). ls-files decides the collapse from the index and check-ignore decides the tracked carve-out from it, so a moved index breaks the guarantee at BOTH steps — which is why the cross-check runs the whole pair again rather than only the confirmation. The prune set is then the paths both indexes call ignored (keepAgreedPrunes, indexguard.go), and it is skipped entirely — no extra git calls — when GIT_INDEX_FILE is unset.

A repo where nothing is ignored is not an error: check-ignore exits 1 to say "none of these", which is an answer. Every other failure is returned, and callers must not read an error as "nothing is ignored" (package contract) — including a failure of the cross-check's own run.

func (IgnoredPath) Rule

func (p IgnoredPath) Rule() string

Rule renders the deciding ignore line in the shape git's own `check-ignore -v` prints it ("<file>:<line>:<pattern>"), so a reader can paste it straight back at git. Every consumer that attributes a prune — the census, rules-for — uses this one spelling.

type Worktree

type Worktree struct {
	// Path is the worktree's root directory.
	Path string
	// Bare marks a repository with no working tree.
	Bare bool
	// Prunable marks an entry git would drop on `git worktree prune`. git still
	// LISTS it, at exit 0 — it is not the same thing as a worktree that exists
	// but is missing files.
	//
	// IT IS A VERDICT ON THE REGISTRATION, NOT ON THE DIRECTORY, and a caller
	// that reads it as "the directory is gone" is wrong in both directions.
	// Measured on git 2.50.1: deleting a worktree's `.git` file makes the entry
	// prunable while every file in it stays where it was; moving the whole
	// worktree makes it prunable while the worktree keeps working — git lists
	// the OLD path, and a commit in the new location succeeds.
	Prunable bool
	// PrunableReason is git's own words for why, empty when git gave none.
	//
	// Carried rather than discarded because the states above have opposite
	// cures — prune deregisters a worktree that `git worktree repair` would
	// fix — and a caller that has only the flag has to invent a reason.
	PrunableReason string
	// Locked marks an entry the operator locked with `git worktree lock`.
	Locked bool
}

Worktree is one entry of `git worktree list`, reduced to the path plus the three states that decide whether it is a hook site at all.

Path is the path exactly as git reported it — no cleaning, no case folding, no separator rewriting — so it can be compared against and joined with git's other answers without a second normalisation disagreeing with the first.

func Worktrees

func Worktrees(root string) ([]Worktree, error)

Worktrees returns every worktree git reports for the repository containing root, in git's own order. It does not require root to be the top level: the question is about the repository, and a caller diagnosing a subdirectory root still needs the answer.

Any git failure is an error, and so is any record that does not parse — see parseWorktrees.

Directories

Path Synopsis
Package gitseal seals a test binary's process environment against the developer's ambient git configuration.
Package gitseal seals a test binary's process environment against the developer's ambient git configuration.

Jump to

Keyboard shortcuts

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