config

package
v0.17.11 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package config loads .formwork/ YAML strictly and compiles rule envelopes into executable rules (spec §5). Any schema error is fatal — never a silent skip.

generated.go — the one definition of generated output (formwork.yaml `generated:`). Split from config.go, which the 750-line vendor cap bounds.

WHY ONE DEFINITION. A rule about hand-written code does not judge what a generator wrote: the generator's output is correct when it reproduces from its input, and that is a different gate. Before 0.14 every such rule carried its own list of generator spellings (`**/*.g.dart`, `**/*.pb.go`, `shared/generated/**`, ...) — one copy per rule, each a path region a hand-written file could be parked in, and each silently wrong the day a generator was added or renamed its output.

A generated file says what it is: every generator writes a header. The repository declares those headers ONCE, here, and each declaration names the rule that PROVES a file carrying it reproduces from its generator (`proven_by`). That proof is what keeps the marker from being a self-granted exemption: a hand-written file that copies the header fails the freshness gate, because regenerating does not produce it.

A file is generated when a declared marker appears in its LEADING comment block — the lines before its first line that is neither blank nor a comment. A marker anywhere later (a string, a comment beside code) declares nothing. Generated files are outside every rule's evaluation unless the rule says `scope.generated: true`, and the escape-hatch census counts them on every run.

scan.go — the formwork.yaml `scan:` block: the two repo-global channels that remove paths from the shared walk before any rule sees them, and their load-time validation. Split from config.go, which the 750-line vendor cap bounds; same package.

scopedeclare.go — scope.not_declaring: the declaration-keyed half of scope. Split from config.go, which the 750-line vendor cap bounds; same package.

WHY A DECLARATION IS NOT A PATH. Every other scope key answers "where does this file sit". That is the wrong question for the largest class of non-authored files in a real repository — generator output. Answering it by location means every rule that must not judge generated code carries a list of globs naming today's generator layout: `**/*.g.dart`, `**/*.pb.go`, `**/*.freezed.dart`, `shared/generated/**`, one entry per spelling per rule. Those lists are permitted-SETS by shape: a region a rule does not look at, which is exactly where the next violation gets parked, and adding a generator (or renaming an output suffix) silently widens or strands them.

A generated file already says what it is, in its first line, because every generator writes the marker: `// Code generated by protoc-gen-go. DO NOT EDIT.` So the rule can key on what the file DECLARES instead of on where it sits — one marker per rule, no glob list, and a new generator is covered on the day it lands rather than when someone remembers to add its suffix.

WHY THIS IS NOT AN HONOUR SYSTEM, which is the obvious objection. A marker a file writes about itself could be written into a hand-authored file to buy an exemption. That attack is real and this key does not defeat it alone — it is defeated by the codegen-freshness gates an adopting repo already runs, which assert that every file bearing the marker REPRODUCES from its generator. A hand-authored file wearing the marker fails those. So the declaration is a CHECKED claim, not a self-granted one, and that is the difference between this key and the glob list it replaces: a glob cannot be checked against anything, and nothing detects a file moved into its region.

The key therefore subtracts scope like except.paths does, and like except.paths it is reported with live match counts rather than silently — an entry matching nothing is a lie the census prints, not a protection nobody can see.

scopeparse.go — the parsers for the rule `scope:` block. Split from config.go, which the 750-line vendor cap bounds; same package.

testcode.go — the one definition of test code (formwork.yaml `tests:`) and a rule's statement that its subject is production code (scope.subject). Split from config.go, which the 750-line vendor cap bounds.

WHY A SUBJECT AND NOT AN EXCLUDE. Every rule judges tests by default: a test is code, and a rule about code reads it. Some rules are about something only production code can do — a production import of a testing package, a reflection call in shipped code, a request message no production handler consumes — and for those a test is not a weaker instance of the subject; it is not the subject at all, or (for a consumer census) it is evidence the rule must not count. Before 0.15 each such rule said so with its own list of test globs in scope.exclude: one copy per rule, indistinguishable from an exclude that forgives a violation, and wrong the day a test convention moved.

