412 lines
21 KiB
Markdown
412 lines
21 KiB
Markdown
# config-discovery
|
||
|
||
## Goal
|
||
|
||
`lucisv.toml` / `.lucisv.toml` discovery in the style of ruff's `ruff.toml`:
|
||
for every input file, search upward from its directory for a config file
|
||
and take `line-length`, `indent` and `exclude` from the first one found.
|
||
CLI flags still win. This is what makes lucisv usable in a repo where the
|
||
style is a property of the tree rather than of the command line — an
|
||
editor's format-on-save (which goes through stdin) picks up the same
|
||
settings as CI's `lucisv --check`, with no per-editor configuration. Kept
|
||
deliberately tiny per TODO.md §3: three keys, no tables, no option
|
||
explosion, no new dependency.
|
||
|
||
## Assumptions
|
||
|
||
- **Three keys is the whole surface.** `line-length`, `indent`,
|
||
`exclude` — exactly the CLI's own knobs. Anything else in the file is
|
||
a hard error, not a warning: ruff's experience is that silently
|
||
ignoring `line_length` (underscore) or a misspelled key wastes far
|
||
more user time than a strict parser costs.
|
||
- **A full TOML crate is not justified for this.** CLAUDE.md requires a
|
||
written justification for a dependency; `toml` + `serde` is ~30k lines
|
||
of transitive code to read three scalars and a string array out of a
|
||
file that is, in practice, four lines long. The hand-rolled subset
|
||
parser is ~100 lines, has no unsafe, no build-time cost, and its
|
||
failure mode ("unsupported in lucisv.toml") is a better error than a
|
||
full parser silently accepting syntax lucisv would then ignore. If the
|
||
key set ever grows past ~10 keys or needs tables, revisit.
|
||
- **The supported grammar is a subset, and says so.** Anything valid in
|
||
real TOML but outside the subset (tables, multi-line arrays, dotted
|
||
keys, floats, booleans, datetimes, literal/multi-line strings, string
|
||
escapes) is rejected with an error naming the file and line. It is
|
||
never silently ignored.
|
||
- **Config files are read fresh on every run.** No caching across runs,
|
||
no config hash in a cache key (TODO.md §3's content-hash cache item
|
||
will need one — see Handshakes).
|
||
- **Discovery is lexical, not symlink-aware.** The upward walk
|
||
normalizes `.` / `..` textually and never calls `canonicalize`, so a
|
||
file reached through a symlink resolves against the symlink's path,
|
||
not the link target's. This matches how the path was typed, which is
|
||
what a user editing that path expects.
|
||
- **`exclude` is resolved once per command-line input, not per walked
|
||
directory.** A config file found at (or above) the input path
|
||
contributes its `exclude` patterns to that whole walk; a config file
|
||
in a *subdirectory* of the walk does not add excludes mid-walk. Its
|
||
`line-length`/`indent` still apply per file. Doing better would mean
|
||
re-resolving config at every directory during the walk, which is more
|
||
machinery than the payoff justifies today.
|
||
- **Range checks apply to config files, not to CLI flags.** A typo in a
|
||
file you can't see the effect of is worth catching (`line-length =
|
||
1000` is nearly always a mistake); an explicit `--line-length 1000` on
|
||
the command line stays as permissive as it has always been, because
|
||
tightening it would change frozen CLI behavior for no safety gain.
|
||
|
||
## Behavior (the contract this feature adds)
|
||
|
||
### Discovery rule
|
||
|
||
For a directory `D`, in this exact order:
|
||
|
||
1. If `D/lucisv.toml` exists → use it. Stop.
|
||
2. Else if `D/.lucisv.toml` exists → use it. Stop.
|
||
3. Else if `D/.git` exists (file *or* directory) → stop with **no**
|
||
config. The `.git` check happens **after** steps 1–2, so a config
|
||
file sitting next to `.git` in the repo root *is* found.
|
||
4. Else move to `D`'s parent and repeat. At the filesystem root, stop
|
||
with no config.
|
||
|
||
The starting directory `D` is:
|
||
|
||
- for an input file: the directory containing it;
|
||
- for a directory named on the command line: that directory itself;
|
||
- for stdin: the directory of `--stdin-filename` when given, else the
|
||
current working directory.
|
||
|
||
Relative paths are resolved against the current directory before the
|
||
walk, so `lucisv a.sv` searches the cwd and its ancestors.
|
||
|
||
Exactly one config file is ever used per file — there is no merging of a
|
||
parent config into a child config (ruff's `extend` is not implemented).
|
||
|
||
### Recognized keys
|
||
|
||
| Key | Type | Range | Effect |
|
||
|---|---|---|---|
|
||
| `line-length` | integer | 40..=400 | same as `--line-length` |
|
||
| `indent` | integer | 1..=8 | same as `--indent` |
|
||
| `exclude` | array of strings | — | appended to `--exclude` patterns, same glob semantics |
|
||
|
||
All optional. An unknown key is a hard error naming the key, the file
|
||
and the line. A duplicate key is an error too.
|
||
|
||
### Supported TOML subset (grammar)
|
||
|
||
```
|
||
file := line*
|
||
line := ws* (comment | entry)? ws*
|
||
comment := '#' <rest of line>
|
||
entry := key ws* '=' ws* value (ws* comment)?
|
||
key := "line-length" | "indent" | "exclude"
|
||
value := integer | string | array
|
||
integer := digit+
|
||
string := '"' <any char except '"' and '\'> '"'
|
||
array := '[' ws* (string (ws* ',' ws* string)* (ws* ',')?)? ws* ']'
|
||
```
|
||
|
||
Everything is one entry per line; whitespace around every token is
|
||
optional. Rejected with an explicit "unsupported in lucisv.toml" error:
|
||
tables/sections (`[tool.lucisv]`), multi-line arrays, string escapes,
|
||
booleans/floats/datetimes, and any line that is not a comment, blank, or
|
||
`key = value`.
|
||
|
||
### Precedence
|
||
|
||
**CLI flag > config file > built-in default**, per setting, not per
|
||
file: `--line-length 80` with a config that sets only `indent` uses the
|
||
CLI's width and the file's indent. `exclude` is the exception and
|
||
*accumulates*: CLI patterns plus config patterns, since both are "also
|
||
skip this".
|
||
|
||
Files in different directories can get different configs in a single
|
||
run; discovered configs are cached in a `HashMap` keyed by directory (the
|
||
whole upward chain is memoized, so a big tree under one config file
|
||
parses that file once).
|
||
|
||
### `--no-config`
|
||
|
||
Ignores config files entirely — nothing is read from disk, every file
|
||
gets CLI-flags-or-defaults. The escape hatch for "format this the way I
|
||
just typed, whatever the repo says".
|
||
|
||
### Errors
|
||
|
||
A config file that cannot be read or parsed is a **fatal** error:
|
||
`error: <path>:<line>: <what>`, exit code 2, and **no file is written**
|
||
— all configs are resolved before any formatting starts, so a broken
|
||
config in a deep subdirectory cannot leave a run half-applied. This
|
||
respects the frozen exit-code contract (2 = error, files untouched).
|
||
|
||
## Handshakes
|
||
|
||
- **Consumes `Options.stdin_filename`** from cli-polish exactly as that
|
||
feature's README promised: the raw path is used only as the *anchor
|
||
directory* for discovery. Nothing is read from or written to that
|
||
path, and it still need not exist.
|
||
- **Consumes `Options.exclude`** as the CLI layer; config `exclude`
|
||
patterns are appended to it and matched by the same
|
||
`walk::is_excluded`.
|
||
- **Consumes `vlog_formatter::Config`** (`max_width`, `indent_width`)
|
||
unchanged. Nothing in `crates/vlog_formatter` or `crates/vlog_parser`
|
||
was touched; the two fields sufficed, so no change request was needed.
|
||
- **Changes `args::Options`** (internal to `crates/lucisv`): the eager
|
||
`config: Config` field is replaced by `line_length: Option<usize>` and
|
||
`indent: Option<usize>` — "was the flag given?" has to survive to the
|
||
point where the file config is known. `Options::config_with(&FileConfig)`
|
||
builds the per-file `Config`. A new `no_config: bool` field carries
|
||
`--no-config`.
|
||
- **Promises to TODO.md §3's content-hash cache:** the cache key must
|
||
include the resolved per-file settings (or a hash of the config file
|
||
that produced them), not just file content + lucisv version — two files
|
||
with identical content under different config files must not share a
|
||
cache entry. `config::FileConfig` derives `PartialEq` and is cheap to
|
||
hash-by-debug if that is all the cache needs.
|
||
- **Promises to TODO.md §3's parallelism item:** config resolution
|
||
happens entirely up front, in `gather`, on one thread. The
|
||
`Vec<(PathBuf, Config)>` it produces is exactly the work list a
|
||
`par_iter` wants — `Discovery` itself never needs to be shared across
|
||
threads.
|
||
- **Promises to the future LSP (TODO.md §6):** `Discovery::for_file` is
|
||
the one entry point a server needs to answer "what settings apply to
|
||
this buffer?", and its cache is per-`Discovery`, so a server can drop
|
||
and rebuild one when a config file changes on disk.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `src/config.rs`: TOML-subset parser (`parse`) + upward discovery
|
||
with a per-directory `HashMap` cache (`Discovery`).
|
||
- [x] Discovery rule: `lucisv.toml` before `.lucisv.toml`, `.git` stops the
|
||
walk *after* the current directory is checked, filesystem root
|
||
stops it.
|
||
- [x] Keys `line-length` (40..=400), `indent` (1..=8), `exclude`
|
||
(appended to CLI excludes); unknown key / duplicate key / bad
|
||
value / out-of-range are hard errors naming file and line.
|
||
- [x] Precedence CLI > file > default, per setting; per-file resolution
|
||
so different directories can differ in one run.
|
||
- [x] `--no-config` flag, documented in `--help`.
|
||
- [x] stdin anchors on `--stdin-filename`'s directory, else cwd.
|
||
- [x] Config errors are fatal, exit 2, before anything is written.
|
||
- [x] Unit tests for the parser and for discovery; CLI integration
|
||
tests in `crates/lucisv/tests/cli.rs`.
|
||
- [x] `README.md`: Configuration section. `TODO.md` §3 config item
|
||
checked off.
|
||
|
||
## Work log
|
||
|
||
### 2026-08-19 — dev agent
|
||
|
||
- Read CLAUDE.md, TODO.md §3, README.md, `docs/features/cli-polish/README.md`
|
||
and all of `crates/lucisv/src` before writing anything. cli-polish's
|
||
Handshakes section already promised `stdin_filename` as the discovery
|
||
anchor and `exclude` as the CLI layer; both are honored literally.
|
||
- **No TOML dependency.** Justification (CLAUDE.md requires one in
|
||
writing): three keys, one array, no tables — `toml`+`serde` would be
|
||
three transitive crates and a proc-macro build step to read four lines
|
||
of text. The subset parser is 95 lines including error messages, and
|
||
it *rejects* what it does not support rather than accepting TOML lucisv
|
||
would then ignore, which is the better failure mode here. Revisit if
|
||
the key set passes ~10 or ever needs tables.
|
||
- **Discovery walks up, `.git` stops it after the directory is
|
||
checked.** The alternative (check `.git` first) would make the common
|
||
layout — `lucisv.toml` next to `.git` in the repo root — silently not
|
||
work, which is exactly the ruff layout people expect. Both halves of
|
||
the rule have tests (`git_stops_the_walk_but_only_after_its_own_directory`
|
||
in `config.rs`, `the_search_stops_at_a_git_directory_after_checking_it`
|
||
in `tests/cli.rs`). A `.git` *file* (submodule / worktree) stops the
|
||
walk too.
|
||
- **The cache memoizes the whole chain, not just the starting
|
||
directory.** One `HashMap<PathBuf, FileConfig>`: after resolving
|
||
`a/b/c`, the entries for `a/b/c`, `a/b`, `a` and the root all point at
|
||
the same answer, so a tree of 1000 directories under one config file
|
||
reads and parses that file once. This is a three-line addition
|
||
(`chain`) over the naive version and needs no extra data structure.
|
||
- **Config errors are fatal, and resolved before any write.** `gather`
|
||
now returns `Vec<(PathBuf, Config)>` — every config file in the run is
|
||
read while building that list, so a broken `lucisv.toml` in a deep
|
||
subdirectory aborts with exit 2 and *nothing* written, rather than
|
||
half the tree formatted. It also keeps the error from being repeated
|
||
once per file in the offending directory.
|
||
- **`Options` changed shape** (internal to `crates/lucisv`): `config:
|
||
Config` became `line_length: Option<usize>` / `indent: Option<usize>`,
|
||
because "was the flag given?" has to survive until the file config is
|
||
known. `Options::config_with` / `exclude_with` apply precedence in one
|
||
place each. Nothing outside `crates/lucisv` was touched;
|
||
`vlog_formatter::Config`'s two fields sufficed exactly.
|
||
- **Range checks (`line-length` 40..=400, `indent` 1..=8) apply to the
|
||
file only**, not to `--line-length`/`--indent`. Tightening the flags
|
||
would change frozen CLI behavior for no safety gain; a typo in a file
|
||
you can't see the effect of is the case worth catching. Recorded under
|
||
Assumptions.
|
||
- **`exclude` resolves once per command-line input**, not per walked
|
||
directory — the walk needs its pattern list before it starts. A config
|
||
in a subdirectory still sets `line-length`/`indent` for the files under
|
||
it; it just cannot add excludes mid-walk. Documented as an assumption
|
||
rather than built, per "simplicity first".
|
||
- Trailing `#` comments after a value are supported (quote-aware, so
|
||
`exclude = ["a#b"]` is not truncated); trailing commas in arrays are
|
||
accepted like real TOML. Both cost three lines and are the two things
|
||
people actually type.
|
||
- The workspace was uncompilable for part of this run — the concurrent
|
||
agent's span work in `vlog_parser`/`vlog_formatter` was mid-landing
|
||
(56-60 compile errors in `vlog_parser`, none in `lucisv`). Waited it out
|
||
rather than touching their crates; final gates re-run on the merged
|
||
tree, see Results.
|
||
- Sanity-checked the real binary outside the test suite (scratchpad, then
|
||
deleted): a tree with `indent = 4` + `exclude = ["gen"] # generated`
|
||
formatted `rtl/a.sv` to 4 spaces, left `gen/g.sv` untouched, exit 0;
|
||
changing the key to `line_length` produced
|
||
`error: …/lucisv.toml:2: unknown key \`line_length\` (known keys:
|
||
line-length, indent, exclude)` and exit 2 with nothing written.
|
||
|
||
**Results** (workspace root, final):
|
||
|
||
- `cargo test -p lucisv`: **59 passed, 0 failed** — 38 unit (config 18:
|
||
8 parser + 10 discovery; args 6; walk 4; diff 6; main 4 — the 6 args
|
||
tests include the two new precedence tests) and 21 CLI integration
|
||
(8 new: upward search, per-directory configs, CLI override,
|
||
`--no-config`, broken-config-exits-2 (5 malformed files), config
|
||
excludes, stdin discovery + stdin config error, `.git` stop).
|
||
- `cargo test --workspace`: **148 passed, 0 failed** (`lucisv` 59,
|
||
`vlog_formatter` 42, `vlog_parser` 47) on the tree as merged with the
|
||
concurrent span work.
|
||
- `cargo clippy -p lucisv --all-targets`: zero warnings.
|
||
- `cargo fmt -p lucisv --check`: clean. Only `crates/lucisv` was formatted,
|
||
so no file owned by the other agent was touched.
|
||
- Sizes: `config.rs` 476 lines (203 of code + doc comments, 273 of
|
||
tests; the parser half is 95 lines), `args.rs` 220, `main.rs` 261,
|
||
`tests/cli.rs` 465. No `Cargo.toml` change, no new dependency.
|
||
|
||
## QA log
|
||
|
||
### 2026-08-19 — QA agent
|
||
|
||
Scope: `crates/lucisv/**` only (a concurrent dev agent was landing the spans
|
||
feature in `vlog_parser`/`vlog_formatter`; the workspace was compilable by
|
||
the time these checks ran, so both scoped and full-workspace runs were
|
||
possible).
|
||
|
||
**Gates** — all clean:
|
||
- `cargo test -p lucisv`: 59 passed, 0 failed (38 unit + 21 integration, exact
|
||
match to the claim). `cargo test --workspace`: 158 passed, 0 failed
|
||
(`lucisv` 59, `vlog_formatter` 42, `vlog_parser` 57) — higher than the
|
||
work log's "148 at the time of dev's run" because the concurrent span
|
||
work (10 new `tests/spans.rs` cases) landed afterward; not a
|
||
config-discovery regression.
|
||
- `cargo clippy -p lucisv --all-targets`: zero warnings.
|
||
- `cargo fmt -p lucisv --check`: clean.
|
||
- No `Cargo.toml` / `Cargo.lock` diff anywhere in the repo — the
|
||
no-new-dependency claim holds.
|
||
- `unwrap()`/`expect()`/`panic!` audit of `config.rs`, `args.rs`, `main.rs`:
|
||
every occurrence outside `#[cfg(test)] mod tests` was checked by line
|
||
number; none exist outside test modules (`main.rs`'s are all inside its
|
||
own `mod tests` too, so the CLAUDE.md main.rs exemption wasn't even
|
||
needed). All public items in `config.rs` (`FileConfig` + its 3 fields,
|
||
`parse`, `Discovery` + its 3 `pub fn`s) carry a doc comment.
|
||
|
||
**Claims verified against the real binary** (scratchpad trees, deleted
|
||
after): nearest-wins-no-merge with two files formatted differently in one
|
||
run (byte-exact); `.git` as a plain file *and* as a directory both stop the
|
||
walk, and a config sitting next to `.git` is still found either way;
|
||
`--no-config` reads nothing off disk even when the file present is garbage;
|
||
CRLF config files parse and apply correctly (verified actual indent +
|
||
line-length effect, not just exit code, since `str::lines()` strips the
|
||
`\r`); a 5000-element `exclude` array and a 10-directory deep chain both
|
||
resolve correctly with no slowdown; a symlinked input resolves its config
|
||
against the symlink's own directory, not the real target's — matching the
|
||
documented "lexical, not symlink-aware" behavior exactly (confirmed by
|
||
pointing a symlink from a dir with `indent=2` at a real file under a dir
|
||
with `indent=8`: the write came out at 2). `--stdin-filename` pointing at a
|
||
nonexistent directory doesn't error — the upward walk just finds no config
|
||
and falls through to defaults, exit 0, no crash.
|
||
|
||
**Pre-write fatality (the contract claim most worth breaking) — held.**
|
||
Built the adversarial case directly: `a_good/x.sv` (alphabetically first,
|
||
its directory has no config problem) plus `b_bad/lucisv.toml` with an unknown
|
||
key governing `b_bad/y.sv` (alphabetically later, so it's walked and
|
||
formatted *after* `a_good/x.sv` in `walk_dir`'s sorted order). Ran the real
|
||
binary: exit 2, and **both** files came back byte-identical to their
|
||
originals — `gather()` really does resolve every file's config before
|
||
`run_files` writes anything, even when the broken config belongs to a file
|
||
later in walk order than an otherwise-fine one.
|
||
|
||
**Findings** — all non-blocking (no silent write-despite-config-error, no
|
||
parser hole that accepts a wrong value; every malformed input tried failed
|
||
closed at exit 2 with nothing written):
|
||
|
||
1. **[Low] BOM breaks key matching with a confusing message.** A
|
||
`lucisv.toml` starting with a UTF-8 BOM (`EF BB BF`) fails every key on
|
||
its first line: `read_to_string` doesn't strip it and `str::trim()`
|
||
doesn't treat U+FEFF as whitespace, so `indent = 4` becomes the "key"
|
||
`\u{FEFF}indent`, reported as `unknown key` with an invisible character
|
||
in the message. Still exit 2, nothing written — just a diagnosis a user
|
||
can't act on without knowing to check for a BOM. `config.rs:29-64`.
|
||
2. **[Low] Permission-denied paths are misreported as "no such file or
|
||
directory".** `chmod 000` on a directory (or an ancestor needed to
|
||
reach it) makes `Path::is_dir()`/`is_file()`/`.exists()` swallow the
|
||
underlying `EACCES` and return `false` everywhere they're used —
|
||
`collect_files` in `walk.rs:17-23` (pre-existing, not new to this
|
||
feature) and `Discovery::for_dir`'s `config_file_in`/`.git` checks in
|
||
`config.rs:175,180,213-215`. The user sees `no such file or directory`
|
||
instead of a permission error, and a config file sitting inside a
|
||
permission-blocked directory is silently treated as "not present there"
|
||
rather than erroring — the walk just continues upward. Still fails
|
||
safe (exit 2 or a sensible fallback, never a crash, never a wrong
|
||
write), just a misleading diagnosis. Restored permissions after
|
||
testing.
|
||
3. **[Info] Integer grammar is looser than documented.** The grammar in
|
||
this README says `integer := digit+`, and the "unsupported TOML is
|
||
named, not ignored" philosophy explicitly lists booleans/floats/escapes
|
||
as rejected-by-name — but `indent = +4` and `indent = 04` both parse
|
||
silently to `4` (`str::parse::<usize>` accepts a leading `+` and
|
||
leading zeros). The resulting value is correct in both cases, so this
|
||
is not a safety issue, just an undocumented acceptance outside the
|
||
stated grammar. `config.rs:66-83` (`set_int`).
|
||
4. **[Doc, fixed directly] Work log arithmetic didn't add up.** The Work
|
||
log's Results section said "config 20: 9 parser + 11 discovery" tests.
|
||
Actual count from the test run: 18 `config::` unit tests (8
|
||
parser-only + 10 that exercise `Discovery`/`TempTree`) — matches the
|
||
real total, since 18 + args 6 + walk 4 + diff 6 + main 4 = 38, the
|
||
verified unit-test count; the original "20" would have made it 40.
|
||
Fixed the two numbers directly in place above (small, unambiguous, per
|
||
the QA fixing latitude in CLAUDE.md) rather than filing it as a
|
||
finding only.
|
||
|
||
**Verdict:** all four scope claims (discovery rule, TOML subset parser,
|
||
precedence, test counts) hold up under adversarial testing through the
|
||
real binary and the unit suite. Nothing here rises to the level CLAUDE.md
|
||
cares most about — no masked corruption, no silent wrong write.
|
||
|
||
## Review
|
||
|
||
**2026-08-19 — lead. Verdict: accepted and committed, with two small lead
|
||
fixes.**
|
||
|
||
Textbook feature: the strict-subset TOML parser is the right reading of
|
||
the no-dependencies rule (and the "unknown key is a hard error" behavior
|
||
is worth more than the whole rest of the feature — a silently ignored
|
||
`line_length` typo is exactly how formatters lose users' trust), the
|
||
`.git`-stops-after-check ordering is correct and well documented, and
|
||
`gather()` resolving every config before any write is the exit-code
|
||
contract taken seriously. QA's walk-order attack on pre-write fatality
|
||
was the right test and it held.
|
||
|
||
Lead fixes while accepting (QA findings 1 and 3):
|
||
|
||
1. **BOM stripped** at the top of `parse()` — a BOM'd config now parses
|
||
instead of producing an `unknown key` with an invisible cause.
|
||
2. **`+4` rejected** — `from_str` accepts a leading `+` that the
|
||
documented `digit+` grammar does not; the parser now enforces the
|
||
grammar it documents. (Leading zeros like `04` remain accepted:
|
||
they *are* `digit+`.)
|
||
|
||
Dispositions:
|
||
|
||
- **EACCES swallowed as "not found"** (finding 2): pre-existing in
|
||
`walk.rs` too, fails safe (exit 2, nothing written), and fixing it
|
||
properly means switching the discovery checks from `is_file()` to
|
||
`metadata()` error inspection across both modules — queued as a
|
||
follow-up note here rather than patched piecemeal.
|
||
- QA's in-place arithmetic fix to the work log (finding 4) was within
|
||
its small-fix latitude and is appreciated.
|