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]>
232 lines
6.8 KiB
Rust
232 lines
6.8 KiB
Rust
//! vfmt — a Verilog/SystemVerilog formatter in the spirit of `ruff format`.
|
|
//!
|
|
//! 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::panic::AssertUnwindSafe;
|
|
use std::path::PathBuf;
|
|
use std::process::ExitCode;
|
|
|
|
use args::Options;
|
|
use vlog_formatter::{format_source, Config};
|
|
use walk::{collect_files, EXTENSIONS};
|
|
|
|
fn main() -> ExitCode {
|
|
let opts = match args::parse() {
|
|
Ok(o) => o,
|
|
Err(e) => {
|
|
eprintln!("error: {e}");
|
|
return ExitCode::from(2);
|
|
}
|
|
};
|
|
|
|
if opts.inputs.len() == 1 && opts.inputs[0] == "-" {
|
|
run_stdin(&opts)
|
|
} else {
|
|
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)
|
|
}
|
|
|
|
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 out == src {
|
|
unchanged += 1;
|
|
continue;
|
|
}
|
|
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 {
|
|
if n == 1 {
|
|
""
|
|
} else {
|
|
"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}");
|
|
}
|
|
}
|