A repository's test code is a fact about its toolchains (`*_test.go` is a Go test because `go build` leaves it out), so it is declared ONCE, here. A rule whose subject is production code says `scope.subject: production`; every other rule reads tests. `formwork lint` lists each production-subject rule with the number of test files its subject leaves out, and refuses one whose subject leaves out nothing, so the statement is never a silent subtraction.

Index

Constants

View Source
const (
	SubjectAll        = "all"
	SubjectProduction = "production"
)

Subject values for scope.subject.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Version int
	// CorpusHash fingerprints the exact envelope and rule-file bytes LoadRules
	// consumed, including embedded library files later overridden locally.
	CorpusHash string
	// Engine is the raw engine-version constraint from formwork.yaml ("" if
	// absent). EngineConstraint is its parsed form (nil if absent). A binary
	// whose version does not satisfy the constraint refuses to run (spec §4).
	Engine           string
	EngineConstraint *semver.Constraints
	Lanes            []Lane
	Scope            ScopeConfig
	Ignore           []IgnoreEntry
	// Gitignore is the scan.gitignore declaration, nil when the key is absent.
	// Absent is off: a repo that does not declare it gets exactly the walk it
	// got before this key existed.
	Gitignore *GitignoreEntry
	Rules     []*Rule
	// Library is the pack names declared in formwork.yaml, in declaration
	// order. Empty when the key is absent or the list is empty.
	Library []string
	// RuleFiles is how many .formwork/rules/*.yaml files were read, whatever
	// they declared. It exists so a zero-rule refusal can name the actual
	// cause: no rule files at all is a different mistake from rule files that
	// parse and declare nothing (an empty or null `rules:` list, the shape a
	// bad merge or a templating error produces), and "add a rule file" is
	// useless advice to someone staring at the rule file they just wrote.
	RuleFiles int
	// Generation is the formwork.yaml `generated:` definition, nil when the
	// key is absent. Every rule loaded with this config carries it.
	Generation *Generation
	// Tests is the formwork.yaml `tests:` definition of test code, nil when
	// the repository declares none (testcode.go).
	Tests *TestCode
}

Config is the loaded, compiled configuration. Rules are sorted by ID and Lanes by Name.

func Load

func Load(repoRoot string) (*Config, error)

