CLI filelist M13: vfmt -f files.f

The -f flag (repeatable) feeds M1's filelist parser to format, check,
--check and --diff: listed paths are exact like positional args (never
excluded or gitignored), warnings go to stderr without touching the
frozen exit-code contract, an unreadable filelist is exit 2 with nothing
written, and inputs from every source dedup by lexical absolute path -
which also closes the old vfmt rtl/ rtl/a.sv double-processing. --lines
and stdin reject -f at parse time. vfmt.toml's filelist key stays
server-only, deliberately. QA's exit-code matrix confirmed all eight
cells; its pre-existing torn-write find is filed in TODO §1.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-25 02:44:38 -07:00
1 parent 80978f324f
commit 36ddabac6c
8 files changed
+763 -13

No files matched your search

+21 -3
View File
@@ -18,6 +18,10 @@ vfmt --check rtl/
# print a unified diff instead of rewriting (also exit 1 if anything would change)
vfmt --diff rtl/
# format exactly what an EDA `.f` filelist names (repeatable, adds to the rest)
vfmt -f project.f
vfmt check -f project.f -f tb/tb.f rtl/extra.sv
# skip generated files while walking directories (repeatable)
vfmt --exclude '*_gen.sv' --exclude build rtl/
@@ -127,9 +131,23 @@ filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file
`filelist` names the project's sources the way the rest of the EDA world
already does — one path per line, `-f` to nest another filelist, `+incdir+`,
`+define+`, `#`/`//` comments, `$VAR` expansion, paths relative to the
filelist that names them. It is read by `vfmt-server`, where it defines
exactly which files are indexed ([Editor setup](#editor-setup)); the CLI does
not consume it yet. Details: `docs/features/filelist/README.md`.
filelist that names them. This **key** is read by `vfmt-server` only, where it
defines exactly which files are indexed ([Editor setup](#editor-setup)): a
`vfmt rtl/` that quietly formatted a filelist's files instead of `rtl/`'s would
be a surprise. On the command line a filelist is named explicitly, with `-f`:
```bash
vfmt -f project.f # format exactly the files it names
vfmt check -f project.f rtl/ # ...added to whatever else is named
```
The listed paths are taken exactly as written — neither `--exclude` nor
`.gitignore` filters them, just as neither filters a file named on the command
line — and a file named twice over is processed once. A listed file that has
gone missing, an option vfmt does not know and an unset `$VAR` are warnings on
stderr that change no exit code; a filelist that cannot be read at all is an
error (exit 2) and nothing is processed. Details:
`docs/features/filelist/README.md` and `docs/features/cli-filelist/README.md`.
**Precedence: CLI flag > config file > default**, per setting (`--indent 4`
with a file that sets only `line-length` uses both). `exclude` is the
+9 -1
View File
@@ -43,6 +43,14 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
`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.
- [ ] **Atomic in-place writes.** QA find during cli-filelist (2026-08-25,
pre-existing): `process_file` and the `--fix` path write with plain
`fs::write` (open/truncate/write) while `cache.rs` next door already
does tempfile+rename. Two workers reaching one inode through two
spellings (symlink alias — lexical dedup cannot see it) could tear a
file. Fix: tempfile+rename in both writers; optionally canonicalized
dedup keys as a second line of defense.
## 2. Formatter features
- [x] **[V] Format-off fences.** Support `// verilog_format: off` /
@@ -611,7 +619,7 @@ section only tracks the milestones.
instantiates X / what X instantiates) over LSP callHierarchy.
- [x] **M12 `semantic-lints`** — unused-signal, undriven-net,
multiply-driven: the first semantic lint rules on `vlog_semantic`.
- [ ] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line,
- [x] **M13 `cli-filelist`** — `vfmt -f files.f` on the command line,
reusing M1's parser; format/lint exactly the project's files.
- [ ] **M14 `macro-expansion`** — single-step macro expansion on hover
(the define-table README's promised follow-up); version 0.5.0 with a
+70 -4
View File
@@ -73,6 +73,8 @@ pub struct Options {
pub ignore: Vec<String>,
/// Files, directories, or the single input `-`.
pub inputs: Vec<String>,
/// `-f`: EDA filelists whose files are added to [`Options::inputs`].
pub filelists: Vec<String>,
}
impl Options {
@@ -136,6 +138,7 @@ USAGE:
vfmt [OPTIONS] <file|dir>... format files in place
vfmt format [OPTIONS] <file|dir>... the same, spelled out
vfmt check [OPTIONS] <file|dir>... lint files
vfmt [OPTIONS] -f <filelist> format what an EDA .f filelist names
vfmt - read from stdin, write to stdout
A subcommand is only recognized as the *first* argument, so every command
@@ -150,6 +153,16 @@ OPTIONS:
repeated. A pattern with `/` matches a path suffix,
otherwise it matches a file or directory name; `*`
matches within one path component
-f <FILELIST> also process every source file this EDA `.f`
filelist names; may be repeated, and combines with
file and directory arguments. Listed paths are
taken exactly as written — neither --exclude nor
.gitignore filters them, just as neither filters a
file named on the command line. A listed file that
is missing, an option vfmt does not know and an
unset $VAR are warnings on stderr and change no
exit code; a filelist that cannot be read at all
is an error and nothing is processed
--stdin-filename <PATH> path to report in messages for input read from stdin;
also the directory config discovery starts from
--no-gitignore don't read .gitignore files while walking directories
@@ -164,8 +177,8 @@ OPTIONS:
inclusive line ranges and emit every other byte
exactly as written; comma-separated (`--lines
3-9,40`) and repeatable. Requires explicit file
arguments or `-`, never a directory, and neither
reads nor writes the cache
arguments or `-`, never a directory and never a
filelist, and neither reads nor writes the cache
--line-length <N> maximum line length (default 100)
--indent <N> indent width in spaces (default 2)
--no-config ignore vfmt.toml / .vfmt.toml files
@@ -196,6 +209,15 @@ IGNORE FILES:
supported: `**`, `?`, character classes, `\\` escapes and the global/repo
excludes files. Paths named on the command line are never ignored.
FILELISTS:
`-f project.f` reads the EDA filelist every Verilog build already has: one
source path per line, resolved against the directory of the filelist naming
it, plus `-f other.f` to nest another, `+incdir+`/`+define+` (accepted and
ignored — vfmt does not preprocess), `$VAR`/`${{VAR}}` expansion, and `//` or
`#` comments. The files it names are added to whatever the command line
already names, in that order, and a file named twice over is processed once.
Paths containing whitespace cannot be listed: there is no quoting.
CACHE:
A file whose exact content vfmt has already verified is formatted — under
the same line-length, indent and vfmt version — is skipped on the next run
@@ -210,7 +232,9 @@ CONFIGURATION:
directory containing `.git`, after checking it). Recognized keys, all
optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of
patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file,
read by vfmt-server only). A command line flag overrides the file.
read by vfmt-server only — the CLI reads a filelist only when `-f` names
one, so `vfmt rtl/` always means the directory it was given). A command
line flag overrides the file.
RANGE FORMATTING:
`--lines` formats one construct at a time: an item whose lines meet a range
@@ -258,6 +282,7 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
select: Vec::new(),
ignore: Vec::new(),
inputs: Vec::new(),
filelists: Vec::new(),
};
let mut line_specs: Vec<String> = Vec::new();
let mut args = args.peekable();
@@ -296,6 +321,10 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
let v = args.next().ok_or("--exclude requires a value")?;
opts.exclude.push(v);
}
"-f" => {
let v = args.next().ok_or("-f requires a value")?;
opts.filelists.push(v);
}
"--stdin-filename" => {
let v = args.next().ok_or("--stdin-filename requires a value")?;
opts.stdin_filename = Some(v);
@@ -344,7 +373,9 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
s => opts.inputs.push(s.to_string()),
}
}
if opts.inputs.is_empty() {
// A filelist is an input like any other, so `-f files.f` alone is a
// complete command line and needs no positional argument.
if opts.inputs.is_empty() && opts.filelists.is_empty() {
return Err("no input files (try `vfmt --help`)".to_string());
}
// Repeating the flag is the same as one comma-separated list; both spell
@@ -355,6 +386,18 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
if opts.diff && opts.stdout {
return Err("--diff cannot be combined with --stdout".to_string());
}
if !opts.filelists.is_empty() {
// stdin is one buffer with no path of its own; a filelist is a set of
// paths on disk. Reading both would mean ignoring one of them.
if opts.inputs.iter().any(|input| input == "-") {
return Err("`-` cannot be combined with -f".to_string());
}
// Same reason `--lines` rejects a directory: line numbers name lines
// of *a file*, and a filelist is a file set.
if opts.lines.is_some() {
return Err("--lines needs a file, not a filelist".to_string());
}
}
check_flag_scopes(&opts)?;
Ok(opts)
}
@@ -515,6 +558,29 @@ mod tests {
assert!(parse(&["check", "--lines", "1", "a.sv"]).is_err());
}
#[test]
fn filelists_are_collected_and_stand_in_for_positional_inputs() {
let opts = parse(&["-f", "a.f", "-f", "b.f", "rtl"]).unwrap();
assert_eq!(opts.filelists, vec!["a.f", "b.f"]);
assert_eq!(opts.inputs, vec!["rtl"]);
// A filelist is an input, so it is a complete command line on its own.
let opts = parse(&["-f", "a.f"]).unwrap();
assert_eq!(opts.filelists, vec!["a.f"]);
assert!(opts.inputs.is_empty());
assert!(parse(&["--check"]).is_err(), "neither inputs nor filelists is still an error");
assert!(parse(&["-f"]).is_err());
}
#[test]
fn a_filelist_is_a_file_set_so_stdin_and_lines_reject_it() {
// stdin is one buffer with no path; a filelist is a set of paths.
assert!(parse(&["-f", "a.f", "-"]).is_err());
// Same reason `--lines` rejects a directory: line 12 of 400 files is
// never what anyone meant.
assert!(parse(&["--lines", "1", "-f", "a.f"]).is_err());
assert!(parse(&["--lines", "1", "a.sv"]).is_ok(), "a named file is still fine");
}
#[test]
fn gitignore_is_honored_unless_switched_off() {
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
+78 -2
View File
@@ -6,6 +6,7 @@
//! vfmt --check <file|dir>... exit 1 if anything would change
//! vfmt --diff <file|dir>... print a unified diff of what would change
//! vfmt check <file|dir>... lint files (exit 1 if anything is found)
//! vfmt -f files.f format what an EDA `.f` filelist names
//! vfmt - read stdin, write stdout
//!
//! Exit codes: 0 nothing to do, 1 `--check`/`--diff` found changes or `check`
@@ -17,9 +18,10 @@ mod diff;
mod lint;
use std::cell::Cell;
use std::collections::HashSet;
use std::io::Read;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
use rayon::prelude::*;
@@ -27,6 +29,7 @@ use rayon::prelude::*;
use args::{Command, Options};
use vfmt_core::cache::{content_hash, Cache, Entry};
use vfmt_core::config::Discovery;
use vfmt_core::filelist;
use vfmt_core::walk::{collect_files, EXTENSIONS};
use vlog_formatter::{format_range, format_source, Config, LineRanges};
@@ -278,7 +281,10 @@ fn build_pool(opts: &Options) -> Result<(), String> {
.map_err(|e| format!("could not start the worker pool: {e}"))
}
/// Collects the files to format, each with the settings that govern it.
/// Collects the files to format, each with the settings that govern it:
/// the command line's own inputs (walked, and filtered by `--exclude` and
/// `.gitignore` when they are directories) plus everything the `-f`
/// filelists name (exact paths, filtered by neither — they were named).
/// Every config file is read here, before anything is written, so a broken
/// one aborts the whole run instead of leaving it half applied.
fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
@@ -296,6 +302,10 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
}
// Filelists come after the command line's own inputs, in flag order: they
// add files, they never replace or reorder what was named directly.
files.extend(filelist_files(opts)?);
let files = dedup(files);
if files.is_empty() {
return Err(format!("no Verilog files found (extensions: {})", EXTENSIONS.join(", ")));
}
@@ -307,6 +317,55 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
Ok(jobs)
}
/// Every file the `-f` filelists name, in flag order then list order.
///
/// The one place `gather` speaks to the user: a filelist's warnings — a
/// listed file that is gone, an option vfmt does not know, an unset `$VAR`,
/// a `-f` chain nested too deep — have to be said even though the run
/// succeeds, so they go to stderr and change no exit code. Only the filelist
/// itself being unreadable is an error, and it aborts the run here, before
/// anything has been written.
fn filelist_files(opts: &Options) -> Result<Vec<PathBuf>, String> {
let mut files = Vec::new();
for name in &opts.filelists {
let list = filelist::read(Path::new(name))?;
for warning in &list.warnings {
eprintln!("warning: {warning}");
}
files.extend(list.files);
}
Ok(files)
}
/// Drops repeats, keeping each file's first spelling. One file can be named
/// twice over — by a directory walk and by name, by two filelists, or by a
/// filelist and the command line — and processing it twice would double its
/// line in the summary and, worse, put two workers on one path.
fn dedup(files: Vec<PathBuf>) -> Vec<PathBuf> {
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let mut seen = HashSet::new();
files.into_iter().filter(|file| seen.insert(absolute(&cwd, file))).collect()
}
/// `path` folded to the absolute, `.`/`..`-free spelling two names for one
/// file share. Lexical, like `vfmt_core`'s own normalization: symlinks are
/// deliberately left unresolved, so this is only ever a dedup key and never
/// the path vfmt reports.
fn absolute(cwd: &Path, path: &Path) -> PathBuf {
let joined = if path.is_absolute() { path.to_path_buf() } else { cwd.join(path) };
let mut out = PathBuf::new();
for component in joined.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other),
}
}
out
}
/// The settings for a buffer piped in on stdin: discovery anchors on
/// `--stdin-filename`'s directory when given, else on the current one.
fn stdin_config(opts: &Options) -> Result<Config, String> {
@@ -452,6 +511,23 @@ mod tests {
assert!(!elsewhere);
}
#[test]
fn dedup_folds_the_spellings_of_one_file_and_keeps_the_first() {
let files = ["rtl/a.sv", "rtl/../rtl/a.sv", "./rtl/a.sv", "rtl/b.sv", "rtl/a.sv"]
.iter()
.map(PathBuf::from)
.collect();
// The first spelling survives: it is what the user typed, and it is
// what every message about that file will say.
assert_eq!(dedup(files), [PathBuf::from("rtl/a.sv"), PathBuf::from("rtl/b.sv")]);
// The key is absolute, so a relative and an absolute name for one
// file are one file.
let cwd = std::env::current_dir().expect("cwd");
let files = vec![cwd.join("rtl/a.sv"), PathBuf::from("rtl/a.sv")];
assert_eq!(dedup(files), [cwd.join("rtl/a.sv")]);
}
#[test]
fn format_contained_reports_parse_errors() {
let err = format_contained("module", &Config::default(), None).unwrap_err();
+186
View File
@@ -1511,3 +1511,189 @@ fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
child.wait_with_output().expect("run vfmt")
}
// --- `-f`, the EDA filelist (docs/features/cli-filelist/README.md) ---------
/// A tree with a filelist naming one file directly and one through a nested
/// `-f`, plus a file nothing lists. Returns the temp dir.
fn filelist_tree(tag: &str) -> TempDir {
let dir = TempDir::new(tag);
dir.write("rtl/a.sv", UNFORMATTED);
dir.write("rtl/b.sv", UNFORMATTED);
dir.write("rtl/unlisted.sv", UNFORMATTED);
dir.write("top.f", "# the project\nrtl/a.sv\n-f sub/more.f\n");
dir.write("sub/more.f", "../rtl/b.sv\n");
dir
}
#[test]
fn a_filelist_names_the_files_to_format() {
let dir = filelist_tree("filelist");
let list = dir.write("top.f", "# the project\nrtl/a.sv\n-f sub/more.f\n");
let out = run(&["-f", &list]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("rtl/a.sv"), FORMATTED);
assert_eq!(dir.read("rtl/b.sv"), FORMATTED, "a nested -f contributes its files too");
assert_eq!(dir.read("rtl/unlisted.sv"), UNFORMATTED, "only what the filelist names");
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
}
#[test]
fn a_filelist_and_positional_inputs_add_up_and_each_file_is_processed_once() {
let dir = filelist_tree("filelist-plus");
let list = dir.write("top.f", "rtl/a.sv\n-f sub/more.f\n");
let also = dir.write("rtl/unlisted.sv", UNFORMATTED);
let already = dir.write("rtl/a.sv", UNFORMATTED);
// `rtl/a.sv` is named three times over — by the filelist, by name, and by
// the directory walk — and must still be one file in the summary.
let out =
run(&["--check", "-f", &list, &also, &already, &dir.path.join("rtl").to_string_lossy()]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
let text = stdout(&out);
assert_eq!(text.matches("a.sv").count(), 1, "{text}");
assert_eq!(text.matches("b.sv").count(), 1, "{text}");
assert_eq!(text.matches("unlisted.sv").count(), 1, "{text}");
assert!(stderr(&out).contains("3 files would be reformatted"), "{}", stderr(&out));
// Either half works on its own, and repeating `-f` adds a second list.
let other = dir.write("other.f", "rtl/unlisted.sv\n");
let out = run(&["--check", "-f", &list, "-f", &other]);
assert_eq!(code(&out), 1);
assert!(stderr(&out).contains("3 files would be reformatted"), "{}", stderr(&out));
}
#[test]
fn a_missing_listed_file_warns_and_the_rest_are_still_processed() {
let dir = filelist_tree("filelist-missing");
let list = dir.write("top.f", "rtl/a.sv\ngone.sv\n-y lib\nrtl/b.sv\n");
let out = run(&["-f", &list]);
assert_eq!(code(&out), 0, "a warning is not an error: {}", stderr(&out));
assert_eq!(dir.read("rtl/a.sv"), FORMATTED);
assert_eq!(dir.read("rtl/b.sv"), FORMATTED);
let err = stderr(&out);
assert!(err.contains("warning: "), "{err}");
assert!(err.contains("top.f:2: no such file `gone.sv`"), "{err}");
assert!(err.contains("top.f:3: ignoring unsupported option `-y`"), "{err}");
assert!(stdout(&out).is_empty(), "warnings must not pollute stdout: {}", stdout(&out));
}
#[test]
fn an_unreadable_filelist_exits_2_and_processes_nothing() {
let dir = filelist_tree("filelist-unreadable");
let missing = dir.path.join("nope.f").to_string_lossy().into_owned();
let out = run(&["-f", &missing, &dir.write("rtl/a.sv", UNFORMATTED)]);
assert_eq!(code(&out), 2, "an unreadable filelist is the one hard error");
assert!(stderr(&out).contains("nope.f"), "{}", stderr(&out));
assert_eq!(dir.read("rtl/a.sv"), UNFORMATTED, "nothing is written when the run aborts");
}
#[test]
fn check_mode_exits_1_when_a_listed_file_would_be_reformatted() {
let dir = filelist_tree("filelist-check");
let list = dir.write("top.f", "rtl/a.sv\n");
let out = run(&["--check", "-f", &list]);
assert_eq!(code(&out), 1);
assert!(stdout(&out).contains("would reformat"), "{}", stdout(&out));
assert_eq!(dir.read("rtl/a.sv"), UNFORMATTED, "--check never writes");
// Formatted input, same filelist: nothing to do.
dir.write("rtl/a.sv", FORMATTED);
assert_eq!(code(&run(&["--check", "-f", &list])), 0);
}
#[test]
fn the_linter_takes_a_filelist_too_and_json_stays_parsable() {
let dir = TempDir::new("filelist-lint");
dir.write("foo.sv", LINTY);
let list = dir.write("top.f", "foo.sv\ngone.sv\n");
let out = run(&["check", "--select", "no-tabs", "-f", &list]);
assert_eq!(code(&out), 1, "{}", stderr(&out));
assert!(stdout(&out).contains("no-tabs"), "{}", stdout(&out));
// The filelist's warnings go to stderr, so stdout is still one JSON array.
let out = run(&["check", "--output-format", "json", "--select", "no-tabs", "-f", &list]);
assert_eq!(code(&out), 1);
let text = stdout(&out);
assert!(text.starts_with('['), "{text}");
assert!(text.trim_end().ends_with(']'), "{text}");
assert!(!text.contains("warning"), "{text}");
assert!(stderr(&out).contains("no such file `gone.sv`"), "{}", stderr(&out));
}
#[test]
fn a_filelists_paths_are_relative_to_it_not_to_the_working_directory() {
let dir = filelist_tree("filelist-cwd");
let sub = TempDir::new("filelist-cwd-elsewhere");
// Run from an unrelated directory, naming the filelist relatively from
// there: every path inside it still resolves against the filelist's
// own directory, and the nested list's against its own.
let relative = pathdiff(&sub.path, &dir.path.join("top.f"));
let out = run_in(&sub, &["--no-cache", "-f", &relative]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("rtl/a.sv"), FORMATTED);
assert_eq!(dir.read("rtl/b.sv"), FORMATTED);
}
/// `to` spelled relative to `from`, for the temp dirs here: they are always
/// siblings, so `../<name>/<rest>` is the whole story.
fn pathdiff(from: &std::path::Path, to: &std::path::Path) -> String {
let name = to.strip_prefix(from.parent().expect("temp parent")).expect("sibling");
std::path::Path::new("..").join(name).to_string_lossy().into_owned()
}
#[test]
fn a_listed_file_is_never_excluded_or_gitignored() {
let dir = TempDir::new("filelist-exclude");
dir.write(".gitignore", "*_gen.sv\nbuild/\n");
dir.write("gen/a_gen.sv", UNFORMATTED);
dir.write("build/inner.sv", UNFORMATTED);
let list = dir.write("top.f", "gen/a_gen.sv\nbuild/inner.sv\n");
// Same rule as a path named on the command line: it was named, so it is
// processed, whatever --exclude and .gitignore say.
let out = run(&["--exclude", "*_gen.sv", "--exclude", "build", "-f", &list]);
assert_eq!(code(&out), 0, "{}", stderr(&out));
assert_eq!(dir.read("gen/a_gen.sv"), FORMATTED);
assert_eq!(dir.read("build/inner.sv"), FORMATTED);
}
#[test]
fn stdin_and_lines_are_usage_errors_with_a_filelist() {
let dir = filelist_tree("filelist-usage");
let list = dir.write("top.f", "rtl/a.sv\n");
let out = run_with_stdin(&["-f", &list, "-"], UNFORMATTED);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("`-` cannot be combined with -f"), "{}", stderr(&out));
let out = run(&["--lines", "1", "-f", &list]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("--lines needs a file, not a filelist"), "{}", stderr(&out));
let out = run(&["-f"]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("-f requires a value"), "{}", stderr(&out));
// A filelist that names nothing usable is the ordinary empty-input error.
let empty = dir.write("empty.f", "# nothing here\n");
let out = run(&["-f", &empty]);
assert_eq!(code(&out), 2);
assert!(stderr(&out).contains("no Verilog files found"), "{}", stderr(&out));
assert_eq!(dir.read("rtl/a.sv"), UNFORMATTED, "no bad command line writes anything");
}
#[test]
fn help_documents_the_filelist_flag() {
let text = stdout(&run(&["--help"]));
assert!(text.contains("FILELISTS:"), "{text}");
assert!(text.contains("-f <FILELIST>"), "{text}");
assert!(text.contains("read by vfmt-server only"), "the toml key stays server-only: {text}");
}
+390
View File
@@ -0,0 +1,390 @@
# cli-filelist
## Goal
Give the `vfmt` CLI the same front door the server got in M1: `vfmt -f
project.f` formats or lints exactly the files an EDA filelist names, reusing
`vfmt_core::filelist::read` unchanged. M1 deliberately stopped at the config
key and the language server — "a `vfmt -f` flag is its own change with its own
exit-code questions" (`docs/features/filelist/README.md`, Status). This is that
change: the flag, the answers to those questions, and nothing else. No new
parsing, no new dependency, no version bump.
## Assumptions
- **A filelist is an *input*, not a *mode*.** `-f` adds files to whatever the
command line already names; it does not replace, filter or reorder them. So
`vfmt -f a.f`, `vfmt rtl/` and `vfmt -f a.f rtl/ tb/top.sv` are all ordinary
runs, and having neither positional inputs nor `-f` is still the usage error
it always was.
- **Listed paths are named paths.** `--exclude` and `.gitignore` filter
*directory walks* only (`docs/features/parallel-files/README.md`: "a path
named on the command line is never ignored"). A filelist path was written
down by a human in a project file, which is at least as explicit as typing
it as an argument, so the same rule applies: it is processed. The opposite
choice would mean a `.gitignore` in a generated-RTL directory could silently
shrink the build's own file set.
- **Warnings are warnings.** Everything M1's parser reports as a warning — a
listed file that no longer exists, an option vfmt has no table for, an unset
`$VAR`, a repeated filelist, a `-f` chain past `MAX_NESTING_DEPTH` — goes to
stderr as `warning: <filelist>:<line>: <what>` and leaves the exit code
alone. This matches the server, which shows the same strings and keeps
indexing. A stale line in a 400-file filelist must not fail CI; the run's
exit code reports what happened to the files that *do* exist.
- **The filelist itself is not.** `filelist::read`'s `Err` is reserved for the
root file being unreadable, the one case where the caller learns nothing at
all — a typo in the flag, or a path that CI did not generate. That is a hard
error: exit 2, before the worker pool starts, with nothing processed and
nothing written. Silently formatting only the positional inputs when the
filelist is missing would be the worst of both worlds.
- **Two names for one file are one file.** Dedup is by lexical absolute path
(`.`/`..` folded, symlinks deliberately not resolved — the same rule
`filelist::Reader::normalize` and `config::Discovery::absolute` already
use), and the *first* spelling seen is the one vfmt reports, so
`vfmt -f p.f rtl/a.sv` still says `rtl/a.sv` and not the absolute path the
filelist produced. This also dedups repeats that have nothing to do with
filelists (`vfmt rtl/ rtl/a.sv`), which previously formatted the file twice
— see the Work log.
- **The `filelist` key in `vfmt.toml` stays server-only.** Auto-consuming it
would make `vfmt rtl/` process files that are not under `rtl/`, and
`vfmt --check .` in CI change its file set because someone added a key for
the editor's benefit. A CLI filelist is named on the command line, where it
is visible in the CI log. `--help` says so in the CONFIGURATION section.
- **An empty result is the existing empty-input error.** A filelist naming
nothing that exists produces its warnings and then `no Verilog files found`,
exit 2 — the same answer `vfmt empty-dir/` has always given.
- **`-f` is not `-F`.** vcs's `-F` (paths relative to the *invoking*
directory rather than to the filelist) is not supported, exactly as M1 left
it. Nobody has asked.
## Handshakes
### Consumed
- `vfmt_core::filelist::read(&Path) -> Result<Filelist, String>` — unchanged,
used exactly as the server uses it. Only `files` and `warnings` are read:
`incdirs` and `defines` are meaningless to a formatter that does not
preprocess, and are dropped.
- `vfmt_core::walk::collect_files` / `config::Discovery` — unchanged. Filelist
files skip `collect_files` entirely (they are exact paths, and running them
through it would only re-`is_file()` them), but they go through
`Discovery::for_file` in the same loop as every other file, so a listed file
is formatted with its *own* directory's `vfmt.toml`.
### Promised
- **The frozen exit-code contract is untouched.** 0 nothing to do, 1
`--check`/`--diff` would reformat or `check` found violations, 2 error.
Filelist warnings are none of those three; the only new exit-2 cases are
usage errors (an unreadable filelist, `-f` with no value, `-` or `--lines`
with `-f`).
- **stdout stays machine-readable.** Every warning goes to stderr, so
`vfmt check --output-format json -f p.f` still prints exactly one JSON array
on stdout. Pinned by a test.
- **`Options` gains `filelists: Vec<String>`** (`crates/vfmt/src/args.rs`).
Anything constructing an `Options` literal needs the field; nothing outside
`crates/vfmt` does.
### Rejected combinations (all exit 2, all decided at parse time)
| Command line | Why |
|---|---|
| `vfmt -f p.f -` | stdin is one anonymous buffer; a filelist is a set of paths on disk. Reading both would mean ignoring one. |
| `vfmt --lines 3-9 -f p.f` | Same reason `--lines` rejects a directory: line numbers name lines of *a file*, and a filelist is a file set. |
| `vfmt -f` | Missing flag value, like every other flag. |
Everything else about a run is unchanged by `-f`: the cache, `--threads`,
`--stdout`, `--diff`, `--fix`, config discovery and the summary line all
behave exactly as they do for a file named as an argument.
## Status / TODO
- [x] `-f <FILELIST>` on `vfmt`, `vfmt format`, `vfmt --check/--diff` and
`vfmt check`; repeatable; combines with positional inputs
- [x] Warnings to stderr as `warning: ...`, exit code unaffected; unreadable
filelist is exit 2 with nothing processed
- [x] Listed paths bypass `--exclude` and `.gitignore`, like named files
- [x] Dedup across filelists, positional files and directory walks
- [x] `-` and `--lines` rejected with `-f`; empty result is the existing
"no Verilog files found" error
- [x] `--help`: usage line, `-f` entry, a `FILELISTS:` section, `--lines`
wording, and the CONFIGURATION note that the `filelist` key stays
server-only
- [x] `README.md`: `-f` in the CLI examples and in the configuration section
- [x] Tests: 3 unit (2 `args.rs`, 1 `main.rs`) + 10 e2e
(`crates/vfmt/tests/cli.rs`);
`cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`
- [ ] Not done, deliberately: the `vfmt.toml` `filelist` key is still not read
by the CLI (Assumptions), and `+incdir+`/`+define+` still feed nothing
on this side — the formatter and the linter do not preprocess.
- [ ] Not done, deliberately: no `-F`, and no quoting for paths containing
whitespace (both inherited non-goals from `filelist`).
## Work log
### 2026-08-25 — dev agent, M13
Three files of code, all in `crates/vfmt`.
- **`src/args.rs`** — `Options::filelists`, the `-f` arm (placed before the
`s if s.starts_with('-')` catch-all so it is a flag, not an unknown option),
the emptiness check widened to "no inputs *and* no filelists", and the two
rejected combinations. Both rejections live in `parse_from` rather than in
`gather`, so they are cheap unit tests and so `vfmt -f p.f -` cannot reach
the stdin path at all: `is_stdin()` is checked before `gather` in `main`,
and a run that read stdin while ignoring `-f` would be the silent-wrong
answer this feature exists to avoid.
- **`src/main.rs`** — `filelist_files` (read each list in flag order, print
its warnings, collect its files), `dedup` and `absolute`, and three lines in
`gather`. Filelist files are appended *after* the positional inputs' walk,
so a file named both ways keeps the shorter spelling the user typed.
- **`tests/cli.rs`** — the e2e block at the end of the file.
Decisions worth recording:
- **`gather` prints the warnings itself.** It is the only place in `gather`
that says anything, and the doc comment says why: the warnings have to be
visible on a run that *succeeds*, and returning them would mean changing
`gather`'s signature and both of its callers to thread a `Vec<String>`
through to a printing site that does nothing else. `gather` already runs
once, serially, before the pool exists, so there is no ordering hazard —
every warning is on stderr before the first file is touched.
- **Dedup is global, not filelist-vs-command-line.** It was tempting to dedup
only across the two sources, but the same `HashSet` costs nothing and fixes
a pre-existing sharp edge: `vfmt rtl/ rtl/a.sv` used to format `a.sv` twice
and count it twice, and with `--threads > 1` two workers could hold the same
path. **This is a behavior change beyond the flag** — a run naming one file
twice now reports `1 file`, not `2` — and it is the only one. No existing
test asserted the old count.
- **A fourth copy of `normalize` was not written; a third one was.**
`absolute` in `main.rs` is the same twelve lines as
`filelist::Reader::normalize` and `config::Discovery::absolute`, which QA
already examined once and accepted as deliberate duplication (filelist QA
log, Finding 3). The alternative was widening `vfmt_core`'s public API with
a `pub fn normalize(path, cwd)` for a single caller, which CLAUDE.md's
"don't build the abstraction for a second user that doesn't exist" rule and
the "don't touch files outside your feature's scope" rule both argue
against. Recorded here so a future third caller knows to extract it.
Unlike the other two, this copy is *only* a dedup key: the path vfmt reads,
writes and reports is always the one it was given.
- **`--lines` with `-f` is a new error, not a new behavior.** Today
`--lines` only rejects a *directory*; a filelist would have been accepted
and would have applied "line 12" to all 400 files. Rejecting matches the
spirit of the existing rule, and the message is worded like it.
- **The `+incdir+`/`+define+` a filelist carries are dropped without a word.**
They are not warnings — `filelist::read` accepts them silently and the CLI
simply has no use for them. Saying "ignoring +incdir+" on every run of every
real filelist would be noise.
**Files touched outside `crates/vfmt`**: two, both documentation this change
makes untrue and both edited in the style each file already uses.
`README.md` — the CLI example block and the configuration section's "the CLI
does not consume it yet". `docs/features/filelist/README.md` — its Status item
"the CLI does not consume `filelist` yet ... a `vfmt -f` flag is its own
change", struck through and answered the same way that README already resolved
its `+incdir+` item after M10. `TODO.md` and the umbrella checklist were left
for the lead, per the brief — M13's box is still unchecked.
**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy
--all-targets` silent; `cargo test --workspace` green — 1556 tests, 13 of them
new (2 unit in `args.rs`, 1 in `main.rs` pinning the dedup key, 10 e2e in
`tests/cli.rs`: `crates/vfmt`'s two suites went 30 → 33 and 71 → 81). The e2e
set covers: `-f`
alone with a nested `-f` and relative resolution; `-f` plus positional files
and a directory with triple dedup; two `-f` flags; a missing listed file
(warning on stderr, others formatted, exit 0) and an unknown option; an
unreadable filelist (exit 2, nothing written); `--check` with `-f` (exit 1,
then exit 0 once formatted); `vfmt check -f` in text and JSON form (stdout is
one array, warnings on stderr); a filelist named from an unrelated working
directory; a listed file that both `--exclude` and `.gitignore` name; and the
four usage errors. Also hand-driven against the built binary from two
different working directories before the tests were written.
## QA log
### 2026-08-25 — QA agent, M13
**Gates.** `cargo fmt --all -- --check` clean, `cargo clippy --all-targets
--workspace` silent, `cargo test --workspace` green — **1556 tests**,
matching the Work log's count exactly (0 failed, 4 pre-existing `#[ignore]`
elsewhere, unrelated to this feature).
**Exit-code contract audit.** Built `target/release/vfmt` and drove the
matrix by hand: clean file via `-f` → 0; would-reformat via `-f --check` →
1; lint violation via `check -f` → 1; a filelist naming only a missing file
→ warning + `no Verilog files found` → **2** (empty-after-skip, matching
Assumptions' "An empty result is the existing empty-input error" — confirmed
this is the answer, not a bare 0-with-warning); a missing file *alongside* a
present one → warning + the present file processed, exit 0; unreadable root
filelist → 2, nothing written (`nope.f` named in the message); a listed
file with a genuine parse error → 2, `1 file failed to format`; `--check`
with one file erroring and one that would reformat → 2, both lines printed,
error outranks the would-reformat count in the exit code. All eight cells
match `README.md`'s frozen 0/1/2 table exactly. Nothing here reaches an
exit code outside {0,1,2}.
**Claims verified directly, all pass:**
- `-f` repeatable, combines with positional inputs, `-f` alone is a valid
complete command line (`args.rs:378`, tested live).
- Dedup: `vfmt --check rtl/ rtl/a.sv` reports `a.sv` exactly once and the
summary reads `2 files would be reformatted` for a 2-file tree, not 3 —
confirmed the behavior change is real and works as claimed.
- First-spelling-wins is honored across sources, not just within one:
`vfmt --check -f p.f rtl/a.sv` (filelist lists `rtl/a.sv`, positional arg
also names it) reports `rtl/a.sv`, never the filelist's absolute
resolution — matches the Assumptions' worked example verbatim.
- Warnings go to stderr only, never touch the exit code: missing listed
file, unknown `-y` flag, `$VAR`, filelist-lists-itself all produced
`warning: ...` on stderr with the run otherwise succeeding.
- `check -f --output-format json`: stdout is exactly one parseable JSON
array (piped through `python3 -m json.load`, 2 entries) with the missing-
file warning only on stderr. Text-mode `check -f` likewise.
- `vfmt.toml`'s `filelist` key: `--help`'s CONFIGURATION section says
"read by vfmt-server only" as claimed; the CLI never opens the key
(unchanged from before this feature — not separately re-verified beyond
reading the help text and the diff, since the CLI simply never reads
`FileConfig::filelist` anywhere in `crates/vfmt`).
- `-f` + `-`, `--lines` + `-f`, bare `-f`: all three rejected at parse time,
exit 2, with the exact messages the README's Rejected-combinations table
promises.
- `--fix`, `--stdout` (multi-file, concatenated — pre-existing behavior,
unaffected by `-f`), `--threads 1` vs default (`--stdout` output
byte-identical across thread counts), and the cache (`--check -f` twice:
second run reports `1 file from cache`) all behave exactly as they do for
a file named directly, as promised.
- CRLF filelist: works with no special-casing needed, `str::lines()`
already strips `\r` (same as M1's own QA finding).
- `$VAR` expansion to an absolute path: works (first attempt was a shell
quoting mistake on my end, not a vfmt bug — corrected and re-run).
- A filelist that `-f`s itself: one warning, no infinite loop, its own file
still processed once.
- Usage errors: `-f` with no value → `error: -f requires a value`, exit 2.
Repeated identical `-f list.f -f list.f` → deduped, one file reported, not
two. `vfmt -- -f` → `error: unknown option: --`, exit 2 — vfmt has no `--`
end-of-options handling anywhere (pre-existing, not part of this
feature's scope; noting only because the brief asked).
**Finding 1 (Medium, not a blocker) — the dedup note overclaims what it
fixes, and the underlying write is non-atomic; both predate M13.**
`main.rs:344` dedups by **lexical** absolute path only (confirmed by
reading `absolute()`, `main.rs:354-367`: pure `.`/`..` component folding, no
`fs::canonicalize`, no symlink resolution — matches `filelist::Reader::
normalize` and `config::Discovery::absolute` exactly, as documented).
Reproduced directly: a real file and a symlink alias to it, named through
two different spellings (`rtl/a.sv` positional + `alias.sv` via `-f`,
`alias.sv -> rtl/a.sv`), are **not** deduped — both are queued and both get
formatted independently:
```
$ vfmt --check rtl/a.sv -f list.f # list.f names alias.sv, a symlink to rtl/a.sv
would reformat: rtl/a.sv
would reformat: /.../alias.sv
2 files would be reformatted
```
Separately, `process_file` (`main.rs:255`) and the `--fix` write path
(`lint.rs:103`) both write with plain `std::fs::write(file, &out)` —
open-truncate-write, **not** tempfile+rename. `cache.rs:91` sits right next
to this code and *does* the atomic tempfile+rename dance, with a doc comment
explicitly saying "Writes the cache back, atomically" — so the codebase
already has the pattern, just not applied to the file the user actually
asked vfmt to rewrite.
Put together: two workers (`--threads > 1`) that land on the same inode
through two spellings — a symlink pair being the realistic case, since
lexical dedup already closes the plain-duplicate-path case this milestone
set out to fix — can, if their `open(O_TRUNC)`/`write` calls interleave,
produce a torn file that is neither worker's intended output. This is a
real instance of the class of bug hard invariant 1 rules out ("never
corrupt code... no partial output"), not a hypothetical.
**Severity assessment, honestly:** this is **not new in M13** and **not
worsened by it**. Before this milestone there was no dedup at all, so
`vfmt a.sv a.sv` (no symlink needed) already put two workers on one path
under `--threads > 1`, and a symlinked pair had exactly the same exposure
`collect_files` never resolves symlinks either (`walk.rs`, confirmed by
reading it — no `canonicalize`/`read_link` anywhere in `vfmt_core`). M13's
dedup is a strict improvement: it closes the common, likely case (the same
literal path named twice) that used to double-process on every run of
`vfmt rtl/ rtl/a.sv`; it was never advertised as closing the symlink case,
and the README's own Assumptions section says so precisely ("symlinks
deliberately not resolved"). What I'd push back on is only the Work log's
framing — "fixes a pre-existing sharp edge... two workers could hold the
same path" reads as though the write-race is handled, when only its most
common trigger is. I did not manage to force an actual observed corruption
in a 15-round, 40-pair, 8-thread stress test (APFS on this machine appears
to serialize small concurrent writes to one inode closely enough in
practice that the window didn't get hit) — absence of a repro in a
best-effort black-box run is not proof the window can't be hit on slower
storage, larger files, or a different OS/filesystem, so I'm not downgrading
this to "theoretical."
**Not filing this as a blocking finding for M13** — it is outside this
feature's stated scope (`process_file`/`lint.rs` weren't touched here, and
CLAUDE.md's "don't touch files outside your feature's scope" cuts against
fixing it inside this change), it predates M13, and M13 does not make it
worse. Recommend two follow-ups for the backlog, independent of each other:
(1) make the source-file write atomic (tempfile+rename, mirroring
`cache.rs:91`) — this alone would make even a two-worker race benign, since
a rename is atomic and both workers produce byte-identical content; (2)
optionally widen the dedup key to a canonicalized path for a second line of
defense. (1) is the one that actually satisfies hard invariant 1 under
concurrent access; (2) only narrows how often (1) would matter. Suggest the
Work log's "two workers could hold the same path" sentence be softened to
say the fix is for the literal-duplicate case, not the general one, since a
future reader could otherwise believe the race is closed.
**Finding 2 (trivial, accepted, not filed as a real finding) — third copy
of the lexical normalizer.** `main.rs:354-367`'s `absolute()` is confirmed
byte-for-byte-equivalent in logic to `filelist::Reader::normalize` and
`config::Discovery::absolute`. This is the same duplication QA already
examined and accepted once (`docs/features/filelist/README.md`, QA Finding
3); the dev's Work log correctly cites that precedent, and CLAUDE.md's
"don't build the abstraction for a second user that doesn't exist" cuts the
same way here as it did there. Agree with leaving it; flag for extraction
if and when a fourth caller appears, as the Work log itself already says.
**+incdir+/+define+ silent drop: agree, reasoning holds for `check` too.**
Verified by reading `filelist_files` (`main.rs:328-338`): only `list.files`
and `list.warnings` are ever read; `list.incdirs`/`list.defines` are
untouched anywhere in `crates/vfmt`. Checked whether any M12 lint rule
(`crates/vlog_linter/src/rules/`) consults an include graph or any
cross-file state — grepped the whole crate for `incdir`/`include_graph`/
`cross-file`/`workspace`: zero hits. Every existing linter rule operates on
one file's own parse tree (confirmed by `context.rs`/`visit.rs` taking a
single source and no include resolver). `` `include`` resolution using
`incdirs` is M10's, and lives entirely in `vfmt_server` — the CLI has never
resolved includes at all, filelist-fed or not. So the reasoning "vfmt
doesn't preprocess, so incdirs genuinely don't matter" holds for the linter
exactly as it does for the formatter; nothing in M12 would have consulted
them even if they were threaded through.
**No fixes applied.** Nothing here rose to "small unambiguous fix" — the
overclaim is a wording issue in the Work log's prose (the lead's call
whether to soften it), and the write-atomicity gap is a real but
out-of-scope design change, not a typo.
**Verdict: ship.** Every claim in the Handshakes/Status/Assumptions
sections checks out against the code and against the exit-code contract
under direct adversarial testing; all three gates are clean at the exact
count claimed. Finding 1 is worth a backlog entry (atomic writes, mirroring
the pattern already in `cache.rs`) but is pre-existing, not introduced or
worsened by this milestone, and fixing it belongs to a change that touches
`process_file`/`lint.rs`, which is outside `cli-filelist`'s scope.
## Review
**2026-08-25 — lead.** Reviewed after QA's ship verdict; gates run
independently (1556 tests, 0 failures). The semantics decisions are the
right ones, each argued in place — listed paths bypassing exclude rules
matches the positional-arg precedent exactly, the `--lines` + `-f`
rejection prevents a silent 400-file surprise, and keeping the vfmt.toml
key server-only respects the CLI user who never asked for it. QA's
exit-code matrix confirms the frozen contract untouched, including both
ambiguous cells. QA's medium find — lexical-only dedup plus non-atomic
`fs::write`, a torn-file window that predates M13 and that M13 narrows
rather than widens — is real and now filed in TODO.md §1 as its own
correctness item (atomic tempfile+rename writes, mirroring cache.rs).
The third normalizer copy is accepted per the no-abstraction-for-a-
second-user rule, third time consistent. Accepted; M13 checked off.
+7 -2
View File
@@ -159,9 +159,14 @@ extension code change.
README config and editor sections
- [x] Unit tests in `vfmt_core` and `vfmt_server`; `cargo fmt`, `cargo
clippy --all-targets`, `cargo test` all clean
- [ ] Not done, deliberately: the CLI does not consume `filelist` yet
- [x] ~~Not done, deliberately: the CLI does not consume `filelist` yet
(M1 is config-level plumbing plus the server; a `vfmt -f` flag is its
own change with its own exit-code questions).
own change with its own exit-code questions).~~ **M13** is that change:
`vfmt -f project.f` reuses `read` unchanged and answers the exit-code
questions this line predicted (warnings never move the exit code, an
unreadable root filelist is exit 2) —
`docs/features/cli-filelist/README.md`. The `vfmt.toml` **key** is still
read by the server only, now on purpose rather than for want of a flag.
- [x] ~~Not done, deliberately: `+incdir+`/`+define+` feed nothing.~~
`` `include`` resolution arrived in M10 and consumes `Filelist::incdirs`
unchanged, exactly as this line predicted — resolved, in filelist order,
+2 -1
View File
@@ -171,7 +171,7 @@ built but nothing consumes yet. Ordered by value ÷ cost:
multiply-driven: TODO.md §7 calls this the differentiation Verible
cannot do, `vlog_semantic` has existed for rounds, and no semantic rule
ships yet.
- [ ] **CLI `-f` filelist flag** — the vfmt.toml `filelist` key and the
- [x] **CLI `-f` filelist flag** — the vfmt.toml `filelist` key and the
server consume M1's parser; `vfmt -f files.f` (format/lint exactly the
project's files) still does not exist.
- [ ] **Single-step macro expansion on hover** — the define-table README
@@ -267,6 +267,7 @@ commit — in order:
- [x] M10 include-nav — done, one QA HIGH reworked, reviewed
- [x] M11 hierarchy — done, QA doc-fixes in-round, reviewed
- [x] M12 semantic-lints — done, one QA medium reworked, reviewed
- [x] M13 cli-filelist — done, QA clean first pass, reviewed
## Work log