cli-polish
Goal
The small ruff-inspired CLI items from TODO.md §1–§3 that make lucisv
usable in CI and in editors: --diff (print a unified diff instead of
rewriting), --stdin-filename (name the buffer an editor piped in),
--exclude (skip generated files during directory walks), a frozen and
documented exit-code contract, and per-file panic containment so one
pathological file cannot kill a whole run. No new dependencies; the
hand-rolled argument parsing style of main.rs is kept.
Assumptions
--diffdoes not need to be GNU-diff byte-exact. It emits a unified-style diff (--- path/+++ path/@@ -a,b +c,d @@hunks with 3 lines of context) that reads correctly for humans and CI logs. It is not promised to be machine-applicable bypatch; the hunks come from a resync heuristic (below), not from a minimal-edit-script diff, so they can be coarser than GNU's.- Diff granularity is the line. Intra-line changes are shown as a deleted line plus an inserted line.
- A missing final newline is a real difference. A side whose text
does not end in
\ngets a pseudo-line\ No newline at end of fileappended, so "only the trailing newline changed" still produces a visible hunk instead of an empty diff. --excludeis a path-suffix / basename matcher, not a full glob. No**, no?, no character classes.*never crosses a/. Anchoring to the current directory is deliberately not supported — patterns are relative-suffix matches.- Explicitly named files are never excluded.
--excludeonly filters directory walks (ruff calls the opposite behavior--force-exclude; not implemented). - A panic inside the formatter is a bug, not a supported error path. Containment exists so the run continues and the summary is honest; the report carries only the panic payload message, not the source location, because the default hook is silenced for the contained call.
- The formatter is single-threaded today.
catch_panicswaps the process-wide panic hook around each call, which is safe only because nothing else runs concurrently. TODO.md §3's rayon item must revisit this (see Handshakes).
Behavior (the contract this feature freezes)
--diff
-
Implies "do not write": no file is ever modified, exactly like
--check. -
For each file that would change, prints to stdout:
--- path/to/file.sv +++ path/to/file.sv @@ -12,7 +12,6 @@ context line -removed line +added line context lineThe path is printed as given on the command line (the walked path for directory inputs), identically on both header lines. Files that would not change print nothing.
-
The end-of-run summary (
N files would be reformatted, …) goes to stderr, as with--check, solucisv --diff … > patch.txtcaptures only diff text. -
Exit code:
1if any file would change,0if none would,2if any file errored (error wins over "would change"). -
--check --difftogether: the diff replaces thewould reformat: <path>lines; semantics are otherwise identical. -
--diff --stdoutis rejected as a usage error (exit 2) — they ask for two different things on stdout. -
In stdin mode
--diffdiffs the piped buffer against its formatted form, using--stdin-filename(else<stdin>) in the header, and exits 1 if it differs.
--stdin-filename <path>
- Only meaningful when the single input is
-. It replaces<stdin>in error messages (error: <path>: parse error: …) and in the--diffheader and--checkreport line. - It does not cause anything to be read from or written to that path.
- Silently ignored when not reading from stdin.
--exclude <pattern> (repeatable)
Applied while walking a directory, to every entry (file and directory). An excluded directory is not descended into.
- A pattern containing
/is matched against the path suffix, component-aligned:gen/rtlmatchesa/b/gen/rtl/x.sv's directorya/b/gen/rtl, and does not matchgen/other. - A pattern without
/is matched against the entry's name only:buildmatches any file or directory namedbuild;*_pkg.svmatches by basename at any depth. *matches any run of characters (including none) within one path component; it never matches/. There are no other metacharacters.- Matching is case-sensitive and applied to the path as the walk built it (i.e. rooted at the input path as typed).
- Paths named directly on the command line are always formatted, even if
they match an
--excludepattern.
Exit codes (frozen, per TODO.md §3)
| Code | Meaning |
|---|---|
| 0 | Success. Files were formatted, or --check/--diff found nothing to change. |
| 1 | --check or --diff only: at least one file would be reformatted. Nothing was written. |
| 2 | An error occurred: bad arguments, missing input, I/O failure, a file that could not be parsed/verified, or a panic contained during formatting. Any file involved in an error is left untouched. |
Error beats would-change: a run with both reports 2.
Panic containment
Each per-file (and stdin) call into format_source runs inside
std::panic::catch_unwind. The default panic hook is swapped for a
no-op around that call (take_hook/set_hook, restored immediately
after) so the contained panic prints no backtrace noise; the payload
message is re-reported in lucisv's own error style:
error: rtl/bad.sv: panicked while formatting: <payload>
The file is left untouched, counted in the N files failed to format
summary, and the run continues and exits 2. A panic that aborts (e.g.
panic = "abort" profile) cannot be contained — that is inherent to
catch_unwind and accepted.
Handshakes
- Consumes
vlog_formatter::{format_source, Config}only. No change tovlog_formatterorvlog_parserwas needed or made; nothing incrates/vlog_parserorcrates/vlog_formatterwas touched. - Promises to future config discovery (TODO.md §3, not built here):
Options.stdin_filename: Option<String>is the path config discovery must search upward from when input comes from stdin. It is stored raw, exactly as the user typed it, and is never canonicalized or touched on disk by this feature. Config discovery should also reuseOptions.excludeas the CLI-supplied layer that overrides anexcludekey from a config file. - Promises to TODO.md §3's parallelism item:
catch_panicinmain.rsmutates the process-global panic hook. Before files are formatted on multiple threads, replace it with a hook installed once at startup (or drop the hook silencing) — otherwise concurrent take/set pairs race and can leave the no-op hook installed. - Promises to CI users: the exit-code table above is frozen; new modes must map onto 0/1/2 rather than adding codes.
Status / TODO
--diff: unified-style output, no writes, exit 1 on change, works in stdin mode, rejected together with--stdout.--stdin-filename <path>: used in error messages, diff header and check line; handshake for config discovery documented.--exclude <pattern>(repeatable), suffix/basename matching with*inside a component; excluded directories not descended into.- Exit-code contract documented here, in
--helpand in the top-levelREADME.md. - Panic containment via
catch_unwind+ silenced hook, counted as an error, exit 2. main.rssplit intoargs.rs/walk.rs/diff.rs+ driver (it would otherwise have passed ~400 lines).- Unit tests for the glob matcher, the diff renderer and
catch_panic; integration tests incrates/lucisv/tests/cli.rs. cargo test --workspace,cargo clippy --all-targets,cargo fmt --checkclean.- TODO.md: §1 panic containment, §2
--diffand--stdin-filename, §3 exit-code contract checked off. §3's.gitignoreitem is left unchecked — only the--excludehalf of it is done.
Work log
2026-08-18 — dev agent
- Read CLAUDE.md, README.md, TODO.md §1–§3 and the whole existing
main.rsbefore writing anything. Baseline confirmed green:cargo test --workspaceall pass,cargo fmt --checksilent,cargo clippy --all-targetshas 5 pre-existing warnings, all invlog_parser/vlog_formatter(2×if_same_then_else,manual_repeat_n,dead_codeonListItem.blank_before) and none inlucisv. - Split
main.rs(was 220 lines; the five items would have taken it past 400) intoargs.rs(option struct, parsing, help),walk.rs(file collection + the exclude matcher),diff.rs(unified diff) and a drivermain.rsthat keeps the original shape: collect files, loop, count changed/unchanged/errors, print a summary, map to an exit code. No behavior of the existing flags changed. - Diff algorithm. A full LCS over lines is O(n·m) memory, which is
not acceptable for a large netlist, and Myers is more machinery than
this warrants. Used instead a linear scan with a resynchronization
heuristic: on divergence, search outward for the smallest
(di, dj)such that the next 3 lines of both sides agree (or both sides end together), scanning up to 200 lines ahead; emitdideletions anddjinsertions and continue. Beyond 200 lines of divergence it gives up and dumps the remaining tails. That is ~50 lines and produces hunk-shaped output; the cost is that hunks are not guaranteed minimal. Documented under Assumptions. - Exclude matcher. Component-wise, with a small backtracking
*matcher (glob_component, 15 lines). The/-vs-no-/split keeps the common cases (build,*_generated.sv,rtl/gen) working without pulling in a glob crate, and matching per component means*cannot cross a separator for free. - Panic containment. Wrapped the
format_sourcecall in a genericcatch_panichelper so it could be unit-tested with a closure that panics rather than needing an input that actually crashes the formatter. Hook silencing is take/set around each call, which is only sound single-threaded — recorded as a handshake for the rayon item. - Chose to make
--checkwork in stdin mode too (it previously ignored the flag and always printed the formatted text). It is the obvious reading of the flag and editors'--stdin-filenameworkflows want it; noted here as a small behavior change to a previously undefined case. --diffwith--stdoutis a usage error rather than a silent precedence rule: both want stdout, and guessing would be worse than failing.- Top-level
README.md: added the new flags to the usage block and an exit-code table, per TODO.md §3's "document it in README and freeze it". - Tests:
crates/lucisv/tests/cli.rsdrives the real binary viaenv!("CARGO_BIN_EXE_lucisv"), with a hand-rolled tempdir understd::env::temp_dir()(unique name from pid + a counter, removed by aDropguard) so notempfiledependency is needed. All fixtures use trivial Verilog (module m;endmodule→module m;\nendmodule\n) so the tests do not move when the formatter's layout rules change. - Panic containment proven end-to-end, not just by unit test: copied
the workspace into the scratchpad (outside the repo), added
if source.contains("SABOTAGE") { panic!(...) }at the top offormat_sourcein the copy, and ran the resulting binary over a directory of three files. Result:error: …/boom.sv: panicked while formatting: sabotaged formatter: index out of bounds/2 files reformatted, 1 file failed to format, exit 2, no backtrace orthread 'main' panickednoise,boom.svbyte-identical afterwards and the other two files formatted normally. The copy was deleted afterwards; the repo tree was never modified. - Sanity-checked
--diffon thevlog_formatterfixtures (copied out and re-mangled): 9 hunks over 3 files, summary on stderr only, exit 1. As a bonus the output was accepted bypatch -p0 --dry-run— worth knowing, still not promised (see Assumptions). - The workspace was briefly uncompilable mid-run while the other agent
landed an
end_labelchange invlog_parser/vlog_formatter; waited it out rather than touching their crates. Final checks were re-run on the merged tree.
Results (workspace root, final):
cargo test --workspace: 69 passed, 0 failed — 18lucisvunit (args 4, walk 4, diff 6, panic/format 4), 12lucisvCLI integration, 3 + 1 + 2vlog_formatter, 19vlog_formatterverification, 14vlog_parser.cargo clippy --all-targets: no warnings fromlucisv. The 5 pre-existing warnings invlog_parser/vlog_formatterare unchanged from the baseline taken before this work.cargo fmt --check: clean (rancargo fmt -p lucisvonly, so no file owned by the other agent was reformatted).- Sizes:
main.rs231,args.rs156,diff.rs199,walk.rs129,tests/cli.rs261 lines. NoCargo.tomlchange was needed.
QA log
2026-08-18 — QA agent
Scope: crates/lucisv/** and this README only. Nothing in vlog_parser /
vlog_formatter was touched in the repo (a concurrent dev agent was
active there; the workspace failed to build on the first attempt with
errors in vlog_formatter::format.rs unrelated to lucisv — waited and
retried, second attempt built clean, confirming the failure was transient
and outside this feature's scope).
Build / lint / test — all green:
cargo test -p lucisv: 30 passed, 0 failed — 18 unit (main 4, args 4, walk 4, diff 6) + 12 CLI integration (tests/cli.rs). Matches the claimed counts exactly.cargo clippy -p lucisv --all-targets: zero warnings fromlucisv. Fullcargo clippy --all-targetsstill shows exactly 4 warnings, all invlog_parser/vlog_formatter(2×if_same_then_elseinvlog_parser/src/parser.rs:573,715,manual_repeat_ninvlog_formatter/src/printer.rs:91,dead_codeonListItem.blank_beforeinvlog_formatter/src/format.rs:94) — note: the Work log above says "5 pre-existing warnings" but lists only 4; today's run confirms 4. Nit, not fixed (not my log entry to edit).cargo fmt -p lucisv --check: clean, exit 0.- Module sizes, no-unwrap-outside-tests/main, doc comments: all comply
with CLAUDE.md as of this read.
main.rs231,args.rs156,diff.rs199,walk.rs129,tests/cli.rs261 lines. - TODO.md checkbox audit: §1 all four items
[x]; §2--diffand--stdin-filename[x], the other three (format-off, range formatting, alignment inference) correctly still[ ]; §3 exit-code contract[x], the.gitignore+--excludeitem still[ ]as a whole (only the--excludehalf is implemented) — matches the feature README's own claim exactly.
Diff correctness (patch round-trip), verified in scratchpad:
- Nontrivial multi-construct file (module + always block + assign):
lucisv --diffoutput applied cleanly withpatch -p0and byte-matchedlucisv --stdoutoutput. -
200-line gap between two independent single-line changes (256-line file, 250 filler lines between them): 2 separate hunks emitted, both applied cleanly via
patch -p0, round-tripped correctly. Bounded resync handles well-separated changes correctly. - Large contiguous divergence (184-line deeply-nested reindent, every
line's whitespace changed): collapsed to one big replacement hunk,
still applied cleanly via
patch -p0and round-tripped correctly — confirms the documented "coarser but still correct" behavior when resync can't find a tight sync point. - Empty file: diff is
@@ -1,0 +1,1 @@/+(formatter turns""into"\n"). Round-trips correctly viapatch -p0(patch prints "No such line 1 in input file, ignoring" but still produces the right result). - Already-formatted file:
--diffcorrectly prints nothing, exit 0.
FINDING (should-fix) — \ No newline at end of file breaks patch
applicability. crates/lucisv/src/diff.rs:40-46 (split_lines) pushes
the NO_NEWLINE pseudo-line into the same line stream as ordinary
content, so render_one_hunk (diff.rs:129-144) tags it with a regular
-/+ sign like any other line. Real unified diff / GNU patch expect
this marker as a bare, unprefixed line immediately following its
associated content line. Repro:
printf 'module m;endmodule' > old.sv # no trailing newline
lucisv --diff old.sv
produces:
@@ -1,2 +1,2 @@
-module m;endmodule
-\ No newline at end of file
+module m;
+endmodule
(note the leading - on the \ No newline... line — GNU diff never
prefixes it). Applying with patch -p0 fails: 1 out of 1 hunks failed, rejects saved to .rej. Reproduced in both directions (missing
newline in old, and missing newline only in old while new already ends
in one). This is within the documented Assumptions ("not promised
to be machine-applicable by patch"), so it is not a contract violation,
but it directly undercuts the dev work log's "bonus" observation that
patch -p0 --dry-run accepted the sanity-check diffs — that check
evidently didn't include a missing-final-newline case. Worth a follow-up
fix: don't tag NO_NEWLINE rows with a sign in render_one_hunk.
FINDING (should-fix, likely out of lucisv's scope) — stack overflow
aborts the whole batch, not just one file. A syntactically valid but
deeply nested input (150 levels of if (clk) begin ... end, 454 lines,
built in scratchpad — not committed anywhere) crashes the whole lucisv
process with thread 'main' has overflowed its stack / SIGABRT (exit
134), reproduced with plain format, --check, and --diff alike (i.e.
not a --diff-specific bug — it's in the parser/formatter's recursive
descent, crates/vlog_parser/crates/vlog_formatter, both out of this
feature's stated scope). Verified with a 2-file directory (one file
before the bad one in sort order, one bad file): the good file does
get formatted (files are processed in sorted order and writes happen
per-file before the crash), but the run aborts with no exit-code-2
summary at all — just the raw Rust runtime message — and any files
after the crash point are never processed. This is a real gap in claim
5's "other files still processed" promise: catch_unwind cannot ever
catch a stack overflow (this is not the panic = "abort" profile case
already carved out in Assumptions — stack overflow bypasses the panic
machinery entirely regardless of panic strategy). No code was corrupted
(hard invariant #1 holds — the crash happens before any write to the
offending file), but the process-level containment story is weaker than
"other files still processed" suggests for this trigger. Recommend the
Assumptions section explicitly name stack-overflow-from-recursion-depth
as a second, distinct uncontainable case alongside panic = "abort",
since deeply-nested generated RTL is a plausible real-world trigger
Filed here rather than fixed — the fix (bounded recursion / iterative
parsing) belongs in vlog_parser/vlog_formatter, outside this
feature's and this QA pass's scope.
--exclude edge cases, all verified in scratchpad:
--exclude '*'excludes every entry in the walked directory → "no Verilog files found", exit 2. Correct per the name-pattern-matches-any- entry semantics.--exclude <root-dir-basename>on the directory passed as the CLI input itself has no effect —is_excludedis only ever checked on entries found while walking, never on the walk root itself. Not a bug (matches "applied while walking a directory, to every entry" reasonably read), just confirming the edge case behaves as implied.--exclude 'sub1/b.sv'(slash pattern naming a specific file): excluded only that file via component-aligned suffix match, sibling files untouched. Matches claim 3.--exclude '**/x.sv':**is not specially handled (as documented — "No**") but its emergent behavior happens to match intuitive recursive-glob semantics for this shape, because the matcher is a suffix match plus directory-pruning: verified**/x.svexcludesa/b/x.sv(1 level) anda/b/c/x.sv(2 levels) alike, since only the immediate parent + basename are constrained and everything above that is outside the suffix window. A pattern with**in the middle (e.g.a/**/z.sv) would not get arbitrary-depth semantics (not tested live — reasoned fromwalk.rs:54-61's fixed-length trailing- component match), but this is already outside the documented contract. Nit-level observation for whoever eventually revisits the Assumptions wording, no action needed now.- Case sensitivity:
--exclude build_gen.svdoes not matchBUILD_gen.sv. Confirmed case-sensitive as documented.
--stdin-filename edge cases:
- Used correctly in error messages,
--diffheader, and--checkline (existing integration teststdin_mode_uses_stdin_filename_in_errorscovers all three; re-verified live). --stdin-filenamegiven without-as the sole input: silently ignored, file processed normally with no trace of the flag anywhere in output. Matches the documented "Silently ignored when not reading from stdin."
Flag combinations:
--check --difftogether: diff output replaces the "would reformat" line, exit 1 on change. Matches documented behavior exactly.--diffover a directory with one unparseable file: exit 2 (error outranks would-change, confirmed), and--diff's stdout still contains the valid patch for the file(s) that did succeed — each file is diffed independently; only the aggregate exit code reflects the error. Not documented explicitly either way, but seems like the right behavior and is not a finding.--(bare double dash) is not treated as an end-of-options marker —lucisv -- file.sverrors withunknown option: --(exit 2), sinceargs.rs:110rejects any unrecognized token starting with-. Not a regression from this feature (pre-existing hand-rolled parser behavior,args.rsreview confirms this pattern predates the diff/ exclude/stdin-filename additions) and not claimed anywhere in the feature contract, so not filed as a finding against this feature — noting only because it means a file whose name starts with-can never be passed tolucisv. Nit, out of this feature's scope.- Unknown flag (
--bogus-flag): clearerror: unknown option: --bogus-flag, exit 2.
Panic containment — hook swap/restore correctness, verified two ways:
- Static read of
catch_panic(main.rs:178-192): take/set/restore is fully contained within one function call and the process is single- threaded (confirmed:run_files/run_stdincallformat_containedin a plain sequentialforloop, no threads spawned anywhere incrates/lucisv), so there is no possible interleaving between two calls — each call's take_hook always sees the hook the previous call restored. The existingcatch_panic_is_reusableunit test (main.rs:218-224) covers this directly. - Independent live reproduction (beyond trusting the dev's work-log
claim): copied the workspace to scratchpad (never touched the real
repo), added the same
SABOTAGE-string panic trigger toformat_sourcein the copy, built, and ran over a 3-file directory with two panicking files (one before, one after a good file in sort order). Result: both panics reported cleanly and independently (error: .../a_bad1.sv: panicked while formatting: sabotaged formatter: SABOTAGE_ONE ...and the same forc_bad2.svwith its own distinct payload), no cross-contamination between the two error messages, no backtrace/thread 'main' panickednoise from either, the good file in between formatted correctly, both bad files byte-identical afterward, summary1 file reformatted, 2 files failed to format, exit 2. Confirms the swap/restore is sound across repeated catchable panics in one run (see the stack-overflow finding above for the one case where containment genuinely cannot apply). - The TODO §3 rayon handshake note in this README (parallelism will
break the global hook swap) is accurate and worth keeping as a
blocking note for whoever picks up
TODO.md§3's parallel-file- processing item — confirmed by re-readingcatch_panicthere is no thread-local isolation, so two concurrenttake_hook/set_hookpairs would race exactly as described.
Diff hunk math (hand-traced against diff.rs, cross-checked with
live output above): insert-only, delete-only, and change-at-EOF hunks
all produce internally consistent @@ -a,b +c,d @@ headers (line
numbers 1-based, counts matching the printed body exactly in each
traced case), and each traced case matches what patch -p0 accepted
live. No math errors found.
walk.rs glob matcher (glob_component, walk.rs:65-88) audited
by hand-tracing the backtracking algorithm (standard *-wildcard
match with single-star backtrack state) plus the unit tests already
in the file: * at start/middle/end, multiple * in one pattern,
empty pattern (matches() filters empty pattern components out before
calling glob_component, so an empty exclude pattern degrades to
"never matches" rather than reaching the glob matcher — confirmed
correct/safe by reading walk.rs:54-58), and pattern-longer-than-name
(covered by the pattern.len() > components.len() guard in matches()
at walk.rs:56, unrelated to glob_component itself, which has no
analogous guard needed since its own loop is bounded by name.len()).
No correctness issues found; matches the ~15-line claim (24 lines
including the doc comment, close enough).
Overall:
--diffunified output, exit codes, stdout/stderr split — PASS, with the should-fix\ No newline at end of filesign-prefix bug noted above (does not violate the documented "not patch-exact" contract, but is worth fixing).--stdin-filename— PASS, all documented behaviors verified.--excludematching semantics — PASS, all documented behaviors verified;**emergent behavior and no-effect-on-walk-root are nits worth a one-line Assumptions clarification, not bugs.- Exit codes 0/1/2, documented in
--help/README/feature README, error outranks would-change — PASS. - Panic containment — PASS for catchable panics (verified with two
sequential real panics, independent of the dev's own proof); gap
for stack overflow (see finding above) which is a real but
likely-out-of-scope-for-this-feature limitation worth documenting
explicitly rather than silently relying on the
panic = "abort"carve-out to cover it. - Test counts — PASS, 12 CLI integration + 18 unit tests, all green, exact match to the claim.
No fixes were made directly to crates/lucisv/** — nothing rose to the
"typo / missing assertion" bar for a QA-agent-authored fix; both
findings above are implementation decisions (diff renderer sign
handling; documenting an uncontainable-panic edge case) that belong to
the dev agent or the lead's review.
Review
2026-08-19 — lead. Verdict: accepted and committed, with one lead fix.
Solid, well-scoped work. The module split (args/walk/diff) was the right
call at this size, the hand-rolled matcher and diff are appropriately
small, and the flag-semantics decisions (--diff --stdout as a usage
error, summaries on stderr, --check honored on stdin) are all correct
calls that the tests pin down. The end-to-end panic proof on a sabotaged
scratchpad copy continues the standard the safety-net work set.
Lead fix while accepting (QA's should-fix, small and unambiguous):
\ No newline at end of fileis now emitted patch-correctly —diff.rspreviously treated the marker as a signed pseudo content line, whichpatch(1)rejects.split_linesnow keeps line terminators (so an unterminated final line compares unequal to its terminated twin, as GNU diff sees it) and the bare marker is emitted after the affected line, uncounted by the@@math. Verified by test and bypatch -p0 --dry-runaccepting both directions.
Dispositions on the other findings:
- Stack overflow on ~150-level nesting (QA's second should-fix): real
and important, but the root cause is unbounded recursion in
vlog_parser/the formatter walk, out of this feature's scope. Recorded as a new TODO §1 item (recursion-depth limit, ruff-style); the Assumptions carve-out forpanic = "abort"was honest but narrower than reality, and the TODO entry now names the gap precisely. - Panic-hook swap vs future parallelism: confirmed single-threaded today; the handshake note stands — the rayon item in TODO §3 must replace the take_hook/set_hook dance (set once at startup) when it lands.
- Nits (bare
--,**globs, warning-count arithmetic): noted, none actionable now;--handling can ride along with config discovery.