Load reads .formwork/formwork.yaml and .formwork/rules/*.yaml under repoRoot and returns compiled rules sorted by ID. A thin wrapper over ReadEnvelope + LoadRules for callers (and tests) that have no gate to run in between and so don't need the two steps split apart.

func (*Config) IgnoreGlobs

func (c *Config) IgnoreGlobs() []string

IgnoreGlobs returns the glob half of every scan.ignore entry, in config order. This is what scan.WalkIgnoring consumes; lint keeps the full entries for the census.

func (*Config) Lane

func (c *Config) Lane(name string) (Lane, bool)

Lane returns the named lane and whether it exists.

func (*Config) RulesForLane

func (c *Config) RulesForLane(name string) ([]*Rule, error)

RulesForLane returns the rules the named lane selects, preserving the ID-sorted order of Config.Rules. An unknown lane name is an error.

type DeclaringEntry added in v0.14.0

type DeclaringEntry struct {
	Marker  string
	Holders int
}

DeclaringEntry is one scope.not_declaring entry: a literal marker and the exact number of places in the rule's scope that declare it.

type Envelope

type Envelope struct {
	Version          int
	Engine           string
	EngineConstraint *semver.Constraints
	// contains filtered or unexported fields
}

Envelope is a read-once .formwork/formwork.yaml: the raw bytes are read and parsed exactly once, so a caller that needs to gate on it (the engine-version backstop, spec §4) before parsing any rule file is guaranteed to gate on the very same bytes LoadRules subsequently compiles — not a possibly-different later read of the file (finding 8: the file used to be read once for the gate via LoadRootMeta and a second time for execution via Load, so the gate's guarantee weakened from "allowed to evaluate THIS config" to "was allowed to evaluate some recent config").

func ReadEnvelope

func ReadEnvelope(repoRoot string) (*Envelope, error)

ReadEnvelope reads and validates ONLY .formwork/formwork.yaml, once. The caller gates on the envelope (engine constraint) before calling LoadRules, so an unsupported binary reports its version rather than failing on rule schema it was never built to understand.

func (*Envelope) LoadRules

func (e *Envelope) LoadRules() (*Config, error)

LoadRules parses the lanes, scope, and .formwork/rules/*.yaml rule files against the envelope ReadEnvelope already read — the exact same bytes any gate the caller ran between ReadEnvelope and LoadRules evaluated — and returns the compiled Config. Library packs named in formwork.yaml load first; a local file restating the same id replaces the pack rule.

type ExcludeEntry

type ExcludeEntry struct {
	Glob    string
	Comment string
}

ExcludeEntry is one scope.exclude glob plus its optional YAML justification comment (empty when the entry had none).

type GeneratedMarker added in v0.14.0

type GeneratedMarker struct {
	Marker   string
	ProvenBy []string
}

GeneratedMarker is one declared generator header and the rules that prove a file carrying it reproduces from its generator.

type Generation added in v0.14.0

type Generation struct {
	Markers []GeneratedMarker
}

Generation is the repository's definition of generated output. A nil *Generation declares none.

func (*Generation) Declares added in v0.14.0

func (g *Generation) Declares(content []byte) (string, bool)

Declares reports which declared marker the file's leading comment block carries, and whether one does.

type GitignoreEntry

type GitignoreEntry struct {
	Reason string
}

GitignoreEntry is the scan.gitignore declaration: a standing instruction to prune every path git itself refuses to track.

There is deliberately NO boolean here. A `prune: false` spelling would add a third state — declared but inert — that reads at a glance like the channel is active, and this is the widest exemption channel in the engine; the only way to turn it off is to delete the block, which no reader can misread.

Reason is required by schema (exit 2 without it) for the same purpose it is required on IgnoreEntry: this hides paths from every FileSet-consuming rule at once, and a channel that wide must say in the config why it exists, rather than relying on a lint check that might not run.

type Home added in v0.14.0

type Home struct {
	Entry int
	Span  declspan.Span
}

Home is one declaration a not_declaring marker opens in a file: the entry's index in NotDeclaringEntries and the lines the declaration spans.

type IgnoreEntry

type IgnoreEntry struct {
	Glob   string
	Reason string
}

IgnoreEntry is one scan.ignore glob plus its mandatory justification. scan.ignore hides matching paths from every FileSet-consuming rule in the run — the widest exemption channel in the engine — which is why Reason is required by schema (exit 2 without it) rather than by a lint check that might not run. External-tool rules (command, git-diff) shell out and rescan on their own, so they can still SEE ignored trees: extra findings, never silently missed ones (spec §5).

type Lane

type Lane struct {
	Name string
	All  bool
	Tags []string
	Cost string // "", "fast", or "heavy"
	CI   bool
}

Lane is an orchestration group: a named selector over rules (spec §8). Exactly one of All or Tags is set (validated at load). Cost, when set, further restricts the lane to rules of that cost class ("" = any cost). CI reports whether the lane runs in CI — lint's lane-reachability check (spec §9) requires every rule to be selected by at least one CI lane.

func (Lane) Selects

func (l Lane) Selects(r *Rule) bool

Selects reports whether this lane runs r: the cost filter (if any) must match, then an all-lane selects every remaining rule and a tag lane selects a rule sharing at least one tag.

type LangClass

type LangClass struct {
	Name  string
	Globs []string
}

LangClass maps a language flag name to the globs that trigger it.

type Rule

type Rule struct {
	ID       string
	Type     string
	Severity finding.Severity
	Cure     string
	Origin   string
	Tags     []string
	Checker  rules.Checker

	// FixtureExempt is a heavy rule's declared reason for carrying no fixtures
	// (#53). Empty means undeclared, which lint reports rather than skips.
	FixtureExempt string

	Preprocess string // preprocess variant name; "" means raw

	// Library is the pack name this rule was loaded from (e.g. "generic").
	// Empty means the rule was declared in the adopting repo. Lint's
	// fixture-coverage check skips library-sourced rules: their fixtures
	// live in the pack and are proven by `formwork test -C stdlib/<name>`.
	Library string

	// File is the slash-separated, repo-relative path of the rule file that
	// declared this rule (.formwork/rules/<name>.yaml). Empty for a library
	// rule, whose definition ships in the binary. A changeset that edits it may
	// have changed the rule itself, so the changeset gate runs the rule.
	File string
	// contains filtered or unexported fields
}

Rule is a compiled rule: envelope plus instantiated checker.

func New

func New(id, typeName string, sev finding.Severity, cure string, include, exclude []string, c rules.Checker) (*Rule, error)

New builds a compiled rule directly. Load uses it; engine and report tests use it to construct rules without YAML.

func (*Rule) Applies

func (r *Rule) Applies(relPath string) bool

Applies reports whether relPath (slash-separated) is in this rule's scope.

func (*Rule) CloneWithChecker

func (r *Rule) CloneWithChecker(c rules.Checker) *Rule

CloneWithChecker returns a shallow copy of the rule with its checker replaced. Used by lint's load-bearing-prefilter differential to evaluate a prefilter-stripped variant of a rule. The clone shares the scope slices and params node with the original; both are read-only after construction, so sharing is safe (mirrors Fresh).

func (*Rule) Cost

func (r *Rule) Cost() rules.Cost

Cost is the rule's evaluation cost class, defaulting to fast for checkers that do not declare one (spec §8).

func (*Rule) Exclude

func (r *Rule) Exclude() []string

Exclude returns this rule's scope.exclude globs (read-only; do not mutate). Empty when the rule has no excludes. Used by formwork lint's escape-hatch census and dead-exclude hygiene.

func (*Rule) ExcludeEntries

func (r *Rule) ExcludeEntries() []ExcludeEntry

ExcludeEntries returns each scope.exclude glob paired with its YAML justification comment (empty string when the entry had none).

func (*Rule) Fresh

func (r *Rule) Fresh() (*Rule, error)

Fresh returns a copy of the rule with a newly constructed checker. Checkers may carry per-run state (e.g. required-pattern exists mode), so evaluating a rule against multiple independent trees — as the fixture runner does — requires a fresh instance per tree. Rules built with New (no factory) cannot be refreshed. The clone is shallow and shares the scope slices and params node with the original; this is safe because both are treated as read-only after construction.

func (*Rule) Generation added in v0.14.0

func (r *Rule) Generation() *Generation

Generation returns the repository's definition of generated output, shared by every rule loaded from it; nil for a rule built with New.

func (*Rule) Homes added in v0.14.0

func (r *Rule) Homes(path string, content []byte) []Home

Homes returns every declaration in content that one of the rule's not_declaring markers opens: one Home per occurrence of a marker, spanning the declaration that begins on the occurrence's first line (declspan). The engine masks those lines before the rule reads the file, so the home is removed and every other line of the file is judged.

Content, not path: this is the one scope test that cannot be answered from a file name. The marker is matched as a LITERAL, not a pattern: a declaration is fixed text, and a regexp would make the difference between "declares this" and "mentions this" depend on metacharacters nobody meant.

func (*Rule) InPathScope added in v0.15.0

func (r *Rule) InPathScope(relPath string) bool

InPathScope reports whether relPath matches the rule's include and not its exclude, before scope.subject: the path scope a production subject narrows.

func (*Rule) Include

func (r *Rule) Include() []string

Include returns this rule's scope.include globs (read-only; do not mutate). Introspection surface (#105/#108): explain and rules-for render scope from the same globs Applies consults, so the display can never drift from the verdict.

func (*Rule) JudgesGenerated added in v0.14.0

func (r *Rule) JudgesGenerated() bool

JudgesGenerated reports whether the rule declares scope.generated: true, the one way a rule reads files a declared generator wrote.

func (*Rule) MinFiles

func (r *Rule) MinFiles() int

MinFiles returns this rule's scope floor: the number of files its scope must select before the rule is considered to have had anything to look at. Zero — the default for every rule that does not declare `scope.min_files` — means no floor, which is exactly the behaviour that shipped before the key existed.

func (*Rule) NotDeclaring added in v0.8.3

func (r *Rule) NotDeclaring() []string

NotDeclaring returns this rule's scope.not_declaring markers, in entry order. Empty when the rule declares none. Used by the escape-hatch census so the key is never a silent subtraction.

func (*Rule) NotDeclaringEntries added in v0.14.0

func (r *Rule) NotDeclaringEntries() []DeclaringEntry

NotDeclaringEntries returns the {marker, holders} entries (read-only).

func (*Rule) Params

func (r *Rule) Params() (any, error)

Params returns the rule's retained params decoded into plain Go values (maps/slices/scalars), or nil when the rule declared none. Introspection only — the checker was compiled from this same node at load time, so this is a rendering of what already governs, never a second source of truth.

func (*Rule) ParamsYAML

func (r *Rule) ParamsYAML() (string, error)

ParamsYAML re-renders the retained params node as YAML for human display, or "" when the rule declared none.

func (*Rule) SetMinFiles

func (r *Rule) SetMinFiles(n int) error

SetMinFiles sets the scope floor, refusing a value that could never fire.

The field is unexported and this is the only door onto it, so compile (the YAML path) and the New-plus-setter path used by tests cannot disagree about what a legal floor is. A negative floor is refused rather than clamped: every possible file count satisfies it, so it would read as armed while being incapable of failing.

func (*Rule) SubjectIsProduction added in v0.15.0

func (r *Rule) SubjectIsProduction() bool

SubjectIsProduction reports whether the rule declares scope.subject: production, so it reads no file the repository's `tests:` names.

func (*Rule) TestCode added in v0.15.0

func (r *Rule) TestCode() *TestCode

TestCode returns the repository's definition of test code, shared by every rule loaded from it; nil for a rule built with New.

func (*Rule) WholeTreeInvariant

func (r *Rule) WholeTreeInvariant() bool

WholeTreeInvariant reports whether the rule's verdict is a whole-repo invariant that must be evaluated over the whole tree even under a --staged/--range changeset scan (mirrors Cost). Range-scoping a required- pattern(exists) / set-relation / pattern-count / baseline rule false-fails it when the file bearing its token is not in the change range (#4).

type ScopeConfig

type ScopeConfig struct {
	Docs       []string
	Governance []string
	Languages  []LangClass // sorted by Name for deterministic output
}

ScopeConfig classifies a changeset (spec §8): which paths are docs, governance, or (by default) runtime, plus per-language change globs.

func (ScopeConfig) Classify

func (sc ScopeConfig) Classify(changed []string) (class string, langs map[string]bool)

Classify returns the changeset's class and per-language change flags. A file matching no docs/governance glob is runtime (fail-closed, spec §11); the changeset takes the highest class of any file (runtime > governance > docs). An empty changeset is docs (nothing to gate).

type TestCode added in v0.15.0

type TestCode struct {
	Globs []string
}

TestCode is the repository's definition of test code: path globs, matched like scope.include. A nil *TestCode declares none.

func (*TestCode) Contains added in v0.15.0

func (t *TestCode) Contains(relPath string) bool

Contains reports whether relPath (slash-separated) is test code.

Jump to

Keyboard shortcuts

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