scan

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 12 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

restrict.go — the file-set intersection: which walked files are the ones a caller's path list named, including where the two spell the same filename with different bytes (#98). Split from scan.go, which the 750-line vendor cap bounds; same package.

Package scan walks a repository tree once and serves cached file content to rule checkers. It knows nothing about rules (spec §4).

skipdirs.go — the built-in skip set and the predicates that answer "would the walk have descended here?". Split from scan.go, which the 750-line vendor cap bounds; same package, same precedent as restrict.go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuiltinSkipDirs

func BuiltinSkipDirs() []string

BuiltinSkipDirs returns the engine-level skip set, sorted. Exported so `formwork lint`'s escape-hatch census can NAME it rather than restate it in prose (#56): a hand-written "directories named .git, .formwork" drifts the moment this set changes, and it is the one exemption channel no rule can declare, so the census is the only place it is auditable at all.

It reports the NAMES only, and since #268 the DEPTH differs by name — a caller rendering these into prose owns saying so. Widening the strings themselves would break the callers that compare them to a path segment.

func IgnoredBy

func IgnoredBy(path string, globs []string) (string, bool)

IgnoredBy reports whether a scan.ignore glob hides path from the walk, and which one, attributing exactly as WalkIgnoring does: the walk prunes at the SHALLOWEST matching ancestor, testing each level in config order — so this loop is level-outer (shallowest first), glob-inner. A glob-outer loop names a different (deeper) glob than the walk whenever overlapping globs match different ancestor depths (#95 review). Built-in skips are deliberately not consulted here (lint's fallback excludes them with its own guard); consumers needing full walk attribution use NotScannedBy. doublestar cannot case-fold; callers owning case-insensitive concerns handle them above this.

func ScopeRootedUnderSkipDir

func ScopeRootedUnderSkipDir(globs []string) bool

ScopeRootedUnderSkipDir reports whether EVERY glob is rooted at a literal first segment the engine never scans — so no path the walk can produce will ever match, whatever else is in the repository.

A literal LEADING segment is the one position where both members of the skip set prune alike (`.git` prunes anywhere, `.formwork` at the root), so testing the set directly here is exact rather than approximate.

One-sided by construction: it decides only on a literal leading segment, so `**/.git/**` (which also can never match) is not detected. That is deliberate. This exists to explain an already-reported empty scope, and a wrong "the skip set is why" on a rule with an ordinary broken glob would send the reader somewhere there is nothing to find. `**/.formwork/**` is NOT in that category since #268 — it matches every ported corpus's rules — and reporting it would be the opposite error.

func UnderBuiltinSkip

func UnderBuiltinSkip(path string) bool

UnderBuiltinSkip reports whether any component of the slash-separated, root-relative path is a built-in skip directory — by the same predicate, at the same depths, that Walk prunes with before scan.ignore is consulted. Callers reasoning about paths the walk never enumerated (e.g. lint's tracked-path cross-check, #90) use this to avoid attributing a built-in skip to an operator glob.

Each ANCESTOR PREFIX is tested, not each bare segment: `.formwork` prunes only at the walk root since #268, and a bare segment carries no depth. A nested corpus's `.formwork` is scanned content, and reporting it skipped here would excuse it from the very check that asks whether an operator glob is hiding tracked files.

func UnderBuiltinSkipDir

func UnderBuiltinSkipDir(path string) bool

UnderBuiltinSkipDir reports whether an ANCESTOR of path is a built-in skip directory — the question a caller reasoning about a FILE path must ask, and the one UnderBuiltinSkip above answers too loosely.

The leaf is deliberately excluded. Walk consults the skip set in its d.IsDir() branch and again in the symlink refusal (where the answer is to skip a linked .git/.formwork rather than refuse it) — never in its REGULAR-FILE branch, so a regular file named .git or .formwork is scanned and enforced on like any other file; calling it "under a built-in skip" contradicts the walk's own verdict. NotScannedBy has written the `!leaf` guard for exactly this reason since #119, and a caller that reached for UnderBuiltinSkip instead reintroduced the contradiction as a fail-open: a staged .formwork FILE the walk would have failed on was excused from #158's accounting.

Both predicates are kept because they answer different questions. Lint's tracked-path cross-check (#90) asks about paths it has not classified as files or directories, where the looser test is the conservative one; this asks about a path already known to be a file in git's index or a commit.

Types

type File

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

File is one regular file under the scanned root. Content is read at most once and cached; File is safe for concurrent use.

func NewMemFile

func NewMemFile(relPath string, content []byte) *File

NewMemFile returns an in-memory File. For tests and fixture runners.

func (*File) Content

func (f *File) Content() ([]byte, error)

Content returns the file bytes, reading from disk on first call only.

func (*File) Lines

func (f *File) Lines() ([]string, error)

Lines returns the file content split into lines, without a trailing empty line for newline-terminated files.

The returned strings ALIAS the cached content — they are not copies. This is the whole point: content is already retained for the run, and materialising `string(content)` to split made every file cost its own size a second time. Measured over a 10k-file tree, that took a file from 1.06x its size (Content alone) to 2.55x, and applied again for every preprocessor variant, which is the single largest term in the engine's steady-state footprint (#66).

THE INVARIANT THIS DEPENDS ON: cached content is never mutated after it is read. Content() reads once under contentOnce and no caller writes through the returned slice; every preprocess.Transform copies its input before modifying it (`out := append([]byte(nil), src...)`) rather than editing in place, and Variant stores the transform's OUTPUT as a separate File with its own content. A transform that ever mutated its argument would corrupt the shared cache for every other rule regardless of this aliasing — but it would also silently change strings already handed out here, so the two tests in lines_alias_test.go pin the invariant rather than leaving it to a comment.

func (*File) Path

func (f *File) Path() string

Path returns the repo-relative, slash-separated path.

func (*File) Variant

func (f *File) Variant(name string) (*File, error)

Variant returns a view of the file whose content is transformed by the named preprocessor, computed lazily and cached per (file, variant) — spec §6. "raw" and "" return the file itself. Variants share the file's path, so findings against a variant report original positions (transforms are line-preserving).

type FileSet

type FileSet struct {
	Root string
	// Repo is the corpus's own tree — where .formwork lives — when that is a
	// DIFFERENT directory from Root. Empty means "the same as Root", which
	// is what they are for every walk of a repository; a fixture replay is
	// the plane where they differ (#28).
	Repo string
	// Fixture is true when this walk is of a FIXTURE tree rather than the
	// live repository — derived, never set by hand: it is exactly the case
	// where the corpus root and the tree under evaluation differ (#28).
	Fixture bool
	Files   []*File
	// Ignored is every path a scan.ignore glob removed from this walk,
	// sorted by Path. Empty unless the walk ran with ignore globs.
	Ignored []Ignored
}

FileSet is every scannable file under Root, sorted by Path.

func Walk

func Walk(root string) (*FileSet, error)

Walk builds the FileSet for root, skipping .git and .formwork — by name, in either spelling, a real directory or a symlink to one — and skipping non-regular files. Two shapes of symlink are REFUSED (returned as an error) rather than skipped: one whose own name reads as source to a toolchain, and one leading to a directory outside the tree or to something the walk cannot look at. Each would otherwise be a silent skip while the toolchain reads straight through it (spec §11: never skip silently; #54, #143 rows 2-3). The root itself is resolved first, so a symlinked root scans the tree it names instead of enumerating nothing (#143 row 1), and a root that is not a directory at all is refused. Any I/O error also fails the walk.

Walk applies no operator ignores; every pre-scan.ignore caller and test goes through here unchanged.

func WalkIgnoring

func WalkIgnoring(root string, ignore []string) (*FileSet, error)

WalkIgnoring is Walk plus scan.ignore: any entry whose repo-relative slash path matches an ignore glob is pruned and recorded on FileSet.Ignored. Globs are pre-validated by config (exit 2 at load), so Match errors are impossible here — same idiom as config.matchAny. Ordering is deliberate: skipDirs, then ignore, then the symlink refusals — an ignored path is the operator's declared not-ours, so neither #54's refusal nor the directory-symlink refusal fires inside it, and ignore_test.go and symlink_test.go pin each direction of that trade. A pruned directory is never descended, so its contents are neither scanned nor counted.

func WalkWith

func WalkWith(root string, opts Opts) (*FileSet, error)

WalkWith is WalkIgnoring plus the gitignore prune (spec §4). Ordering is deliberate and pinned by tests: the root is resolved (resolveRoot, #143 row 1) before anything is enumerated, and then per entry the built-in skip, then scan.ignore, then gitignore, then the symlink refusals — #54's source-named one and #143 row 2's subtree-hiding one, in that order. All three prune channels precede the refusals for the same reason — a pruned path is out of scope, and the refusal exists to make a bypass of IN-SCOPE source loud, not to police trees nobody gates. builtinSkipDir is asked twice for that reason: once for a real directory and again inside the subtree-hiding refusal, which is the only branch a .git or .formwork spelled as a SYMLINK reaches. Both consults pass the ROOT-RELATIVE path rather than the entry's bare name, because the skip is depth-sensitive for .formwork (#268) — see builtinSkipDir in skipdirs.go.

WHY GITIGNORE PRUNING IS NOT THE FAIL-OPEN CHANGE #80 REJECTS. #80 is right that skipping UNTRACKED files would be a rule bypass: an untracked .go is still compiled, and it is the file most likely to be work in progress. This prunes the IGNORED set instead, which git will not accept into a commit without an edit to .gitignore or an explicit `add -f` — and the caller's seam confirms every path with git itself, which refuses to call a tracked path ignored. So an untracked-but-not-ignored file stays fully in scope, and a force-added file under an ignored directory stays fully in scope.

func (*FileSet) Produced

func (fs *FileSet) Produced(p string) bool

Produced reports whether this FileSet is the scan OF THE FILE the caller's path names — including where the walk and the caller spell that one filename with different bytes. It is the fold above asked as a question, for the caller whose obligation Restrict's own doc names.

It exists because #98's fix stopped at Restrict. internal/cli's requestedButAbsent, which must leave no requested path unaccounted for, rebuilds `present` as an exact string map over the restricted set; git hands it the NFC spelling and the walk carries the NFD one, so a file the fold DID produce read as unproduced. Measured on macOS/APFS at 887acefa with the real binary: a clean NFD-named file exits 2 under --staged and --range with "present in the working tree but not produced by the scan under this spelling" — both halves of that sentence false — with no cure line, and a real `git commit` through formwork's own installed pre-commit hook is refused (#308).

THE ORACLE IS THE FILESYSTEM, exactly as in foldSpellings: same device and inode is identity, not similarity, and no unicode table or dependency is involved. The narrowing is the same too, and for the same reasons — only non-ASCII spellings, on EITHER side, are ever folded, so no ASCII verdict can move and a pruned hard link cannot be answered for by a walked file that merely shares its inode (#333).

A path this FileSet does not carry under ANY spelling answers false, and that includes one git named that the worktree no longer has. That answer is what #158's accounting reads to refuse at exit 2, so guessing true here would turn a loud refusal into the false pass #158 closed.

LSTAT, NOT STAT, for the requested spelling: a symlink is judged by the link and never by its target, so a symlink pointing AT a walked file is not that file. requestedButAbsent Lstats for the same reason and says so. On the walked side the choice is not load-bearing — WalkWith appends only regular files, where the two agree.

Cost is one pass over Files at most, and for an ASCII path no stat call at all — it returns at the gate. The fold's stats are reached only where a non-ASCII spelling went genuinely unmatched.

func (*FileSet) Restrict

func (fs *FileSet) Restrict(allow map[string]bool) *FileSet

Restrict returns a new FileSet containing only files whose path is in allow (slash-separated, root-relative). Order is preserved. Used by file-set modes (--staged/--range) to scan only the changed files.

Matching is by exact path, with one narrow exception the FILESYSTEM decides rather than this package: where a caller's path and a walked path are two spellings of one filename — the macOS NFC/NFD divergence of #98 — the file is matched by identity. foldSpellings below owns that, and owns why it cannot widen anything else.

A path in allow that this FileSet does not carry is simply absent from the result, and that silence is NOT a feature — it is how a file staged and then deleted from the worktree passed every rule at exit 0 (#158). This function cannot do better: it is handed a set of paths with no record of why any of them is missing, and Ignored is not carried onto the result because the restricted set is the engine's input, not a census. Accounting for the difference is therefore the CALLER's obligation; internal/cli's requestedButAbsent is where it is discharged, and its caller exits 2 rather than let an unproduced path read as a checked one.

type GitIgnored

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

GitIgnored is a set of paths git confirmed ignored, keyed for O(1) lookup during the walk. Callers build it from their git seam; this package holds no git dependency of its own, so the walk stays testable without a repository and the seam stays fail-closed in one place rather than two.

func NewGitIgnored

func NewGitIgnored() *GitIgnored

NewGitIgnored returns an empty prune set.

func (*GitIgnored) Add

func (g *GitIgnored) Add(path string, dir bool, rule string)

Add records one confirmed-ignored path. rule is the ignore line responsible for it, carried through to the census so a prune can always be traced to the declaration that caused it.

func (*GitIgnored) Len

func (g *GitIgnored) Len() int

Len is the number of recorded paths.

func (*GitIgnored) Lookup

func (g *GitIgnored) Lookup(rel string, dir bool) (string, bool)

Lookup reports the responsible rule for rel in the given frame (dir or file), if this set covers it — the exported read the guidance layer's ghost overlay uses to pick up existing-ancestor collapse levels. A nil set covers nothing.

type Ignored

type Ignored struct {
	Path string // repo-relative, slash-separated
	Dir  bool
	Glob string // the scan.ignore glob that matched ("" for a gitignore prune)
	By   Source
	Rule string // gitignore only: "<file>:<line>:<pattern>" that decided it
}

Ignored is one path removed from the walk. A Dir record means the subtree was pruned WITHOUT descending — nothing below it was enumerated, which is why counts of "files under an ignored dir" are deliberately not offered anywhere: producing them would cost the walk the prune bought.

type NotScannedVerdict

type NotScannedVerdict struct {
	Builtin bool   // a .git/.formwork ancestor — the built-in skip set
	Glob    string // the scan.ignore glob that pruned it, when that channel decided
	GitRule string // the gitignore rule ("<file>:<line>:<pattern>"), when that channel decided
}

NotScannedVerdict says whether the walk never yields a path, and which channel hides it. At most one of Builtin, Glob, GitRule is set; the zero value is "scanned". Hidden is DERIVED from the channel fields rather than stored, so a verdict claiming a channel without claiming hidden — the silent-governed fail-open — is unrepresentable (#125 review).

func NotScannedBy

func NotScannedBy(path string, opts Opts) NotScannedVerdict

NotScannedBy reports whether WalkWith(opts) never yields path (treated as a FILE path — the walk's file frame), and which trigger hides it, in the walk's own attribution order: descent hits the SHALLOWEST trigger first, and at each directory level the built-in skip set is consulted before scan.ignore globs before the gitignore prune (WalkWith's pinned dir-branch ordering). So a .git nested under an operator-ignored tree attributes the operator glob — the walk pruned above it and never saw that .git — while a root-level .git directory attributes the built-in skip. The built-in set applies to ANCESTOR segments only: WalkWith consults builtinSkipDir in its d.IsDir() branch and in the symlink refusal, never in its regular-file branch, so a regular file NAMED .git (a linked-worktree gitdir pointer is exactly this) is scanned and enforced on — reporting it hidden would contradict check's verdict (#119 third-pass finding 2). Ignore globs and the gitignore files set, by contrast, do match at the leaf: the walk's file branch checks both; the gitignore dirs set, like the built-in skip, applies to ancestors only. Getting any of this wrong makes trusted surfaces (lint's census, rules-for's annotation, #108) disagree about who hid a path — or whether it is hidden at all.

The ancestor test is the whole PREFIX, not its last segment: `.formwork` prunes only at the walk root since #268, and a bare segment cannot say how deep it sits. Answering "hidden by the built-in skip" for a nested corpus's .formwork would be this function claiming a prune the walk does not perform.

func (NotScannedVerdict) Hidden

func (v NotScannedVerdict) Hidden() bool

Hidden reports whether any channel hides the path from the walk.

type Opts

type Opts struct {
	// Ignore are scan.ignore globs — the operator's declaration that a tree is
	// not theirs to gate.
	Ignore []string
	// GitIgnored is the set of paths git itself refuses to track, nil when
	// scan.gitignore is undeclared OR when it was declared but git could not
	// answer. Those two cases must stay distinguishable to the CALLER, which
	// is why this is not a bool: nil here means "prune nothing", and it is the
	// caller's job to say which of the two it is. Pruning nothing is the
	// fail-CLOSED direction — the resulting scan is a superset of the declared
	// one, so no rule can pass that would otherwise have failed.
	GitIgnored *GitIgnored
}

Opts are the prunes applied to a walk. The zero value walks everything the built-in skips leave, so every pre-existing caller is unaffected.

type Source

type Source int

Source names the channel that removed a path from the walk. The census must be able to tell them apart: they are declared in different files, justified differently, and audited differently, so reporting one as the other would send a reader to the wrong place to change it.

const (
	// SourceIgnore is a scan.ignore glob. It is the zero value because it was
	// the only channel when Ignored was introduced, which keeps every existing
	// record's literal shape unchanged.
	SourceIgnore Source = iota
	// SourceGitignore is a path git itself refuses to track.
	SourceGitignore
	// SourceSymlink is a symlink the walk declined to follow (#143). Unlike the
	// other two it is not DECLARED anywhere — no glob, no .gitignore line — so
	// it is the one channel a reader cannot find by looking at config. That is
	// exactly why it has to be censused: the operator sees a rule matching
	// nothing and is told their glob is wrong, when the truth is that the walk
	// declined to look.
	SourceSymlink
)

Jump to

Keyboard shortcuts

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