Files
lucisv/crates/vfmt/tests/cli.rs
T
lucioandClaude Fable 5 7cf657a538 Add vlog_semantic and parallel-files (jointly: shared root manifest)
vlog_semantic (new crate): single-file symbol tables and reference
resolution -- the layer that powers go-to-definition, references,
hover and document outline, and later the semantic lint rules.
Two-pass bind-then-resolve (Verilog forward references), 15 symbol
kinds, scope tree, and a three-state Resolution (Resolved /
ExternalCandidate carrying import paths for the future workspace
index / NotFound). scan.rs recovers name spans the AST lacks (95k
corpus spans verified; handshake filed and approved to move
name_span into the parser, which deletes the module). Corpus
baseline: 79.5% in-file resolution, 0.9% unresolved on clean files,
zero panics including tolerant-parse trees.

parallel-files (vfmt): rayon-parallel per-file formatting -- first
dependency, exact-pinned with written justification. 8 MiB worker
stacks discharge the recursion-limit handshake (sabotage-verified);
single-install panic hook discharges the cli-polish handshake;
deterministic input-order output (one stdout/stderr hash across 14
corpus runs at 4 thread counts); --threads flag; hand-rolled
.gitignore subset with 16/16 differential agreement against git
check-ignore. 3.6x wall-clock on the 860-file corpus.

Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{vlog-semantic,parallel-files}/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 06:39:51 -07:00

684 lines
27 KiB
Rust

