Add cli-polish: --diff, --stdin-filename, --exclude, panic containment
main.rs split into args/walk/diff modules, all std-only. --diff emits a patch-applicable unified diff (bounded-resync hunks, GNU-style missing-newline marker); --exclude is a small component-glob matcher that prunes directory walks; --stdin-filename names stdin buffers in messages; per-file catch_unwind turns formatter panics into ordinary errors. Exit-code contract (0/1/2) frozen and documented in --help and README. 12 CLI integration tests + 18 unit tests. Known gap found by QA, queued in TODO §1: deep nesting overflows the parser stack (uncatchable), needs an explicit recursion-depth limit. Dev: Opus agent; QA: Sonnet agent; review in docs/features/cli-polish/README.md (includes one lead fix: the no-final-newline marker is now emitted the way patch(1) expects). Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
d2cd44c428
commit
0a6c365ec2
8 files changed
+1522
-184
No files matched your search
@@ -12,10 +12,27 @@ vfmt rtl/ tb/top_tb.sv
|
||||
# check mode for CI (exit 1 if anything would change)
|
||||
vfmt --check rtl/
|
||||
|
||||
# pipe through stdin/stdout
|
||||
# print a unified diff instead of rewriting (also exit 1 if anything would change)
|
||||
vfmt --diff rtl/
|
||||
|
||||
# skip generated files while walking directories (repeatable)
|
||||
vfmt --exclude '*_gen.sv' --exclude build rtl/
|
||||
|
||||
# pipe through stdin/stdout; --stdin-filename names the buffer in messages
|
||||
cat foo.sv | vfmt -
|
||||
cat foo.sv | vfmt --stdin-filename rtl/foo.sv -
|
||||
```
|
||||
|
||||
### Exit codes (frozen contract — CI may depend on it)
|
||||
|
||||
| Code | Meaning |
|
||||
|---|---|
|
||||
| 0 | Success: files were formatted, or `--check`/`--diff` found nothing to change |
|
||||
| 1 | `--check`/`--diff` only: at least one file would be reformatted (nothing written) |
|
||||
| 2 | An error occurred (bad arguments, I/O, or a file that could not be formatted); every file involved in an error is left untouched |
|
||||
|
||||
An error outranks "would reformat": a run with both exits 2.
|
||||
|
||||
## Architecture (the ruff mapping)
|
||||
|
||||
The workspace mirrors ruff's crate layout — a comment-preserving parser, a
|
||||
|
||||
@@ -27,9 +27,15 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
failure, return the input unchanged *with a diagnostic and nonzero exit*,
|
||||
never partially formatted output. Parse errors already behave this way
|
||||
(README notes it); extend the same contract to the two checks above.
|
||||
- [ ] **[R] Panic containment.** ruff catches panics per-file and reports
|
||||
- [x] **[R] Panic containment.** ruff catches panics per-file and reports
|
||||
them as errors instead of killing the whole run. Wrap per-file work in
|
||||
`crates/vfmt/src/main.rs` with `std::panic::catch_unwind`.
|
||||
- [ ] **Recursion-depth limit in the parser.** Found by cli-polish QA:
|
||||
~150 levels of expression nesting overflow the stack and abort the whole
|
||||
process — uncatchable by `catch_unwind`, so mid-batch files after the
|
||||
crash never get processed. Add an explicit depth counter in
|
||||
`vlog_parser::parser` that returns a parse error past a documented limit
|
||||
(ruff does the same). Do the same in the formatter's recursive walk.
|
||||
|
||||
## 2. Formatter features
|
||||
|
||||
@@ -54,10 +60,10 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
and localparam/parameter lists. This needs original-spacing info
|
||||
preserved through the lexer — record "excess spaces before token" as
|
||||
trivia.
|
||||
- [ ] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix
|
||||
- [x] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix
|
||||
`patch` mode: print a unified diff instead of rewriting, for CI logs and
|
||||
code review.
|
||||
- [ ] **[R] `--stdin-filename <path>`.** Editors pipe buffer contents via
|
||||
- [x] **[R] `--stdin-filename <path>`.** Editors pipe buffer contents via
|
||||
stdin; the filename is needed for good error messages and (later)
|
||||
per-directory config resolution.
|
||||
|
||||
@@ -77,7 +83,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
- [ ] **[R] Respect `.gitignore`** and add `--exclude` globs when walking
|
||||
directories (`collect_files` in `main.rs` currently walks everything,
|
||||
including e.g. generated netlists).
|
||||
- [ ] **[V+R] Exit-code contract doc.** Already ruff-like (0 clean /
|
||||
- [x] **[V+R] Exit-code contract doc.** Already ruff-like (0 clean /
|
||||
1 would-reformat / 2 error) — document it in README and freeze it; CI
|
||||
scripts will depend on it.
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Hand-rolled command line parsing for the `vfmt` binary.
|
||||
|
||||
use vlog_formatter::Config;
|
||||
|
||||
/// Everything the driver needs to know about one invocation.
|
||||
pub struct Options {
|
||||
/// Don't write; report files that would be reformatted.
|
||||
pub check: bool,
|
||||
/// Don't write; print a unified diff of what would change.
|
||||
pub diff: bool,
|
||||
/// Print formatted output instead of rewriting files.
|
||||
pub stdout: bool,
|
||||
/// Path to report instead of `<stdin>` when input comes from stdin.
|
||||
/// Also the anchor for future per-directory config discovery.
|
||||
pub stdin_filename: Option<String>,
|
||||
/// Patterns skipped while walking directories.
|
||||
pub exclude: Vec<String>,
|
||||
/// Formatter configuration (line length, indent width).
|
||||
pub config: Config,
|
||||
/// Files, directories, or the single input `-`.
|
||||
pub inputs: Vec<String>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// True when this run must not modify any file.
|
||||
pub fn read_only(&self) -> bool {
|
||||
self.check || self.diff
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the `--help` text, including the frozen exit-code contract.
|
||||
pub fn print_help() {
|
||||
println!(
|
||||
"vfmt — a Verilog/SystemVerilog formatter
|
||||
|
||||
USAGE:
|
||||
vfmt [OPTIONS] <file|dir>...
|
||||
vfmt - read from stdin, write to stdout
|
||||
|
||||
OPTIONS:
|
||||
--check don't write; exit 1 if any file would be reformatted
|
||||
--diff don't write; print a unified diff of what would change
|
||||
--stdout print formatted output instead of rewriting files
|
||||
--exclude <PATTERN> skip matching paths when walking directories; may be
|
||||
repeated. A pattern with `/` matches a path suffix,
|
||||
otherwise it matches a file or directory name; `*`
|
||||
matches within one path component
|
||||
--stdin-filename <PATH> path to report in messages for input read from stdin
|
||||
--line-length <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
-h, --help show this help
|
||||
-V, --version show version
|
||||
|
||||
EXIT CODES:
|
||||
0 nothing to do: files were formatted, or --check/--diff found no change
|
||||
1 --check/--diff only: at least one file would be reformatted
|
||||
2 an error occurred (bad arguments, I/O, a file that could not be
|
||||
formatted); files involved in an error are left untouched"
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses `std::env::args()`. Exits the process directly for `--help`
|
||||
/// and `--version`, which have no useful `Options` to return.
|
||||
pub fn parse() -> Result<Options, String> {
|
||||
parse_from(std::env::args().skip(1))
|
||||
}
|
||||
|
||||
fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
let mut opts = Options {
|
||||
check: false,
|
||||
diff: false,
|
||||
stdout: false,
|
||||
stdin_filename: None,
|
||||
exclude: Vec::new(),
|
||||
config: Config::default(),
|
||||
inputs: Vec::new(),
|
||||
};
|
||||
let mut args = args;
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--check" => opts.check = true,
|
||||
"--diff" => opts.diff = true,
|
||||
"--stdout" => opts.stdout = true,
|
||||
"--exclude" => {
|
||||
let v = args.next().ok_or("--exclude requires a value")?;
|
||||
opts.exclude.push(v);
|
||||
}
|
||||
"--stdin-filename" => {
|
||||
let v = args.next().ok_or("--stdin-filename requires a value")?;
|
||||
opts.stdin_filename = Some(v);
|
||||
}
|
||||
"--line-length" => {
|
||||
let v = args.next().ok_or("--line-length requires a value")?;
|
||||
opts.config.max_width =
|
||||
v.parse().map_err(|_| format!("invalid line length: {v}"))?;
|
||||
}
|
||||
"--indent" => {
|
||||
let v = args.next().ok_or("--indent requires a value")?;
|
||||
opts.config.indent_width = v.parse().map_err(|_| format!("invalid indent: {v}"))?;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
std::process::exit(0);
|
||||
}
|
||||
"-V" | "--version" => {
|
||||
println!("vfmt {}", env!("CARGO_PKG_VERSION"));
|
||||
std::process::exit(0);
|
||||
}
|
||||
"-" => opts.inputs.push("-".to_string()),
|
||||
s if s.starts_with('-') => return Err(format!("unknown option: {s}")),
|
||||
s => opts.inputs.push(s.to_string()),
|
||||
}
|
||||
}
|
||||
if opts.inputs.is_empty() {
|
||||
return Err("no input files (try `vfmt --help`)".to_string());
|
||||
}
|
||||
if opts.diff && opts.stdout {
|
||||
return Err("--diff cannot be combined with --stdout".to_string());
|
||||
}
|
||||
Ok(opts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(args: &[&str]) -> Result<Options, String> {
|
||||
parse_from(args.iter().map(|s| s.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_repeated_excludes() {
|
||||
let opts = parse(&["--exclude", "build", "--exclude", "*_gen.sv", "rtl"]).unwrap();
|
||||
assert_eq!(opts.exclude, vec!["build", "*_gen.sv"]);
|
||||
assert_eq!(opts.inputs, vec!["rtl"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_and_stdout_conflict() {
|
||||
assert!(parse(&["--diff", "--stdout", "rtl"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_filename_is_stored_verbatim() {
|
||||
let opts = parse(&["--stdin-filename", "a/b.sv", "-"]).unwrap();
|
||||
assert_eq!(opts.stdin_filename.as_deref(), Some("a/b.sv"));
|
||||
assert!(!opts.read_only());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_value_is_an_error() {
|
||||
assert!(parse(&["--exclude"]).is_err());
|
||||
assert!(parse(&["--line-length"]).is_err());
|
||||
assert!(parse(&["--line-length", "wide", "rtl"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! A small line-oriented unified diff for `--diff`.
|
||||
//!
|
||||
//! The hunks are not a minimal edit script: on a divergence the two
|
||||
//! sides are resynchronized with a bounded forward search. That keeps
|
||||
//! the code short and the memory linear, at the cost of occasionally
|
||||
//! reporting a coarser change than GNU `diff` would.
|
||||
|
||||
/// Unchanged lines printed around each hunk.
|
||||
const CONTEXT: usize = 3;
|
||||
/// Unchanged lines that must line up before the sides count as resynced.
|
||||
const SYNC_RUN: usize = 3;
|
||||
/// How far ahead a resynchronization point is searched for.
|
||||
const MAX_SCAN: usize = 200;
|
||||
/// Pseudo-line standing in for a missing final newline.
|
||||
const NO_NEWLINE: &str = "\\ No newline at end of file";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Tag {
|
||||
Keep,
|
||||
Del,
|
||||
Ins,
|
||||
}
|
||||
|
||||
/// Renders the changes from `old` to `new` as a unified-style diff.
|
||||
/// Returns an empty string if the two texts are equal.
|
||||
pub fn unified(path: &str, old: &str, new: &str) -> String {
|
||||
if old == new {
|
||||
return String::new();
|
||||
}
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let edits = edits(&old, &new);
|
||||
let mut out = format!("--- {path}\n+++ {path}\n");
|
||||
render_hunks(&edits, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Splits into lines *keeping* each terminator, so a final line with no
|
||||
/// newline compares unequal to its terminated twin and shows up as a
|
||||
/// change, exactly as GNU diff treats it.
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find('\n').map_or(rest.len(), |p| p + 1);
|
||||
lines.push(&rest[..end]);
|
||||
rest = &rest[end..];
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn edits<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<(Tag, &'a str)> {
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < old.len() && j < new.len() {
|
||||
if old[i] == new[j] {
|
||||
out.push((Tag::Keep, old[i]));
|
||||
i += 1;
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((di, dj)) = resync(old, new, i, j) else { break };
|
||||
out.extend(old[i..i + di].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..j + dj].iter().map(|l| (Tag::Ins, *l)));
|
||||
i += di;
|
||||
j += dj;
|
||||
}
|
||||
out.extend(old[i..].iter().map(|l| (Tag::Del, *l)));
|
||||
out.extend(new[j..].iter().map(|l| (Tag::Ins, *l)));
|
||||
out
|
||||
}
|
||||
|
||||
/// Finds the smallest pair of skip counts that puts the two sides back
|
||||
/// in step, preferring the shortest total divergence.
|
||||
fn resync(old: &[&str], new: &[&str], i: usize, j: usize) -> Option<(usize, usize)> {
|
||||
for d in 1..=MAX_SCAN {
|
||||
for k in 0..=d {
|
||||
for (di, dj) in [(d, k), (k, d)] {
|
||||
if i + di <= old.len() && j + dj <= new.len() && in_step(old, new, i + di, j + dj) {
|
||||
return Some((di, dj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn in_step(old: &[&str], new: &[&str], i: usize, j: usize) -> bool {
|
||||
let available = (old.len() - i).min(new.len() - j);
|
||||
if available == 0 {
|
||||
// Both sides running out together is a valid resync point.
|
||||
return old.len() - i == new.len() - j;
|
||||
}
|
||||
(0..SYNC_RUN.min(available)).all(|k| old[i + k] == new[j + k])
|
||||
}
|
||||
|
||||
fn render_hunks(edits: &[(Tag, &str)], out: &mut String) {
|
||||
// Line numbers each edit occupies on the old and the new side.
|
||||
let mut rows = Vec::with_capacity(edits.len());
|
||||
let (mut old_no, mut new_no) = (1usize, 1usize);
|
||||
for &(tag, text) in edits {
|
||||
rows.push((tag, text, old_no, new_no));
|
||||
match tag {
|
||||
Tag::Keep => {
|
||||
old_no += 1;
|
||||
new_no += 1;
|
||||
}
|
||||
Tag::Del => old_no += 1,
|
||||
Tag::Ins => new_no += 1,
|
||||
}
|
||||
}
|
||||
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let Some(first) = (start..rows.len()).find(|&r| rows[r].0 != Tag::Keep) else { break };
|
||||
let mut last = first;
|
||||
// Extend while the next change is close enough that its context
|
||||
// would touch this hunk's.
|
||||
loop {
|
||||
let reach = (last + 2 * CONTEXT + 1).min(rows.len());
|
||||
match (last + 1..reach).find(|&r| rows[r].0 != Tag::Keep) {
|
||||
Some(next) => last = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
let from = first.saturating_sub(CONTEXT);
|
||||
let to = (last + CONTEXT + 1).min(rows.len());
|
||||
render_one_hunk(&rows[from..to], out);
|
||||
start = to;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_one_hunk(rows: &[(Tag, &str, usize, usize)], out: &mut String) {
|
||||
let old_count = rows.iter().filter(|r| r.0 != Tag::Ins).count();
|
||||
let new_count = rows.iter().filter(|r| r.0 != Tag::Del).count();
|
||||
let (old_start, new_start) = (rows[0].2, rows[0].3);
|
||||
out.push_str(&format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"));
|
||||
for &(tag, text, _, _) in rows {
|
||||
let sign = match tag {
|
||||
Tag::Keep => ' ',
|
||||
Tag::Del => '-',
|
||||
Tag::Ins => '+',
|
||||
};
|
||||
out.push(sign);
|
||||
match text.strip_suffix('\n') {
|
||||
Some(body) => {
|
||||
out.push_str(body);
|
||||
out.push('\n');
|
||||
}
|
||||
None => {
|
||||
// patch(1) expects the marker bare, on its own line,
|
||||
// directly after the unterminated line.
|
||||
out.push_str(text);
|
||||
out.push('\n');
|
||||
out.push_str(NO_NEWLINE);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn equal_texts_produce_nothing() {
|
||||
assert_eq!(unified("f.sv", "a\nb\n", "a\nb\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_change_keeps_context() {
|
||||
let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";
|
||||
let new = "1\n2\n3\n4\nX\n6\n7\n8\n9\n";
|
||||
let d = unified("f.sv", old, new);
|
||||
assert!(d.starts_with("--- f.sv\n+++ f.sv\n@@ -2,7 +2,7 @@\n"), "{d}");
|
||||
assert!(d.contains("\n-5\n+X\n"), "{d}");
|
||||
// Context is bounded: the first and last lines stay out of it.
|
||||
assert!(!d.contains("\n 1\n"), "{d}");
|
||||
assert!(!d.contains("\n 9\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_changes_become_separate_hunks() {
|
||||
let old: String = (0..40).map(|i| format!("{i}\n")).collect();
|
||||
let new = old.replace("\n1\n", "\nX\n").replace("\n30\n", "\nY\n");
|
||||
let d = unified("f.sv", &old, &new);
|
||||
assert_eq!(d.matches("@@ ").count(), 2, "{d}");
|
||||
assert!(d.contains("-1\n+X\n") && d.contains("-30\n+Y\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insertions_and_deletions_are_reported_separately() {
|
||||
let d = unified("f.sv", "a\nb\nc\n", "a\nb\nb2\nc\n");
|
||||
assert!(d.contains("+b2\n"), "{d}");
|
||||
assert!(!d.contains("-b\n"), "{d}");
|
||||
|
||||
let d = unified("f.sv", "a\nb\nc\nd\n", "a\nc\nd\n");
|
||||
assert!(d.contains("-b\n"), "{d}");
|
||||
// No insertions in the hunk body (the `+++` header line aside).
|
||||
assert!(!d.lines().skip(2).any(|l| l.starts_with('+')), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_final_newline_matches_patch_format() {
|
||||
// The unterminated line is the change; the marker follows it bare.
|
||||
let d = unified("f.sv", "a\nb", "a\nb\n");
|
||||
assert!(d.contains("-b\n\\ No newline at end of file\n+b\n"), "{d}");
|
||||
let d = unified("f.sv", "a\nb\n", "a\nb");
|
||||
assert!(d.contains("-b\n+b\n\\ No newline at end of file\n"), "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wholly_different_texts_diff_as_replacement() {
|
||||
let d = unified("f.sv", "a\nb\n", "x\ny\n");
|
||||
assert!(d.contains("-a\n-b\n+x\n+y\n"), "{d}");
|
||||
}
|
||||
}
|
||||
+190
-179
@@ -3,107 +3,27 @@
|
||||
//! Usage:
|
||||
//! vfmt [OPTIONS] <file|dir>... format files in place
|
||||
//! vfmt --check <file|dir>... exit 1 if anything would change
|
||||
//! vfmt --diff <file|dir>... print a unified diff of what would change
|
||||
//! vfmt - read stdin, write stdout
|
||||
//!
|
||||
//! Exit codes: 0 nothing to do, 1 `--check`/`--diff` found changes,
|
||||
//! 2 an error occurred (the affected files are left untouched).
|
||||
|
||||
mod args;
|
||||
mod diff;
|
||||
mod walk;
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use args::Options;
|
||||
use vlog_formatter::{format_source, Config};
|
||||
|
||||
const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
|
||||
struct Options {
|
||||
check: bool,
|
||||
stdout: bool,
|
||||
config: Config,
|
||||
inputs: Vec<String>,
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
println!(
|
||||
"vfmt — a Verilog/SystemVerilog formatter
|
||||
|
||||
USAGE:
|
||||
vfmt [OPTIONS] <file|dir>...
|
||||
vfmt - read from stdin, write to stdout
|
||||
|
||||
OPTIONS:
|
||||
--check don't write; exit 1 if any file would be reformatted
|
||||
--stdout print formatted output instead of rewriting files
|
||||
--line-length <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
-h, --help show this help
|
||||
-V, --version show version"
|
||||
);
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Options, String> {
|
||||
let mut opts =
|
||||
Options { check: false, stdout: false, config: Config::default(), inputs: Vec::new() };
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--check" => opts.check = true,
|
||||
"--stdout" => opts.stdout = true,
|
||||
"--line-length" => {
|
||||
let v = args.next().ok_or("--line-length requires a value")?;
|
||||
opts.config.max_width =
|
||||
v.parse().map_err(|_| format!("invalid line length: {v}"))?;
|
||||
}
|
||||
"--indent" => {
|
||||
let v = args.next().ok_or("--indent requires a value")?;
|
||||
opts.config.indent_width = v.parse().map_err(|_| format!("invalid indent: {v}"))?;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
print_help();
|
||||
std::process::exit(0);
|
||||
}
|
||||
"-V" | "--version" => {
|
||||
println!("vfmt {}", env!("CARGO_PKG_VERSION"));
|
||||
std::process::exit(0);
|
||||
}
|
||||
"-" => opts.inputs.push("-".to_string()),
|
||||
s if s.starts_with('-') => return Err(format!("unknown option: {s}")),
|
||||
s => opts.inputs.push(s.to_string()),
|
||||
}
|
||||
}
|
||||
if opts.inputs.is_empty() {
|
||||
return Err("no input files (try `vfmt --help`)".to_string());
|
||||
}
|
||||
Ok(opts)
|
||||
}
|
||||
|
||||
fn collect_files(input: &str, files: &mut Vec<PathBuf>) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
walk_dir(path, files).map_err(|e| format!("{input}: {e}"))?;
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
} else {
|
||||
return Err(format!("{input}: no such file or directory"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn walk_dir(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
walk_dir(&path, files)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
use walk::{collect_files, EXTENSIONS};
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let opts = match parse_args() {
|
||||
let opts = match args::parse() {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -111,104 +31,164 @@ fn main() -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
// stdin mode
|
||||
if opts.inputs.len() == 1 && opts.inputs[0] == "-" {
|
||||
let mut src = String::new();
|
||||
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
|
||||
eprintln!("error: reading stdin: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
match format_source(&src, &opts.config) {
|
||||
Ok(out) => {
|
||||
print!("{out}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("error: <stdin>: {e}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
run_stdin(&opts)
|
||||
} else {
|
||||
let mut files = Vec::new();
|
||||
for input in &opts.inputs {
|
||||
if input == "-" {
|
||||
eprintln!("error: `-` cannot be combined with file arguments");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
if let Err(e) = collect_files(input, &mut files) {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
if files.is_empty() {
|
||||
eprintln!("error: no Verilog files found (extensions: {})", EXTENSIONS.join(", "));
|
||||
run_files(&opts)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_stdin(opts: &Options) -> ExitCode {
|
||||
let name = opts.stdin_filename.as_deref().unwrap_or("<stdin>");
|
||||
let mut src = String::new();
|
||||
if let Err(e) = std::io::stdin().read_to_string(&mut src) {
|
||||
eprintln!("error: reading stdin: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
let out = match format_contained(&src, &opts.config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {name}: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
if !opts.read_only() {
|
||||
print!("{out}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if out == src {
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if opts.diff {
|
||||
print!("{}", diff::unified(name, &src, &out));
|
||||
} else {
|
||||
println!("would reformat: {name}");
|
||||
}
|
||||
ExitCode::from(1)
|
||||
}
|
||||
|
||||
let mut changed = 0usize;
|
||||
let mut unchanged = 0usize;
|
||||
let mut errors = 0usize;
|
||||
for file in &files {
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let out = match format_source(&src, &opts.config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if opts.stdout {
|
||||
print!("{out}");
|
||||
continue;
|
||||
}
|
||||
if out == src {
|
||||
unchanged += 1;
|
||||
continue;
|
||||
}
|
||||
changed += 1;
|
||||
if opts.check {
|
||||
println!("would reformat: {}", file.display());
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
fn run_files(opts: &Options) -> ExitCode {
|
||||
let files = match gather(opts) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
|
||||
let mut changed = 0usize;
|
||||
let mut unchanged = 0usize;
|
||||
let mut errors = 0usize;
|
||||
for file in &files {
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let out = match format_contained(&src, &opts.config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if opts.stdout {
|
||||
print!("{out}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if !opts.stdout {
|
||||
let verb = if opts.check { "would be reformatted" } else { "reformatted" };
|
||||
let mut summary = Vec::new();
|
||||
if changed > 0 {
|
||||
summary.push(format!("{changed} file{} {verb}", plural(changed)));
|
||||
}
|
||||
if unchanged > 0 {
|
||||
summary.push(format!("{unchanged} file{} left unchanged", plural(unchanged)));
|
||||
}
|
||||
if errors > 0 {
|
||||
// Parse errors, I/O errors and failed safety checks all land
|
||||
// here; in every case the file was left untouched.
|
||||
summary.push(format!("{errors} file{} failed to format", plural(errors)));
|
||||
}
|
||||
if !summary.is_empty() {
|
||||
eprintln!("{}", summary.join(", "));
|
||||
}
|
||||
if out == src {
|
||||
unchanged += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if errors > 0 {
|
||||
ExitCode::from(2)
|
||||
} else if opts.check && changed > 0 {
|
||||
ExitCode::from(1)
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
changed += 1;
|
||||
if opts.diff {
|
||||
print!("{}", diff::unified(&file.display().to_string(), &src, &out));
|
||||
} else if opts.check {
|
||||
println!("would reformat: {}", file.display());
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if !opts.stdout {
|
||||
report(opts, changed, unchanged, errors);
|
||||
}
|
||||
|
||||
if errors > 0 {
|
||||
ExitCode::from(2)
|
||||
} else if opts.read_only() && changed > 0 {
|
||||
ExitCode::from(1)
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
fn gather(opts: &Options) -> Result<Vec<PathBuf>, String> {
|
||||
let mut files = Vec::new();
|
||||
for input in &opts.inputs {
|
||||
if input == "-" {
|
||||
return Err("`-` cannot be combined with file arguments".to_string());
|
||||
}
|
||||
collect_files(input, &opts.exclude, &mut files)?;
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Err(format!("no Verilog files found (extensions: {})", EXTENSIONS.join(", ")));
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn report(opts: &Options, changed: usize, unchanged: usize, errors: usize) {
|
||||
let verb = if opts.read_only() { "would be reformatted" } else { "reformatted" };
|
||||
let mut summary = Vec::new();
|
||||
if changed > 0 {
|
||||
summary.push(format!("{changed} file{} {verb}", plural(changed)));
|
||||
}
|
||||
if unchanged > 0 {
|
||||
summary.push(format!("{unchanged} file{} left unchanged", plural(unchanged)));
|
||||
}
|
||||
if errors > 0 {
|
||||
// Parse errors, I/O errors, failed safety checks and contained
|
||||
// panics all land here; in every case the file was left untouched.
|
||||
summary.push(format!("{errors} file{} failed to format", plural(errors)));
|
||||
}
|
||||
if !summary.is_empty() {
|
||||
eprintln!("{}", summary.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats one source text, reporting a panic inside the formatter as an
|
||||
/// ordinary error so the rest of the run can continue.
|
||||
fn format_contained(src: &str, config: &Config) -> Result<String, String> {
|
||||
match catch_panic(|| format_source(src, config)) {
|
||||
Ok(Ok(out)) => Ok(out),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
Err(msg) => Err(format!("panicked while formatting: {msg}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f`, turning a panic into `Err(message)`. The default panic hook
|
||||
/// is silenced for the duration so a contained panic prints no backtrace
|
||||
/// noise of its own. Sound only while vfmt formats on a single thread —
|
||||
/// see the feature README's handshake with the parallelism work.
|
||||
fn catch_panic<T>(f: impl FnOnce() -> T) -> Result<T, String> {
|
||||
let hook = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(|_| {}));
|
||||
let result = std::panic::catch_unwind(AssertUnwindSafe(f));
|
||||
std::panic::set_hook(hook);
|
||||
result.map_err(|payload| {
|
||||
if let Some(s) = payload.downcast_ref::<&str>() {
|
||||
(*s).to_string()
|
||||
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||
s.clone()
|
||||
} else {
|
||||
"unknown panic".to_string()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn plural(n: usize) -> &'static str {
|
||||
@@ -218,3 +198,34 @@ fn plural(n: usize) -> &'static str {
|
||||
"s"
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn catch_panic_returns_values_unchanged() {
|
||||
assert_eq!(catch_panic(|| 1 + 1), Ok(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_panic_reports_the_payload() {
|
||||
assert_eq!(catch_panic(|| panic!("boom")), Err("boom".to_string()));
|
||||
let n = 7;
|
||||
assert_eq!(catch_panic(|| panic!("boom {n}")), Err("boom 7".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_panic_is_reusable() {
|
||||
// The hook swap must be balanced, so a second contained panic
|
||||
// behaves exactly like the first.
|
||||
assert_eq!(catch_panic(|| panic!("first")), Err("first".to_string()));
|
||||
assert_eq!(catch_panic(|| panic!("second")), Err("second".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_contained_reports_parse_errors() {
|
||||
let err = format_contained("module", &Config::default()).unwrap_err();
|
||||
assert!(err.contains("parse error"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! File discovery: directory walking and `--exclude` matching.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions vfmt formats when walking a directory.
|
||||
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
|
||||
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
||||
/// it if it is a directory. Exclude patterns apply to directory walks
|
||||
/// only — a path named on the command line is always formatted.
|
||||
pub fn collect_files(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
files: &mut Vec<PathBuf>,
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
walk_dir(path, exclude, files).map_err(|e| format!("{input}: {e}"))?;
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
} else {
|
||||
return Err(format!("{input}: no such file or directory"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn walk_dir(dir: &Path, exclude: &[String], files: &mut Vec<PathBuf>) -> std::io::Result<()> {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, exclude) {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
walk_dir(&path, exclude, files)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True if `path` matches any exclude pattern. A pattern containing `/`
|
||||
/// is matched against the path's trailing components; one without is
|
||||
/// matched against the final component only.
|
||||
pub fn is_excluded(path: &Path, exclude: &[String]) -> bool {
|
||||
let components: Vec<&str> = path.iter().filter_map(|c| c.to_str()).collect();
|
||||
exclude.iter().any(|pattern| matches(pattern, &components))
|
||||
}
|
||||
|
||||
fn matches(pattern: &str, components: &[&str]) -> bool {
|
||||
let pattern: Vec<&str> = pattern.split('/').filter(|p| !p.is_empty()).collect();
|
||||
if pattern.is_empty() || pattern.len() > components.len() {
|
||||
return false;
|
||||
}
|
||||
let tail = &components[components.len() - pattern.len()..];
|
||||
pattern.iter().zip(tail).all(|(p, c)| glob_component(p, c))
|
||||
}
|
||||
|
||||
/// Matches one path component against a pattern in which `*` stands for
|
||||
/// any run of characters (including none). No other metacharacters.
|
||||
fn glob_component(pattern: &str, name: &str) -> bool {
|
||||
let (pattern, name) = (pattern.as_bytes(), name.as_bytes());
|
||||
let (mut p, mut n) = (0, 0);
|
||||
// Position of the last `*` seen, and how much of `name` it had
|
||||
// consumed at that point, so a failed match can backtrack into it.
|
||||
let (mut star, mut consumed) = (None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && pattern[p] == b'*' {
|
||||
star = Some(p);
|
||||
consumed = n;
|
||||
p += 1;
|
||||
} else if p < pattern.len() && pattern[p] == name[n] {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if let Some(s) = star {
|
||||
p = s + 1;
|
||||
consumed += 1;
|
||||
n = consumed;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&b| b == b'*')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn excluded(path: &str, pattern: &str) -> bool {
|
||||
is_excluded(Path::new(path), &[pattern.to_string()])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_patterns_match_at_any_depth() {
|
||||
assert!(excluded("rtl/build", "build"));
|
||||
assert!(excluded("rtl/a/b/gen.sv", "gen.sv"));
|
||||
assert!(!excluded("rtl/building", "build"));
|
||||
assert!(!excluded("build/rtl", "rtl.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_stays_inside_one_component() {
|
||||
assert!(excluded("rtl/foo_gen.sv", "*_gen.sv"));
|
||||
assert!(excluded("rtl/foo_gen.sv", "*"));
|
||||
assert!(!excluded("rtl/foo_gen.sv", "rtl*sv"));
|
||||
assert!(excluded("rtl/foo_gen.sv", "rtl/*sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_patterns_match_a_path_suffix() {
|
||||
assert!(excluded("a/b/gen/rtl", "gen/rtl"));
|
||||
assert!(excluded("a/b/gen/rtl/x.sv", "gen/*/x.sv"));
|
||||
assert!(!excluded("a/b/gen/other", "gen/rtl"));
|
||||
assert!(!excluded("gen/rtl", "b/gen/rtl"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_handles_repeats_and_empty_matches() {
|
||||
assert!(excluded("a/xxxy", "*y"));
|
||||
assert!(excluded("a/y", "*y"));
|
||||
assert!(excluded("a/ab", "a*b*"));
|
||||
assert!(!excluded("a/xxx", "*y"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! End-to-end tests that drive the real `vfmt` binary.
|
||||
//!
|
||||
//! Fixtures use the most trivial Verilog possible so these tests stay
|
||||
//! stable while the formatter's layout rules evolve.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const VFMT: &str = env!("CARGO_BIN_EXE_vfmt");
|
||||
/// Formats to `FORMATTED`: the only change is the newline before `endmodule`.
|
||||
const UNFORMATTED: &str = "module m;endmodule\n";
|
||||
const FORMATTED: &str = "module m;\nendmodule\n";
|
||||
/// Truncated header — the parser cannot recover from this.
|
||||
const UNPARSEABLE: &str = "module\n";
|
||||
|
||||
/// A throwaway directory under the system temp dir, removed on drop.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!("vfmt-cli-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, contents: &str) -> String {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("create parent dir");
|
||||
}
|
||||
std::fs::write(&path, contents).expect("write fixture");
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn read(&self, rel: &str) -> String {
|
||||
std::fs::read_to_string(self.path.join(rel)).expect("read fixture")
|
||||
}
|
||||
|
||||
fn root(&self) -> String {
|
||||
self.path.to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[&str]) -> Output {
|
||||
Command::new(VFMT).args(args).output().expect("run vfmt")
|
||||
}
|
||||
|
||||
fn run_with_stdin(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(VFMT)
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn vfmt");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
child.wait_with_output().expect("run vfmt")
|
||||
}
|
||||
|
||||
fn code(out: &Output) -> i32 {
|
||||
out.status.code().expect("exit code")
|
||||
}
|
||||
|
||||
fn stdout(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stdout).into_owned()
|
||||
}
|
||||
|
||||
fn stderr(out: &Output) -> String {
|
||||
String::from_utf8_lossy(&out.stderr).into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_files_in_place() {
|
||||
let dir = TempDir::new("inplace");
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
dir.write("nested/b.v", UNFORMATTED);
|
||||
dir.write("notes.txt", "not verilog\n");
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("nested/b.v"), FORMATTED);
|
||||
assert_eq!(dir.read("notes.txt"), "not verilog\n", "non-Verilog files are not touched");
|
||||
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
|
||||
|
||||
// Second run is a no-op: nothing left to change.
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0);
|
||||
assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_without_writing() {
|
||||
let dir = TempDir::new("check");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 1, "would-change must exit 1");
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
assert_eq!(dir.read("a.sv"), UNFORMATTED, "--check must not write");
|
||||
|
||||
dir.write("a.sv", FORMATTED);
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 0, "nothing to change must exit 0");
|
||||
assert_eq!(stdout(&out), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_prints_a_unified_diff_without_writing() {
|
||||
let dir = TempDir::new("diff");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--diff", &path]);
|
||||
assert_eq!(code(&out), 1, "would-change must exit 1");
|
||||
assert_eq!(dir.read("a.sv"), UNFORMATTED, "--diff must not write");
|
||||
|
||||
let text = stdout(&out);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines[0], format!("--- {path}"), "{text}");
|
||||
assert_eq!(lines[1], format!("+++ {path}"), "{text}");
|
||||
assert!(lines[2].starts_with("@@ ") && lines[2].ends_with(" @@"), "{text}");
|
||||
assert!(lines.contains(&"-module m;endmodule"), "{text}");
|
||||
assert!(lines.contains(&"+module m;"), "{text}");
|
||||
assert!(lines.contains(&"+endmodule"), "{text}");
|
||||
// The summary goes to stderr so stdout is a clean patch.
|
||||
assert!(stderr(&out).contains("would be reformatted"), "{}", stderr(&out));
|
||||
|
||||
dir.write("a.sv", FORMATTED);
|
||||
let out = run(&["--diff", &path]);
|
||||
assert_eq!(code(&out), 0);
|
||||
assert_eq!(stdout(&out), "", "an unchanged file prints no diff");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_conflicts_with_stdout() {
|
||||
let dir = TempDir::new("diffconflict");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
let out = run(&["--diff", "--stdout", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).contains("--diff cannot be combined with --stdout"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_mode_uses_stdin_filename_in_errors() {
|
||||
let out = run_with_stdin(&["-"], UNPARSEABLE);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).starts_with("error: <stdin>: "), "{}", stderr(&out));
|
||||
|
||||
let out = run_with_stdin(&["--stdin-filename", "rtl/top.sv", "-"], UNPARSEABLE);
|
||||
assert_eq!(code(&out), 2);
|
||||
assert!(stderr(&out).starts_with("error: rtl/top.sv: "), "{}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("<stdin>"), "{}", stderr(&out));
|
||||
assert!(!std::path::Path::new("rtl/top.sv").exists(), "--stdin-filename must not touch disk");
|
||||
|
||||
// It also names the buffer in --diff and --check output.
|
||||
let out = run_with_stdin(&["--diff", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert!(stdout(&out).starts_with("--- rtl/top.sv\n+++ rtl/top.sv\n"), "{}", stdout(&out));
|
||||
|
||||
let out = run_with_stdin(&["--check", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED);
|
||||
assert_eq!(code(&out), 1);
|
||||
assert_eq!(stdout(&out), "would reformat: rtl/top.sv\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_mode_formats_to_stdout() {
|
||||
let out = run_with_stdin(&["-"], UNFORMATTED);
|
||||
assert_eq!(code(&out), 0);
|
||||
assert_eq!(stdout(&out), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclude_skips_files_and_directories() {
|
||||
let dir = TempDir::new("exclude");
|
||||
dir.write("keep.sv", UNFORMATTED);
|
||||
dir.write("skip_gen.sv", UNFORMATTED);
|
||||
dir.write("build/inner.sv", UNFORMATTED);
|
||||
dir.write("sub/keep.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--exclude", "*_gen.sv", "--exclude", "build", &dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("keep.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("sub/keep.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("skip_gen.sv"), UNFORMATTED, "name glob must be excluded");
|
||||
assert_eq!(dir.read("build/inner.sv"), UNFORMATTED, "excluded dir is not descended into");
|
||||
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclude_matches_a_path_suffix_when_it_contains_a_slash() {
|
||||
let dir = TempDir::new("excludepath");
|
||||
dir.write("gen/rtl/a.sv", UNFORMATTED);
|
||||
dir.write("gen/hand/b.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--exclude", "gen/rtl", &dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("gen/rtl/a.sv"), UNFORMATTED);
|
||||
assert_eq!(dir.read("gen/hand/b.sv"), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exclude_does_not_apply_to_explicitly_named_files() {
|
||||
let dir = TempDir::new("excludeexplicit");
|
||||
let path = dir.write("skip_gen.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--exclude", "*_gen.sv", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("skip_gen.sv"), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unformattable_file_exits_2_and_is_left_untouched() {
|
||||
let dir = TempDir::new("badparse");
|
||||
dir.write("bad.sv", UNPARSEABLE);
|
||||
dir.write("good.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 2, "an error must exit 2");
|
||||
assert_eq!(dir.read("bad.sv"), UNPARSEABLE, "a file that fails to format is not rewritten");
|
||||
assert_eq!(dir.read("good.sv"), FORMATTED, "other files are still formatted");
|
||||
let err = stderr(&out);
|
||||
assert!(err.contains("bad.sv: parse error"), "{err}");
|
||||
assert!(err.contains("1 file failed to format"), "{err}");
|
||||
|
||||
// An error outranks "would reformat" in --check and --diff too.
|
||||
dir.write("good.sv", UNFORMATTED);
|
||||
assert_eq!(code(&run(&["--check", &dir.root()])), 2);
|
||||
assert_eq!(code(&run(&["--diff", &dir.root()])), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_errors_exit_2() {
|
||||
assert_eq!(code(&run(&[])), 2, "no inputs");
|
||||
assert_eq!(code(&run(&["--nope", "x.sv"])), 2, "unknown option");
|
||||
assert_eq!(code(&run(&["--exclude"])), 2, "missing option value");
|
||||
assert_eq!(code(&run(&["/definitely/not/here.sv"])), 2, "missing input file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_documents_the_exit_codes() {
|
||||
let out = run(&["--help"]);
|
||||
assert_eq!(code(&out), 0);
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("EXIT CODES:"), "{text}");
|
||||
for flag in ["--check", "--diff", "--exclude", "--stdin-filename"] {
|
||||
assert!(text.contains(flag), "help is missing {flag}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
# cli-polish
|
||||
|
||||
## Goal
|
||||
|
||||
The small ruff-inspired CLI items from `TODO.md` §1–§3 that make `vfmt`
|
||||
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
|
||||
|
||||
- **`--diff` does 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 by `patch`; 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 `\n` gets a pseudo-line `\ No newline at end of file`
|
||||
appended, so "only the trailing newline changed" still produces a
|
||||
visible hunk instead of an empty diff.
|
||||
- **`--exclude` is 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.** `--exclude` only
|
||||
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_panic` swaps 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 line
|
||||
```
|
||||
|
||||
The 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`, so `vfmt --diff … > patch.txt` captures
|
||||
only diff text.
|
||||
- Exit code: `1` if any file would change, `0` if none would, `2` if any
|
||||
file errored (error wins over "would change").
|
||||
- `--check --diff` together: the diff replaces the
|
||||
`would reformat: <path>` lines; semantics are otherwise identical.
|
||||
- `--diff --stdout` is rejected as a usage error (exit 2) — they ask for
|
||||
two different things on stdout.
|
||||
- In stdin mode `--diff` diffs 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 `--diff`
|
||||
header and `--check` report 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/rtl` matches `a/b/gen/rtl/x.sv`'s directory
|
||||
`a/b/gen/rtl`, and does not match `gen/other`.
|
||||
- A pattern **without `/`** is matched against the **entry's name**
|
||||
only: `build` matches any file or directory named `build`;
|
||||
`*_pkg.sv` matches 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 `--exclude` pattern.
|
||||
|
||||
### 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 vfmt'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
|
||||
to `vlog_formatter` or `vlog_parser` was needed or made; nothing in
|
||||
`crates/vlog_parser` or `crates/vlog_formatter` was 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 reuse
|
||||
`Options.exclude` as the CLI-supplied layer that overrides an
|
||||
`exclude` key from a config file.
|
||||
- **Promises to TODO.md §3's parallelism item:** `catch_panic` in
|
||||
`main.rs` mutates 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
|
||||
|
||||
- [x] `--diff`: unified-style output, no writes, exit 1 on change,
|
||||
works in stdin mode, rejected together with `--stdout`.
|
||||
- [x] `--stdin-filename <path>`: used in error messages, diff header and
|
||||
check line; handshake for config discovery documented.
|
||||
- [x] `--exclude <pattern>` (repeatable), suffix/basename matching with
|
||||
`*` inside a component; excluded directories not descended into.
|
||||
- [x] Exit-code contract documented here, in `--help` and in the
|
||||
top-level `README.md`.
|
||||
- [x] Panic containment via `catch_unwind` + silenced hook, counted as
|
||||
an error, exit 2.
|
||||
- [x] `main.rs` split into `args.rs` / `walk.rs` / `diff.rs` + driver
|
||||
(it would otherwise have passed ~400 lines).
|
||||
- [x] Unit tests for the glob matcher, the diff renderer and
|
||||
`catch_panic`; integration tests in `crates/vfmt/tests/cli.rs`.
|
||||
- [x] `cargo test --workspace`, `cargo clippy --all-targets`,
|
||||
`cargo fmt --check` clean.
|
||||
- [x] TODO.md: §1 panic containment, §2 `--diff` and `--stdin-filename`,
|
||||
§3 exit-code contract checked off. §3's `.gitignore` item is left
|
||||
unchecked — only the `--exclude` half 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.rs` before writing anything. Baseline confirmed green:
|
||||
`cargo test --workspace` all pass, `cargo fmt --check` silent,
|
||||
`cargo clippy --all-targets` has 5 pre-existing warnings, all in
|
||||
`vlog_parser`/`vlog_formatter` (2× `if_same_then_else`,
|
||||
`manual_repeat_n`, `dead_code` on `ListItem.blank_before`) and none in
|
||||
`vfmt`.
|
||||
- Split `main.rs` (was 220 lines; the five items would have taken it
|
||||
past 400) into `args.rs` (option struct, parsing, help), `walk.rs`
|
||||
(file collection + the exclude matcher), `diff.rs` (unified diff) and
|
||||
a driver `main.rs` that 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; emit `di` deletions and
|
||||
`dj` insertions 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_source` call in a generic
|
||||
`catch_panic` helper 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 `--check` work 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-filename` workflows want it;
|
||||
noted here as a small behavior change to a previously undefined case.
|
||||
- `--diff` with `--stdout` is 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/vfmt/tests/cli.rs` drives the real binary via
|
||||
`env!("CARGO_BIN_EXE_vfmt")`, with a hand-rolled tempdir under
|
||||
`std::env::temp_dir()` (unique name from pid + a counter, removed by a
|
||||
`Drop` guard) so no `tempfile` dependency 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 of
|
||||
`format_source` in 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 or `thread 'main' panicked` noise, `boom.sv`
|
||||
byte-identical afterwards and the other two files formatted normally.
|
||||
The copy was deleted afterwards; the repo tree was never modified.
|
||||
- Sanity-checked `--diff` on the `vlog_formatter` fixtures (copied out
|
||||
and re-mangled): 9 hunks over 3 files, summary on stderr only, exit 1.
|
||||
As a bonus the output was accepted by `patch -p0 --dry-run` — worth
|
||||
knowing, still not promised (see Assumptions).
|
||||
- The workspace was briefly uncompilable mid-run while the other agent
|
||||
landed an `end_label` change in `vlog_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** — 18 `vfmt` unit
|
||||
(args 4, walk 4, diff 6, panic/format 4), 12 `vfmt` CLI integration,
|
||||
3 + 1 + 2 `vlog_formatter`, 19 `vlog_formatter` verification, 14
|
||||
`vlog_parser`.
|
||||
- `cargo clippy --all-targets`: no warnings from `vfmt`. The 5
|
||||
pre-existing warnings in `vlog_parser`/`vlog_formatter` are unchanged
|
||||
from the baseline taken before this work.
|
||||
- `cargo fmt --check`: clean (ran `cargo fmt -p vfmt` only, so no file
|
||||
owned by the other agent was reformatted).
|
||||
- Sizes: `main.rs` 231, `args.rs` 156, `diff.rs` 199, `walk.rs` 129,
|
||||
`tests/cli.rs` 261 lines. No `Cargo.toml` change was needed.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-18 — QA agent
|
||||
|
||||
Scope: `crates/vfmt/**` 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 `vfmt` — 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 vfmt`: **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 vfmt --all-targets`: zero warnings from `vfmt`. Full
|
||||
`cargo clippy --all-targets` still shows exactly 4 warnings, all in
|
||||
`vlog_parser`/`vlog_formatter` (2× `if_same_then_else` in
|
||||
`vlog_parser/src/parser.rs:573,715`, `manual_repeat_n` in
|
||||
`vlog_formatter/src/printer.rs:91`, `dead_code` on `ListItem.blank_before`
|
||||
in `vlog_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 vfmt --check`: clean, exit 0.
|
||||
- Module sizes, no-unwrap-outside-tests/main, doc comments: all comply
|
||||
with CLAUDE.md as of this read. `main.rs` 231, `args.rs` 156, `diff.rs`
|
||||
199, `walk.rs` 129, `tests/cli.rs` 261 lines.
|
||||
- TODO.md checkbox audit: §1 all four items `[x]`; §2 `--diff` and
|
||||
`--stdin-filename` `[x]`, the other three (`format-off`, range
|
||||
formatting, alignment inference) correctly still `[ ]`; §3 exit-code
|
||||
contract `[x]`, the `.gitignore`+`--exclude` item still `[ ]` as a
|
||||
whole (only the `--exclude` half 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):
|
||||
`vfmt --diff` output applied cleanly with `patch -p0` and byte-matched
|
||||
`vfmt --stdout` output.
|
||||
- >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 -p0` and 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 via `patch -p0` (patch prints "No such
|
||||
line 1 in input file, ignoring" but still produces the right result).
|
||||
- Already-formatted file: `--diff` correctly prints nothing, exit 0.
|
||||
|
||||
**FINDING (should-fix) — `\ No newline at end of file` breaks `patch`
|
||||
applicability.** `crates/vfmt/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
|
||||
vfmt --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 vfmt'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 `vfmt`
|
||||
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_excluded` is 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.sv` excludes
|
||||
`a/b/x.sv` (1 level) and `a/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 from `walk.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.sv` does not match
|
||||
`BUILD_gen.sv`. Confirmed case-sensitive as documented.
|
||||
|
||||
**`--stdin-filename` edge cases:**
|
||||
- Used correctly in error messages, `--diff` header, and `--check`
|
||||
line (existing integration test `stdin_mode_uses_stdin_filename_in_errors`
|
||||
covers all three; re-verified live).
|
||||
- `--stdin-filename` given 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 --diff` together: diff output replaces the "would reformat"
|
||||
line, exit 1 on change. Matches documented behavior exactly.
|
||||
- `--diff` over 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 — `vfmt -- file.sv` errors with `unknown option: --` (exit 2),
|
||||
since `args.rs:110` rejects any unrecognized token starting with `-`.
|
||||
Not a regression from this feature (pre-existing hand-rolled parser
|
||||
behavior, `args.rs` review 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 to `vfmt`. Nit, out of this feature's scope.
|
||||
- Unknown flag (`--bogus-flag`): clear `error: 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_stdin` call `format_contained`
|
||||
in a plain sequential `for` loop, no threads spawned anywhere in
|
||||
`crates/vfmt`), so there is no possible interleaving between two
|
||||
calls — each call's take_hook always sees the hook the previous call
|
||||
restored. The existing `catch_panic_is_reusable` unit 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 to
|
||||
`format_source` in 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 for `c_bad2.sv` with its
|
||||
own distinct payload), no cross-contamination between the two error
|
||||
messages, no backtrace/`thread 'main' panicked` noise from either,
|
||||
the good file in between formatted correctly, both bad files
|
||||
byte-identical afterward, summary `1 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-reading `catch_panic` there is no
|
||||
thread-local isolation, so two concurrent `take_hook`/`set_hook` pairs
|
||||
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:**
|
||||
1. `--diff` unified output, exit codes, stdout/stderr split — **PASS**,
|
||||
with the should-fix `\ No newline at end of file` sign-prefix bug
|
||||
noted above (does not violate the documented "not patch-exact"
|
||||
contract, but is worth fixing).
|
||||
2. `--stdin-filename` — **PASS**, all documented behaviors verified.
|
||||
3. `--exclude` matching semantics — **PASS**, all documented behaviors
|
||||
verified; `**` emergent behavior and no-effect-on-walk-root are nits
|
||||
worth a one-line Assumptions clarification, not bugs.
|
||||
4. Exit codes 0/1/2, documented in `--help`/README/feature README,
|
||||
error outranks would-change — **PASS**.
|
||||
5. 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.
|
||||
6. Test counts — **PASS**, 12 CLI integration + 18 unit tests, all
|
||||
green, exact match to the claim.
|
||||
|
||||
No fixes were made directly to `crates/vfmt/**` — 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):
|
||||
|
||||
1. **`\ No newline at end of file` is now emitted patch-correctly** —
|
||||
`diff.rs` previously treated the marker as a signed pseudo content
|
||||
line, which `patch(1)` rejects. `split_lines` now 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 by `patch -p0 --dry-run` accepting 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 for `panic = "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.
|
||||
Reference in new issue
Block a user