//! 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";
/// Formats to `INDENT_2` or `INDENT_4` depending on the `indent` setting.
const UNINDENTED: &str = "module m;\nwire x;\nendmodule\n";
const INDENT_2: &str = "module m;\n wire x;\nendmodule\n";
const INDENT_4: &str = "module m;\n wire x;\nendmodule\n";
/// 44 columns: one line under the default 100, split under `line-length = 40`.
const WIDE: &str = "module m (input wire aaaa, input wire bbbb);\nendmodule\n";
const WIDE_SPLIT: &str = "module m (\n input wire aaaa,\n input wire bbbb\n);\nendmodule\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 deeply_nested_file_does_not_kill_the_batch() {
// Before `vlog_parser`'s depth limit this input overflowed the stack and
// aborted the process, so files sorted after it were never processed —
// and a stack overflow is not a panic, so `catch_unwind` cannot help.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(150),
"end\n".repeat(150)
);
// A postfix chain is built by a loop, not by recursion: it costs the
// parser no depth but hands the formatter an equally deep AST, which
// crashed it the same way until chains got a budget of their own.
let chain = format!("module m;\nassign x = a{};\nendmodule\n", ".b".repeat(1500));
let dir = TempDir::new("deep");
dir.write("a_before.sv", UNFORMATTED);
dir.write("b_deep.sv", &deep);
dir.write("c_chain.sv", &chain);
dir.write("d_after.sv", UNFORMATTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 2, "a file that cannot be parsed exits 2");
assert_eq!(dir.read("b_deep.sv"), deep, "the offending file is left untouched");
assert_eq!(dir.read("c_chain.sv"), chain, "the offending file is left untouched");
assert_eq!(dir.read("a_before.sv"), FORMATTED);
assert_eq!(dir.read("d_after.sv"), FORMATTED, "files after the bad ones are still processed");
let err = stderr(&out);
assert!(err.contains("b_deep.sv: parse error"), "{err}");
assert!(err.contains("nesting too deep"), "{err}");
assert!(err.contains("c_chain.sv: parse error"), "{err}");
assert!(err.contains("expression chain too long"), "{err}");
assert!(err.contains("2 files reformatted"), "{err}");
assert!(err.contains("2 files failed to format"), "{err}");
}
/// A tree wide enough that the pool actually splits it up, with a mix of
/// formatted, unformatted and broken files so every counter is exercised.
fn mixed_tree(dir: &TempDir) {
for n in 0..24 {
dir.write(&format!("wide/f{n:02}.sv"), UNFORMATTED);
dir.write(&format!("deep/a/b/c/g{n:02}.v"), FORMATTED);
}
dir.write("bad/x.sv", UNPARSEABLE);
dir.write("bad/y.sv", UNPARSEABLE);
}
#[test]
fn thread_count_changes_nothing_but_speed() {
// The determinism bar: the same invocation must produce byte-identical
// stdout, stderr and exit code however many workers ran it.
for mode in [&["--check"][..], &["--diff"][..]] {
let dir = TempDir::new("threads");
mixed_tree(&dir);
let root = dir.root();
let mut args = mode.to_vec();
args.push(&root);
let parallel = run(&args);
let mut serial_args = vec!["--threads", "1"];
serial_args.extend_from_slice(mode);
serial_args.push(&root);
let serial = run(&serial_args);
assert_eq!(code(&parallel), code(&serial), "{mode:?}");
assert_eq!(parallel.stdout, serial.stdout, "{mode:?}: stdout must not depend on threads");
assert_eq!(parallel.stderr, serial.stderr, "{mode:?}: stderr must not depend on threads");
assert_eq!(code(&parallel), 2, "the broken files win over would-reformat");
assert!(stderr(&parallel).contains("2 files failed to format"), "{}", stderr(&parallel));
// And a second parallel run of the same thing is byte-identical too.
let again = run(&args);
assert_eq!(parallel.stdout, again.stdout, "{mode:?}: two parallel runs must agree");
assert_eq!(parallel.stderr, again.stderr, "{mode:?}: two parallel runs must agree");
}
}
#[test]
fn writing_in_parallel_matches_writing_serially() {
let parallel = TempDir::new("writepar");
let serial = TempDir::new("writeser");
mixed_tree(&parallel);
mixed_tree(&serial);
let a = run(&[&parallel.root()]);
let b = run(&["--threads", "1", &serial.root()]);
assert_eq!(code(&a), 2);
assert_eq!(code(&b), 2);
// Only the summary line can be compared verbatim: the error lines name
// the two (necessarily different) temporary directories.
let summary = |out: &Output| stderr(out).lines().last().unwrap_or_default().to_string();
assert_eq!(summary(&a), summary(&b), "the summary must not depend on the thread count");
assert_eq!(
summary(&a),
"24 files reformatted, 24 files left unchanged, 2 files failed to format"
);
for n in 0..24 {
let f = format!("wide/f{n:02}.sv");
assert_eq!(parallel.read(&f), FORMATTED);
assert_eq!(parallel.read(&f), serial.read(&f));
}
assert_eq!(parallel.read("bad/x.sv"), UNPARSEABLE, "a broken file is left untouched");
}
#[test]
fn diff_over_many_files_comes_out_in_input_order() {
let dir = TempDir::new("difforder");
let names = ["a.sv", "b.sv", "c.sv", "d/e.sv", "d/f.sv", "g.sv"];
for name in names {
dir.write(name, UNFORMATTED);
}
let out = run(&["--diff", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let text = stdout(&out);
let headers: Vec<&str> = text.lines().filter(|l| l.starts_with("--- ")).collect();
let expected: Vec<String> =
names.iter().map(|n| format!("--- {}/{n}", dir.root())).collect::<Vec<_>>();
// `d/` sorts after `c.sv` and before `g.sv`, matching the walk order.
let mut expected: Vec<&str> = expected.iter().map(String::as_str).collect();
expected.sort();
assert_eq!(headers, expected, "{text}");
// Each file's hunks stay together: nothing interleaves.
assert_eq!(text.matches("@@ ").count(), names.len(), "{text}");
assert_eq!(stdout(&run(&["--threads", "1", "--diff", &dir.root()])), text);
}
#[test]
fn a_deeply_nested_file_formats_on_a_worker_thread() {
// Just under `vlog_parser::MAX_NESTING_DEPTH` (a nested `if … begin`
// costs two levels), so it parses — and needs several MiB of stack to
// do it in a debug build: without the depth limit this family died at
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
// stack. This test crashes the process if the pool's 8 MiB is dropped.
let deep = format!(
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
"if (clk) begin\n".repeat(28),
"end\n".repeat(28)
);
let dir = TempDir::new("deeppool");
dir.write("deep.sv", &deep);
dir.write("plain.sv", UNFORMATTED);
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let err = stderr(&out);
assert!(!err.contains("parse error"), "the input must be under the limit: {err}");
assert!(!err.contains("panicked"), "{err}");
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
}
#[test]
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
let dir = TempDir::new("configpar");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("sub/vfmt.toml", "indent = 8\n");
dir.write("sub/deeper/vfmt.toml", "indent = 2\n");
for n in 0..12 {
dir.write(&format!("root{n:02}.sv"), UNINDENTED);
dir.write(&format!("sub/mid{n:02}.sv"), UNINDENTED);
dir.write(&format!("sub/deeper/low{n:02}.sv"), UNINDENTED);
}
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
for n in 0..12 {
assert_eq!(dir.read(&format!("root{n:02}.sv")), INDENT_4);
assert_eq!(
dir.read(&format!("sub/mid{n:02}.sv")),
"module m;\n wire x;\nendmodule\n"
);
assert_eq!(dir.read(&format!("sub/deeper/low{n:02}.sv")), INDENT_2);
}
}
#[test]
fn gitignore_is_honored_while_walking() {
let dir = TempDir::new("gitignore");
dir.write(".gitignore", "# generated\nbuild/\n*_gen.sv\n");
dir.write("keep.sv", UNFORMATTED);
dir.write("skip_gen.sv", UNFORMATTED);
dir.write("build/inner.sv", UNFORMATTED);
dir.write("sub/deep_gen.sv", UNFORMATTED);
dir.write("sub/keep.sv", UNFORMATTED);
let out = run(&[&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, "a name pattern ignores at any depth");
assert_eq!(dir.read("sub/deep_gen.sv"), UNFORMATTED);
assert_eq!(dir.read("build/inner.sv"), UNFORMATTED, "an ignored directory is not entered");
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
}
#[test]
fn a_nested_gitignore_overrides_the_one_above_it() {
let dir = TempDir::new("gitignorenested");
dir.write(".gitignore", "*_gen.sv\n/anchored.sv\n");
dir.write("sub/.gitignore", "!keep_gen.sv\ndrop.sv\n");
dir.write("anchored.sv", UNFORMATTED);
dir.write("sub/anchored.sv", UNFORMATTED);
dir.write("sub/keep_gen.sv", UNFORMATTED);
dir.write("sub/other_gen.sv", UNFORMATTED);
dir.write("sub/drop.sv", UNFORMATTED);
dir.write("drop.sv", UNFORMATTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("anchored.sv"), UNFORMATTED, "a leading slash anchors to the root");
assert_eq!(dir.read("sub/anchored.sv"), FORMATTED, "…and does not reach into a subdirectory");
assert_eq!(dir.read("sub/keep_gen.sv"), FORMATTED, "the deeper `!` rule wins");
assert_eq!(dir.read("sub/other_gen.sv"), UNFORMATTED, "the outer rule still applies");
assert_eq!(dir.read("sub/drop.sv"), UNFORMATTED, "the deeper file's own rule applies");
assert_eq!(dir.read("drop.sv"), FORMATTED, "a deeper rule does not apply above itself");
}
#[test]
fn no_gitignore_switches_the_whole_thing_off() {
let dir = TempDir::new("nogitignore");
dir.write(".gitignore", "build/\n*_gen.sv\n");
dir.write("keep.sv", UNFORMATTED);
dir.write("skip_gen.sv", UNFORMATTED);
dir.write("build/inner.sv", UNFORMATTED);
let out = run(&["--no-gitignore", &dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("keep.sv"), FORMATTED);
assert_eq!(dir.read("skip_gen.sv"), FORMATTED);
assert_eq!(dir.read("build/inner.sv"), FORMATTED);
}
#[test]
fn gitignore_does_not_apply_to_explicitly_named_paths() {
let dir = TempDir::new("gitignoreexplicit");
dir.write(".gitignore", "*_gen.sv\nbuild/\n");
let named = dir.write("skip_gen.sv", UNFORMATTED);
let inside = dir.write("build/inner.sv", UNFORMATTED);
let out = run(&[&named, &inside]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("skip_gen.sv"), FORMATTED, "a path on the command line is never ignored");
assert_eq!(dir.read("build/inner.sv"), FORMATTED);
}
#[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}");
assert!(text.contains("CONFIGURATION:"), "{text}");
assert!(text.contains("IGNORE FILES:"), "{text}");
for flag in [
"--check",
"--diff",
"--exclude",
"--stdin-filename",
"--no-config",
"--no-gitignore",
"--threads",
] {
assert!(text.contains(flag), "help is missing {flag}");
}
}
#[test]
fn a_config_file_is_found_by_searching_upward() {
let dir = TempDir::new("configup");
dir.write("vfmt.toml", "indent = 4\nline-length = 40\n");
dir.write("a/b/x.sv", UNINDENTED);
dir.write("a/b/wide.sv", WIDE);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("a/b/x.sv"), INDENT_4);
// Both keys took effect: split by `line-length`, indented by `indent`.
assert_eq!(
dir.read("a/b/wide.sv"),
"module m (\n input wire aaaa,\n input wire bbbb\n);\nendmodule\n"
);
// Both names work; `.vfmt.toml` is the fallback within one directory.
dir.write("a/b/x.sv", UNINDENTED);
std::fs::rename(dir.path.join("vfmt.toml"), dir.path.join(".vfmt.toml")).expect("rename");
assert_eq!(code(&run(&[&dir.root()])), 0);
assert_eq!(dir.read("a/b/x.sv"), INDENT_4);
}
#[test]
fn each_file_gets_the_config_of_its_own_directory() {
let dir = TempDir::new("configper");
dir.write("vfmt.toml", "indent = 4\n");
dir.write("root.sv", UNINDENTED);
dir.write("sub/vfmt.toml", "indent = 8\n");
dir.write("sub/deep/inner.sv", UNINDENTED);
dir.write("other/plain.sv", UNINDENTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("root.sv"), INDENT_4);
assert_eq!(dir.read("sub/deep/inner.sv"), "module m;\n wire x;\nendmodule\n");
assert_eq!(dir.read("other/plain.sv"), INDENT_4, "the nearest config is the root's");
// --check uses the same per-file settings and its summary is unchanged:
// everything is now formatted to its own directory's config.
let out = run(&["--check", &dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert!(stderr(&out).contains("3 files left unchanged"), "{}", stderr(&out));
}
#[test]
fn a_cli_flag_overrides_the_config_file() {
let dir = TempDir::new("configcli");
dir.write("vfmt.toml", "indent = 4\nline-length = 40\n");
dir.write("x.sv", UNINDENTED);
dir.write("wide.sv", WIDE);
let out = run(&["--indent", "2", &dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("x.sv"), INDENT_2, "--indent wins over the file");
assert_eq!(dir.read("wide.sv"), WIDE_SPLIT, "line-length is still the file's");
}
#[test]
fn no_config_ignores_config_files_entirely() {
let dir = TempDir::new("noconfig");
// Not even parsed: --no-config reads nothing from disk.
dir.write("vfmt.toml", "this file is not valid at all\n");
dir.write("x.sv", UNINDENTED);
let out = run(&["--no-config", &dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("x.sv"), INDENT_2, "defaults apply");
}
#[test]
fn a_broken_config_exits_2_before_writing_anything() {
let dir = TempDir::new("configbad");
dir.write("vfmt.toml", "indent = 4\nline_length = 80\n");
dir.write("x.sv", UNINDENTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 2, "a config error is an error, not a warning");
assert_eq!(dir.read("x.sv"), UNINDENTED, "nothing is written when the config is broken");
let err = stderr(&out);
assert!(err.contains("vfmt.toml:2:"), "the error names the file and line: {err}");
assert!(err.contains("unknown key `line_length`"), "{err}");
for (contents, expected) in [
("indent = 99\n", "between 1 and 8"),
("line-length = wide\n", "expects an integer"),
("[tool.vfmt]\nindent = 2\n", "tables"),
("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"),
] {
dir.write("vfmt.toml", contents);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 2, "{contents}");
assert!(stderr(&out).contains(expected), "{contents}: {}", stderr(&out));
assert_eq!(dir.read("x.sv"), UNINDENTED);
}
}
#[test]
fn config_excludes_are_added_to_cli_excludes() {
let dir = TempDir::new("configexclude");
dir.write("vfmt.toml", "exclude = [ \"*_gen.sv\", \"build\" ] # generated\n");
dir.write("keep.sv", UNINDENTED);
dir.write("skip_gen.sv", UNINDENTED);
dir.write("build/inner.sv", UNINDENTED);
dir.write("vendor/v.sv", UNINDENTED);
let out = run(&["--exclude", "vendor", &dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("keep.sv"), INDENT_2);
assert_eq!(dir.read("skip_gen.sv"), UNINDENTED, "config exclude applies");
assert_eq!(dir.read("build/inner.sv"), UNINDENTED, "config exclude applies to dirs");
assert_eq!(dir.read("vendor/v.sv"), UNINDENTED, "--exclude still applies");
}
#[test]
fn stdin_discovers_config_from_stdin_filename() {
let dir = TempDir::new("configstdin");
dir.write("vfmt.toml", "indent = 4\n");
let buffer = format!("{}/rtl/buffer.sv", dir.root());
let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(stdout(&out), INDENT_4);
assert!(!std::path::Path::new(&buffer).exists(), "--stdin-filename must not touch disk");
// Without the flag the anchor is the cwd, which has no config here.
let out = run_with_stdin(&["-"], UNINDENTED);
assert_eq!(code(&out), 0);
assert_eq!(stdout(&out), INDENT_2);
let out = run_with_stdin(&["--no-config", "--stdin-filename", &buffer, "-"], UNINDENTED);
assert_eq!(code(&out), 0);
assert_eq!(stdout(&out), INDENT_2, "--no-config applies to stdin too");
// A broken config is an error in stdin mode too, and nothing is echoed.
dir.write("vfmt.toml", "indent = 4\nbogus = 1\n");
let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED);
assert_eq!(code(&out), 2);
assert_eq!(stdout(&out), "", "no output when the config is broken");
assert!(stderr(&out).contains("unknown key `bogus`"), "{}", stderr(&out));
}
#[test]
fn the_search_stops_at_a_git_directory_after_checking_it() {
let dir = TempDir::new("configgit");
dir.write("vfmt.toml", "indent = 4\n");
std::fs::create_dir_all(dir.path.join("repo/.git")).expect("create .git");
dir.write("repo/rtl/x.sv", UNINDENTED);
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("repo/rtl/x.sv"), INDENT_2, "the walk stops at the repo root");
// A config file *in* the repo root is still found: `.git` only stops
// the walk after its own directory has been checked.
dir.write("repo/rtl/x.sv", UNINDENTED);
dir.write("repo/vfmt.toml", "indent = 8\n");
let out = run(&[&dir.root()]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("repo/rtl/x.sv"), "module m;\n wire x;\nendmodule\n");
}