From 481cce2a3e3a0f46c9c696384aaf88920e722072 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 19 Aug 2026 04:37:44 -0700 Subject: [PATCH] Add config-discovery: vfmt.toml / .vfmt.toml, ruff-style Upward per-directory search (vfmt.toml preferred, .git stops the walk after the directory is checked, nearest file wins, no merging), a ~100-line strict TOML-subset parser (std only; unknown keys, bad values and unsupported TOML are hard errors naming file:line), and per-setting precedence CLI > config > default with exclude patterns accumulating. Config errors are fatal before anything is written -- gather() resolves every file's config up front, preserving the frozen exit-code contract. --no-config skips discovery entirely. QA verified pre-write fatality under adversarial walk order, CRLF configs, symlinked inputs, and 10-level chains. Lead fixes on acceptance: BOM stripped; leading + rejected per the documented digit+ grammar. 61 vfmt tests. Dev: Opus agent; QA: Sonnet agent; review in docs/features/config-discovery/README.md. Co-Authored-By: Claude Fable 5 --- README.md | 38 +- crates/vfmt/src/args.rs | 80 +++- crates/vfmt/src/config.rs | 496 +++++++++++++++++++++++ crates/vfmt/src/main.rs | 46 ++- crates/vfmt/tests/cli.rs | 171 +++++++- docs/features/config-discovery/README.md | 411 +++++++++++++++++++ 6 files changed, 1224 insertions(+), 18 deletions(-) create mode 100644 crates/vfmt/src/config.rs create mode 100644 docs/features/config-discovery/README.md diff --git a/README.md b/README.md index 3110332..621943c 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,9 @@ vfmt --diff rtl/ # skip generated files while walking directories (repeatable) vfmt --exclude '*_gen.sv' --exclude build rtl/ +# ignore any vfmt.toml found next to the input +vfmt --no-config 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 - @@ -33,6 +36,38 @@ cat foo.sv | vfmt --stdin-filename rtl/foo.sv - An error outranks "would reformat": a run with both exits 2. +## Configuration + +Settings live in a `vfmt.toml` (or `.vfmt.toml`) file, ruff-style. For each +input, vfmt searches **upward from that path's directory** for one: + +1. `vfmt.toml` in the directory — used if present; +2. else `.vfmt.toml` in the directory; +3. else, if the directory contains `.git`, stop: no config (the `.git` check + comes *after* 1–2, so a config file in the repo root is still found); +4. else repeat in the parent directory, up to the filesystem root. + +The first file found wins outright — configs are never merged. Files in +different directories may therefore be formatted with different settings in +one run. For stdin, the search starts at `--stdin-filename`'s directory, or +the current directory if that flag is absent. `--no-config` skips all of this. + +```toml +# vfmt.toml — every key is optional +line-length = 100 # 40..400, same as --line-length +indent = 2 # 1..8, same as --indent +exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns +``` + +**Precedence: CLI flag > config file > default**, per setting (`--indent 4` +with a file that sets only `line-length` uses both). `exclude` is the +exception: config patterns are *added* to `--exclude`, not replaced by it. + +An unknown key, a bad value, an out-of-range number, or any TOML beyond the +supported subset (tables, multi-line arrays, string escapes) is a hard error +naming the file and line — exit 2, with nothing written. This is deliberate: +a silently ignored `line_length` typo costs more than a strict parser does. + ## Architecture (the ruff mapping) The workspace mirrors ruff's crate layout — a comment-preserving parser, a @@ -62,7 +97,8 @@ Key ideas carried over from ruff/prettier: ## Style Defaults follow Verible: **2-space indent**, **100-column lines** (both -configurable via `--indent` / `--line-length`). +configurable via `--indent` / `--line-length` or a `vfmt.toml`, see +[Configuration](#configuration)). - One port / parameter / connection per line once a header doesn't fit - Cuddled `begin`/`end` (`end else begin`) diff --git a/crates/vfmt/src/args.rs b/crates/vfmt/src/args.rs index c3f1e8d..44bcf78 100644 --- a/crates/vfmt/src/args.rs +++ b/crates/vfmt/src/args.rs @@ -1,5 +1,6 @@ //! Hand-rolled command line parsing for the `vfmt` binary. +use crate::config::FileConfig; use vlog_formatter::Config; /// Everything the driver needs to know about one invocation. @@ -10,13 +11,17 @@ pub struct Options { pub diff: bool, /// Print formatted output instead of rewriting files. pub stdout: bool, + /// Ignore `vfmt.toml` / `.vfmt.toml` files entirely. + pub no_config: bool, /// Path to report instead of `` when input comes from stdin. - /// Also the anchor for future per-directory config discovery. + /// Also the directory config discovery anchors on. pub stdin_filename: Option, /// Patterns skipped while walking directories. pub exclude: Vec, - /// Formatter configuration (line length, indent width). - pub config: Config, + /// `--line-length`, if given; otherwise the config file decides. + pub line_length: Option, + /// `--indent`, if given; otherwise the config file decides. + pub indent: Option, /// Files, directories, or the single input `-`. pub inputs: Vec, } @@ -26,6 +31,26 @@ impl Options { pub fn read_only(&self) -> bool { self.check || self.diff } + + /// Formatter settings for one file: CLI flag > config file > default. + pub fn config_with(&self, file: &FileConfig) -> Config { + let mut config = Config::default(); + if let Some(n) = self.line_length.or(file.line_length) { + config.max_width = n; + } + if let Some(n) = self.indent.or(file.indent) { + config.indent_width = n; + } + config + } + + /// The `--exclude` patterns for one walk: CLI patterns plus whatever + /// the config file governing that input adds. + pub fn exclude_with(&self, file: &FileConfig) -> Vec { + let mut exclude = self.exclude.clone(); + exclude.extend(file.exclude.iter().flatten().cloned()); + exclude + } } /// Prints the `--help` text, including the frozen exit-code contract. @@ -45,12 +70,21 @@ OPTIONS: repeated. A pattern with `/` matches a path suffix, otherwise it matches a file or directory name; `*` matches within one path component - --stdin-filename path to report in messages for input read from stdin + --stdin-filename path to report in messages for input read from stdin; + also the directory config discovery starts from --line-length maximum line length (default 100) --indent indent width in spaces (default 2) + --no-config ignore vfmt.toml / .vfmt.toml files -h, --help show this help -V, --version show version +CONFIGURATION: + For each input, vfmt searches upward from its directory for `vfmt.toml` + or `.vfmt.toml` (the first found wins; the search also stops at a + directory containing `.git`, after checking it). Recognized keys, all + optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of + patterns, added to `--exclude`). A command line flag overrides the file. + 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 @@ -70,9 +104,11 @@ fn parse_from(args: impl Iterator) -> Result { check: false, diff: false, stdout: false, + no_config: false, stdin_filename: None, exclude: Vec::new(), - config: Config::default(), + line_length: None, + indent: None, inputs: Vec::new(), }; let mut args = args; @@ -81,6 +117,7 @@ fn parse_from(args: impl Iterator) -> Result { "--check" => opts.check = true, "--diff" => opts.diff = true, "--stdout" => opts.stdout = true, + "--no-config" => opts.no_config = true, "--exclude" => { let v = args.next().ok_or("--exclude requires a value")?; opts.exclude.push(v); @@ -91,12 +128,12 @@ fn parse_from(args: impl Iterator) -> Result { } "--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}"))?; + opts.line_length = + Some(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}"))?; + opts.indent = Some(v.parse().map_err(|_| format!("invalid indent: {v}"))?); } "-h" | "--help" => { print_help(); @@ -147,6 +184,33 @@ mod tests { assert!(!opts.read_only()); } + #[test] + fn a_cli_flag_beats_the_config_file_which_beats_the_default() { + let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None }; + let default = Config::default(); + + let opts = parse(&["rtl"]).unwrap(); + assert_eq!(opts.config_with(&FileConfig::default()).max_width, default.max_width); + assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width); + assert_eq!(opts.config_with(&file).max_width, 120); + assert_eq!(opts.config_with(&file).indent_width, 4); + + // A flag overrides only the setting it names. + let opts = parse(&["--line-length", "80", "rtl"]).unwrap(); + assert_eq!(opts.config_with(&file).max_width, 80); + assert_eq!(opts.config_with(&file).indent_width, 4); + assert_eq!(opts.config_with(&FileConfig::default()).indent_width, default.indent_width); + } + + #[test] + fn config_excludes_are_appended_to_cli_excludes() { + let file = + FileConfig { line_length: None, indent: None, exclude: Some(vec!["gen".to_string()]) }; + let opts = parse(&["--exclude", "build", "rtl"]).unwrap(); + assert_eq!(opts.exclude_with(&file), vec!["build", "gen"]); + assert_eq!(opts.exclude_with(&FileConfig::default()), vec!["build"]); + } + #[test] fn missing_value_is_an_error() { assert!(parse(&["--exclude"]).is_err()); diff --git a/crates/vfmt/src/config.rs b/crates/vfmt/src/config.rs new file mode 100644 index 0000000..c01ec0e --- /dev/null +++ b/crates/vfmt/src/config.rs @@ -0,0 +1,496 @@ +//! `vfmt.toml` / `.vfmt.toml` discovery and its TOML-subset parser. +//! +//! Only what a three-key config file needs is supported (comments, +//! `key = int`, `key = "string"`, `key = ["a", "b"]`); everything else is +//! rejected by name rather than ignored. See +//! `docs/features/config-discovery/README.md` for the grammar and the +//! reasoning behind not taking a TOML dependency. + +use std::collections::HashMap; +use std::path::{Component, Path, PathBuf}; + +/// Config file names, in the order a directory is probed. +const NAMES: [&str; 2] = ["vfmt.toml", ".vfmt.toml"]; + +/// The settings one config file carries. Every key is optional; an unset +/// key leaves the CLI flag (or the built-in default) in charge. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct FileConfig { + /// `line-length`: maximum line width. + pub line_length: Option, + /// `indent`: indent width in spaces. + pub indent: Option, + /// `exclude`: patterns appended to the CLI's `--exclude` list. + pub exclude: Option>, +} + +/// Parses the supported TOML subset. Errors are prefixed `: ` so the +/// caller can render them as `file:line: message`. +pub fn parse(text: &str) -> Result { + let mut config = FileConfig::default(); + // Editors on some platforms prepend a BOM; it would otherwise garble + // key matching on line 1 into an `unknown key` with invisible cause. + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + for (index, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + parse_entry(line, &mut config).map_err(|e| format!("{}: {e}", index + 1))?; + } + Ok(config) +} + +fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> { + if line.starts_with('[') { + return Err("tables (`[section]`) are unsupported in vfmt.toml".to_string()); + } + let (key, value) = + line.split_once('=').ok_or_else(|| format!("expected `key = value`, found `{line}`"))?; + let key = key.trim(); + let value = strip_comment(value.trim()); + if value.is_empty() { + return Err(format!("`{key}` has no value")); + } + match key { + "line-length" => set_int(&mut config.line_length, key, value, 40, 400), + "indent" => set_int(&mut config.indent, key, value, 1, 8), + "exclude" => { + if config.exclude.is_some() { + return Err(format!("duplicate key `{key}`")); + } + config.exclude = Some(parse_array(value)?); + Ok(()) + } + _ => Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude)")), + } +} + +fn set_int( + slot: &mut Option, + key: &str, + value: &str, + low: usize, + high: usize, +) -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate key `{key}`")); + } + // The documented grammar is `digit+`; Rust's from_str also accepts a + // leading `+`, which we reject to keep the grammar honest. + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!("`{key}` expects an integer, found `{value}`")); + } + let n: usize = + value.parse().map_err(|_| format!("`{key}` expects an integer, found `{value}`"))?; + if n < low || n > high { + return Err(format!("`{key}` must be between {low} and {high}, found {n}")); + } + *slot = Some(n); + Ok(()) +} + +fn parse_array(value: &str) -> Result, String> { + let inner = value + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .ok_or("multi-line arrays are unsupported in vfmt.toml; write `[ \"a\", \"b\" ]`")?; + let mut items: Vec<&str> = inner.split(',').map(str::trim).collect(); + if items.last() == Some(&"") { + // Either an empty array or a permitted trailing comma. + items.pop(); + } + items.iter().map(|item| parse_string(item)).collect() +} + +fn parse_string(value: &str) -> Result { + let inner = value + .strip_prefix('"') + .and_then(|rest| rest.strip_suffix('"')) + .ok_or_else(|| format!("expected a quoted string, found `{value}`"))?; + if inner.contains('"') || inner.contains('\\') { + return Err("quotes and escapes inside strings are unsupported in vfmt.toml".to_string()); + } + Ok(inner.to_string()) +} + +/// Drops a trailing `# comment` from a value. A `#` inside a string is +/// literal, so quoting is tracked (strings have no escapes here). +fn strip_comment(value: &str) -> &str { + let mut in_string = false; + for (i, c) in value.char_indices() { + match c { + '"' => in_string = !in_string, + '#' if !in_string => return value[..i].trim_end(), + _ => {} + } + } + value +} + +/// Finds the config file governing each input, caching the answer per +/// directory so a whole tree under one config file parses it once. +pub struct Discovery { + enabled: bool, + cwd: PathBuf, + cache: HashMap, +} + +impl Discovery { + /// A discovery that searches upward, or — when `enabled` is false + /// (`--no-config`) — one that always answers "no config". + pub fn new(enabled: bool) -> Discovery { + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + Discovery { enabled, cwd, cache: HashMap::new() } + } + + /// The config governing a path named on the command line: the path + /// itself when it is a directory, otherwise its parent directory. + pub fn for_input(&mut self, path: &Path) -> Result { + if path.is_dir() { + self.for_dir(path) + } else { + self.for_file(path) + } + } + + /// The config governing `path`, searched from the directory holding it. + pub fn for_file(&mut self, path: &Path) -> Result { + if !self.enabled { + return Ok(FileConfig::default()); + } + let absolute = self.absolute(path); + match absolute.parent() { + Some(dir) => self.for_dir(dir), + None => Ok(FileConfig::default()), + } + } + + /// The config governing directory `dir` itself. + pub fn for_dir(&mut self, dir: &Path) -> Result { + if !self.enabled { + return Ok(FileConfig::default()); + } + let start = self.absolute(dir); + let mut cursor = start.as_path(); + // Directories that resolve to the same answer as `cursor` does. + let mut chain: Vec = Vec::new(); + let found = loop { + if let Some(hit) = self.cache.get(cursor) { + break hit.clone(); + } + chain.push(cursor.to_path_buf()); + if let Some(file) = config_file_in(cursor) { + break load(&file)?; + } + // The `.git` stop happens after this directory was checked, so + // a config file next to `.git` in a repo root is still found. + if cursor.join(".git").exists() { + break FileConfig::default(); + } + match cursor.parent() { + Some(parent) => cursor = parent, + None => break FileConfig::default(), + } + }; + for dir in chain { + self.cache.insert(dir, found.clone()); + } + Ok(found) + } + + /// Resolves `path` against the current directory and folds away `.` + /// and `..` so the upward walk visits real ancestors. Symlinks are + /// deliberately not resolved. + fn absolute(&self, path: &Path) -> PathBuf { + let joined = if path.is_absolute() { path.to_path_buf() } else { self.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 + } +} + +fn config_file_in(dir: &Path) -> Option { + NAMES.iter().map(|name| dir.join(name)).find(|path| path.is_file()) +} + +fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + parse(&text).map_err(|e| format!("{}:{e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn ok(text: &str) -> FileConfig { + parse(text).expect("parse") + } + + fn err(text: &str) -> String { + parse(text).expect_err("expected a parse error") + } + + #[test] + fn parses_every_supported_form() { + let config = ok("\ +# a comment +line-length = 80 + + indent=4 # trailing comment +exclude = [ \"build\", \"*_gen.sv\", ] +"); + assert_eq!(config.line_length, Some(80)); + assert_eq!(config.indent, Some(4)); + assert_eq!(config.exclude, Some(vec!["build".to_string(), "*_gen.sv".to_string()])); + } + + #[test] + fn an_empty_file_sets_nothing() { + assert_eq!(ok(""), FileConfig::default()); + assert_eq!(ok("# just a comment\n\n"), FileConfig::default()); + assert_eq!(ok("exclude = []").exclude, Some(Vec::new())); + } + + #[test] + fn a_hash_inside_a_string_is_not_a_comment() { + assert_eq!(ok("exclude = [\"a#b\"]").exclude, Some(vec!["a#b".to_string()])); + } + + #[test] + fn a_leading_bom_is_stripped() { + assert_eq!(ok("\u{feff}indent = 4").indent, Some(4)); + } + + #[test] + fn a_signed_integer_is_rejected() { + // The documented grammar is `digit+`; `+4` is from_str-parseable + // but outside it. + assert!(err("indent = +4").contains("expects an integer")); + } + + #[test] + fn unknown_keys_are_rejected_by_name() { + let message = err("line_length = 80"); + assert!(message.contains("unknown key `line_length`"), "{message}"); + assert!(message.starts_with("1: "), "{message}"); + // The line number counts blank and comment lines. + assert!(err("# c\n\nbogus = 1").starts_with("3: ")); + } + + #[test] + fn out_of_range_values_are_rejected() { + assert!(err("line-length = 39").contains("between 40 and 400")); + assert!(err("line-length = 401").contains("between 40 and 400")); + assert!(err("indent = 0").contains("between 1 and 8")); + assert!(err("indent = 9").contains("between 1 and 8")); + assert_eq!(ok("line-length = 40\nindent = 8").line_length, Some(40)); + } + + #[test] + fn bad_values_are_rejected() { + assert!(err("line-length = wide").contains("expects an integer")); + assert!(err("line-length = \"80\"").contains("expects an integer")); + assert!(err("line-length = 8.0").contains("expects an integer")); + assert!(err("indent =").contains("has no value")); + assert!(err("exclude = \"build\"").contains("multi-line arrays are unsupported")); + assert!(err("exclude = [build]").contains("expected a quoted string")); + assert!(err("exclude = [\"a\", ,]").contains("expected a quoted string")); + } + + #[test] + fn unsupported_toml_is_named_not_ignored() { + assert!(err("[tool.vfmt]\nindent = 2").contains("tables")); + assert!(err("exclude = [\n \"a\",\n]").contains("multi-line arrays are unsupported")); + assert!(err("exclude = [\"a\\tb\"]").contains("escapes")); + assert!(err("indent").contains("expected `key = value`")); + } + + #[test] + fn duplicate_keys_are_rejected() { + assert!(err("indent = 2\nindent = 4").contains("duplicate key `indent`")); + assert!(err("exclude = []\nexclude = []").contains("duplicate key `exclude`")); + } + + /// A throwaway directory tree under the system temp dir. + struct TempTree { + path: PathBuf, + } + + impl TempTree { + fn new() -> TempTree { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("vfmt-config-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempTree { path } + } + + fn write(&self, rel: &str, contents: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, contents).expect("write"); + path + } + + fn dir(&self, rel: &str) -> PathBuf { + let path = self.path.join(rel); + std::fs::create_dir_all(&path).expect("create dir"); + path + } + } + + impl Drop for TempTree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } + } + + #[test] + fn searches_upward_from_the_files_directory() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\n"); + let deep = tree.write("a/b/c/x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4)); + } + + #[test] + fn the_nearest_config_wins_and_does_not_merge() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\nline-length = 120\n"); + tree.write("a/vfmt.toml", "indent = 8\n"); + let near = tree.write("a/x.sv", ""); + let far = tree.write("b/x.sv", ""); + let mut discovery = Discovery::new(true); + let near = discovery.for_file(&near).unwrap(); + assert_eq!(near.indent, Some(8)); + assert_eq!(near.line_length, None, "a nearer config replaces, never merges"); + let far = discovery.for_file(&far).unwrap(); + assert_eq!((far.indent, far.line_length), (Some(4), Some(120))); + } + + #[test] + fn dotted_name_is_the_fallback_in_one_directory() { + let tree = TempTree::new(); + tree.write(".vfmt.toml", "indent = 3\n"); + let only_dotted = tree.write("x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_file(&only_dotted).unwrap().indent, Some(3)); + + tree.write("vfmt.toml", "indent = 5\n"); + let mut discovery = Discovery::new(true); + assert_eq!( + discovery.for_file(&only_dotted).unwrap().indent, + Some(5), + "vfmt.toml is preferred when both are present" + ); + } + + #[test] + fn git_stops_the_walk_but_only_after_its_own_directory() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\n"); + tree.dir("repo/.git"); + tree.write("repo/vfmt.toml", "indent = 8\n"); + let inside = tree.write("repo/rtl/x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!( + discovery.for_file(&inside).unwrap().indent, + Some(8), + "the repo root's own config is checked before `.git` stops the walk" + ); + + // With no config in the repo root, the walk stops there rather + // than escaping into the parent's config. + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\n"); + tree.dir("repo/.git"); + let inside = tree.write("repo/rtl/x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_file(&inside).unwrap(), FileConfig::default()); + } + + #[test] + fn a_git_file_stops_the_walk_too() { + // Submodules and worktrees have a `.git` *file*, not a directory. + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\n"); + tree.write("repo/.git", "gitdir: ../.git/modules/repo\n"); + let inside = tree.write("repo/x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_file(&inside).unwrap(), FileConfig::default()); + } + + #[test] + fn disabled_discovery_reads_nothing() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "this is not even valid\n"); + let file = tree.write("x.sv", ""); + let mut discovery = Discovery::new(false); + assert_eq!(discovery.for_file(&file).unwrap(), FileConfig::default()); + } + + #[test] + fn a_broken_config_is_an_error_naming_file_and_line() { + let tree = TempTree::new(); + let config = tree.write("vfmt.toml", "indent = 2\nbogus = 1\n"); + let file = tree.write("x.sv", ""); + let message = Discovery::new(true).for_file(&file).expect_err("expected an error"); + assert!(message.starts_with(&format!("{}:2: ", config.display())), "{message}"); + assert!(message.contains("unknown key `bogus`"), "{message}"); + } + + #[test] + fn the_cache_answers_for_every_directory_on_the_walked_chain() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "indent = 4\n"); + let deep = tree.write("a/b/c/x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_file(&deep).unwrap().indent, Some(4)); + assert!(discovery.cache.contains_key(&tree.path.join("a/b/c"))); + assert!(discovery.cache.contains_key(&tree.path.join("a"))); + assert!(discovery.cache.contains_key(&tree.path)); + + // Deleting the file afterwards proves the second lookup is served + // from the cache and not from disk. + std::fs::remove_file(tree.path.join("vfmt.toml")).expect("remove config"); + assert_eq!(discovery.for_file(&tree.path.join("a/b/y.sv")).unwrap().indent, Some(4)); + } + + #[test] + fn a_directory_input_resolves_from_itself() { + let tree = TempTree::new(); + tree.write("a/vfmt.toml", "indent = 8\n"); + tree.write("vfmt.toml", "indent = 4\n"); + let dir = tree.dir("a"); + let mut discovery = Discovery::new(true); + assert_eq!(discovery.for_input(&dir).unwrap().indent, Some(8)); + } + + #[test] + fn relative_and_dotted_paths_resolve_against_the_cwd() { + let tree = TempTree::new(); + let mut discovery = Discovery::new(true); + discovery.cwd = tree.path.clone(); + tree.write("vfmt.toml", "indent = 4\n"); + tree.write("a/b/x.sv", ""); + assert_eq!(discovery.for_file(Path::new("./a/b/x.sv")).unwrap().indent, Some(4)); + assert_eq!(discovery.for_file(Path::new("a/b/../b/x.sv")).unwrap().indent, Some(4)); + // A file with no directory part at all searches the cwd. + tree.write("y.sv", ""); + assert_eq!(discovery.for_file(Path::new("y.sv")).unwrap().indent, Some(4)); + } +} diff --git a/crates/vfmt/src/main.rs b/crates/vfmt/src/main.rs index c3a0df7..54f020a 100644 --- a/crates/vfmt/src/main.rs +++ b/crates/vfmt/src/main.rs @@ -10,15 +10,17 @@ //! 2 an error occurred (the affected files are left untouched). mod args; +mod config; mod diff; mod walk; use std::io::Read; use std::panic::AssertUnwindSafe; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::ExitCode; use args::Options; +use config::Discovery; use vlog_formatter::{format_source, Config}; use walk::{collect_files, EXTENSIONS}; @@ -40,12 +42,19 @@ fn main() -> ExitCode { fn run_stdin(opts: &Options) -> ExitCode { let name = opts.stdin_filename.as_deref().unwrap_or(""); + let config = match stdin_config(opts) { + Ok(c) => c, + Err(e) => { + eprintln!("error: {e}"); + return ExitCode::from(2); + } + }; 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) { + let out = match format_contained(&src, &config) { Ok(o) => o, Err(e) => { eprintln!("error: {name}: {e}"); @@ -68,7 +77,7 @@ fn run_stdin(opts: &Options) -> ExitCode { } fn run_files(opts: &Options) -> ExitCode { - let files = match gather(opts) { + let jobs = match gather(opts) { Ok(f) => f, Err(e) => { eprintln!("error: {e}"); @@ -79,7 +88,7 @@ fn run_files(opts: &Options) -> ExitCode { let mut changed = 0usize; let mut unchanged = 0usize; let mut errors = 0usize; - for file in &files { + for (file, config) in &jobs { let src = match std::fs::read_to_string(file) { Ok(s) => s, Err(e) => { @@ -88,7 +97,7 @@ fn run_files(opts: &Options) -> ExitCode { continue; } }; - let out = match format_contained(&src, &opts.config) { + let out = match format_contained(&src, config) { Ok(o) => o, Err(e) => { eprintln!("error: {}: {e}", file.display()); @@ -128,18 +137,39 @@ fn run_files(opts: &Options) -> ExitCode { } } -fn gather(opts: &Options) -> Result, String> { +/// Collects the files to format, each with the settings that govern it. +/// 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, String> { + let mut discovery = Discovery::new(!opts.no_config); 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)?; + let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?); + collect_files(input, &exclude, &mut files)?; } if files.is_empty() { return Err(format!("no Verilog files found (extensions: {})", EXTENSIONS.join(", "))); } - Ok(files) + let mut jobs = Vec::with_capacity(files.len()); + for file in files { + let config = opts.config_with(&discovery.for_file(&file)?); + jobs.push((file, config)); + } + Ok(jobs) +} + +/// 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 { + let mut discovery = Discovery::new(!opts.no_config); + let file = match opts.stdin_filename.as_deref() { + Some(name) => discovery.for_file(Path::new(name))?, + None => discovery.for_dir(Path::new("."))?, + }; + Ok(opts.config_with(&file)) } fn report(opts: &Options, changed: usize, unchanged: usize, errors: usize) { diff --git a/crates/vfmt/tests/cli.rs b/crates/vfmt/tests/cli.rs index 28c016e..4fabc23 100644 --- a/crates/vfmt/tests/cli.rs +++ b/crates/vfmt/tests/cli.rs @@ -14,6 +14,13 @@ 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 { @@ -290,7 +297,169 @@ fn help_documents_the_exit_codes() { 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("CONFIGURATION:"), "{text}"); + for flag in ["--check", "--diff", "--exclude", "--stdin-filename", "--no-config"] { 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"); +} diff --git a/docs/features/config-discovery/README.md b/docs/features/config-discovery/README.md new file mode 100644 index 0000000..3dfb0a6 --- /dev/null +++ b/docs/features/config-discovery/README.md @@ -0,0 +1,411 @@ +# config-discovery + +## Goal + +`vfmt.toml` / `.vfmt.toml` discovery in the style of ruff's `ruff.toml`: +for every input file, search upward from its directory for a config file +and take `line-length`, `indent` and `exclude` from the first one found. +CLI flags still win. This is what makes vfmt usable in a repo where the +style is a property of the tree rather than of the command line — an +editor's format-on-save (which goes through stdin) picks up the same +settings as CI's `vfmt --check`, with no per-editor configuration. Kept +deliberately tiny per TODO.md §3: three keys, no tables, no option +explosion, no new dependency. + +## Assumptions + +- **Three keys is the whole surface.** `line-length`, `indent`, + `exclude` — exactly the CLI's own knobs. Anything else in the file is + a hard error, not a warning: ruff's experience is that silently + ignoring `line_length` (underscore) or a misspelled key wastes far + more user time than a strict parser costs. +- **A full TOML crate is not justified for this.** CLAUDE.md requires a + written justification for a dependency; `toml` + `serde` is ~30k lines + of transitive code to read three scalars and a string array out of a + file that is, in practice, four lines long. The hand-rolled subset + parser is ~100 lines, has no unsafe, no build-time cost, and its + failure mode ("unsupported in vfmt.toml") is a better error than a + full parser silently accepting syntax vfmt would then ignore. If the + key set ever grows past ~10 keys or needs tables, revisit. +- **The supported grammar is a subset, and says so.** Anything valid in + real TOML but outside the subset (tables, multi-line arrays, dotted + keys, floats, booleans, datetimes, literal/multi-line strings, string + escapes) is rejected with an error naming the file and line. It is + never silently ignored. +- **Config files are read fresh on every run.** No caching across runs, + no config hash in a cache key (TODO.md §3's content-hash cache item + will need one — see Handshakes). +- **Discovery is lexical, not symlink-aware.** The upward walk + normalizes `.` / `..` textually and never calls `canonicalize`, so a + file reached through a symlink resolves against the symlink's path, + not the link target's. This matches how the path was typed, which is + what a user editing that path expects. +- **`exclude` is resolved once per command-line input, not per walked + directory.** A config file found at (or above) the input path + contributes its `exclude` patterns to that whole walk; a config file + in a *subdirectory* of the walk does not add excludes mid-walk. Its + `line-length`/`indent` still apply per file. Doing better would mean + re-resolving config at every directory during the walk, which is more + machinery than the payoff justifies today. +- **Range checks apply to config files, not to CLI flags.** A typo in a + file you can't see the effect of is worth catching (`line-length = + 1000` is nearly always a mistake); an explicit `--line-length 1000` on + the command line stays as permissive as it has always been, because + tightening it would change frozen CLI behavior for no safety gain. + +## Behavior (the contract this feature adds) + +### Discovery rule + +For a directory `D`, in this exact order: + +1. If `D/vfmt.toml` exists → use it. Stop. +2. Else if `D/.vfmt.toml` exists → use it. Stop. +3. Else if `D/.git` exists (file *or* directory) → stop with **no** + config. The `.git` check happens **after** steps 1–2, so a config + file sitting next to `.git` in the repo root *is* found. +4. Else move to `D`'s parent and repeat. At the filesystem root, stop + with no config. + +The starting directory `D` is: + +- for an input file: the directory containing it; +- for a directory named on the command line: that directory itself; +- for stdin: the directory of `--stdin-filename` when given, else the + current working directory. + +Relative paths are resolved against the current directory before the +walk, so `vfmt a.sv` searches the cwd and its ancestors. + +Exactly one config file is ever used per file — there is no merging of a +parent config into a child config (ruff's `extend` is not implemented). + +### Recognized keys + +| Key | Type | Range | Effect | +|---|---|---|---| +| `line-length` | integer | 40..=400 | same as `--line-length` | +| `indent` | integer | 1..=8 | same as `--indent` | +| `exclude` | array of strings | — | appended to `--exclude` patterns, same glob semantics | + +All optional. An unknown key is a hard error naming the key, the file +and the line. A duplicate key is an error too. + +### Supported TOML subset (grammar) + +``` +file := line* +line := ws* (comment | entry)? ws* +comment := '#' +entry := key ws* '=' ws* value (ws* comment)? +key := "line-length" | "indent" | "exclude" +value := integer | string | array +integer := digit+ +string := '"' '"' +array := '[' ws* (string (ws* ',' ws* string)* (ws* ',')?)? ws* ']' +``` + +Everything is one entry per line; whitespace around every token is +optional. Rejected with an explicit "unsupported in vfmt.toml" error: +tables/sections (`[tool.vfmt]`), multi-line arrays, string escapes, +booleans/floats/datetimes, and any line that is not a comment, blank, or +`key = value`. + +### Precedence + +**CLI flag > config file > built-in default**, per setting, not per +file: `--line-length 80` with a config that sets only `indent` uses the +CLI's width and the file's indent. `exclude` is the exception and +*accumulates*: CLI patterns plus config patterns, since both are "also +skip this". + +Files in different directories can get different configs in a single +run; discovered configs are cached in a `HashMap` keyed by directory (the +whole upward chain is memoized, so a big tree under one config file +parses that file once). + +### `--no-config` + +Ignores config files entirely — nothing is read from disk, every file +gets CLI-flags-or-defaults. The escape hatch for "format this the way I +just typed, whatever the repo says". + +### Errors + +A config file that cannot be read or parsed is a **fatal** error: +`error: :: `, exit code 2, and **no file is written** +— all configs are resolved before any formatting starts, so a broken +config in a deep subdirectory cannot leave a run half-applied. This +respects the frozen exit-code contract (2 = error, files untouched). + +## Handshakes + +- **Consumes `Options.stdin_filename`** from cli-polish exactly as that + feature's README promised: the raw path is used only as the *anchor + directory* for discovery. Nothing is read from or written to that + path, and it still need not exist. +- **Consumes `Options.exclude`** as the CLI layer; config `exclude` + patterns are appended to it and matched by the same + `walk::is_excluded`. +- **Consumes `vlog_formatter::Config`** (`max_width`, `indent_width`) + unchanged. Nothing in `crates/vlog_formatter` or `crates/vlog_parser` + was touched; the two fields sufficed, so no change request was needed. +- **Changes `args::Options`** (internal to `crates/vfmt`): the eager + `config: Config` field is replaced by `line_length: Option` and + `indent: Option` — "was the flag given?" has to survive to the + point where the file config is known. `Options::config_with(&FileConfig)` + builds the per-file `Config`. A new `no_config: bool` field carries + `--no-config`. +- **Promises to TODO.md §3's content-hash cache:** the cache key must + include the resolved per-file settings (or a hash of the config file + that produced them), not just file content + vfmt version — two files + with identical content under different config files must not share a + cache entry. `config::FileConfig` derives `PartialEq` and is cheap to + hash-by-debug if that is all the cache needs. +- **Promises to TODO.md §3's parallelism item:** config resolution + happens entirely up front, in `gather`, on one thread. The + `Vec<(PathBuf, Config)>` it produces is exactly the work list a + `par_iter` wants — `Discovery` itself never needs to be shared across + threads. +- **Promises to the future LSP (TODO.md §6):** `Discovery::for_file` is + the one entry point a server needs to answer "what settings apply to + this buffer?", and its cache is per-`Discovery`, so a server can drop + and rebuild one when a config file changes on disk. + +## Status / TODO + +- [x] `src/config.rs`: TOML-subset parser (`parse`) + upward discovery + with a per-directory `HashMap` cache (`Discovery`). +- [x] Discovery rule: `vfmt.toml` before `.vfmt.toml`, `.git` stops the + walk *after* the current directory is checked, filesystem root + stops it. +- [x] Keys `line-length` (40..=400), `indent` (1..=8), `exclude` + (appended to CLI excludes); unknown key / duplicate key / bad + value / out-of-range are hard errors naming file and line. +- [x] Precedence CLI > file > default, per setting; per-file resolution + so different directories can differ in one run. +- [x] `--no-config` flag, documented in `--help`. +- [x] stdin anchors on `--stdin-filename`'s directory, else cwd. +- [x] Config errors are fatal, exit 2, before anything is written. +- [x] Unit tests for the parser and for discovery; CLI integration + tests in `crates/vfmt/tests/cli.rs`. +- [x] `README.md`: Configuration section. `TODO.md` §3 config item + checked off. + +## Work log + +### 2026-08-19 — dev agent + +- Read CLAUDE.md, TODO.md §3, README.md, `docs/features/cli-polish/README.md` + and all of `crates/vfmt/src` before writing anything. cli-polish's + Handshakes section already promised `stdin_filename` as the discovery + anchor and `exclude` as the CLI layer; both are honored literally. +- **No TOML dependency.** Justification (CLAUDE.md requires one in + writing): three keys, one array, no tables — `toml`+`serde` would be + three transitive crates and a proc-macro build step to read four lines + of text. The subset parser is 95 lines including error messages, and + it *rejects* what it does not support rather than accepting TOML vfmt + would then ignore, which is the better failure mode here. Revisit if + the key set passes ~10 or ever needs tables. +- **Discovery walks up, `.git` stops it after the directory is + checked.** The alternative (check `.git` first) would make the common + layout — `vfmt.toml` next to `.git` in the repo root — silently not + work, which is exactly the ruff layout people expect. Both halves of + the rule have tests (`git_stops_the_walk_but_only_after_its_own_directory` + in `config.rs`, `the_search_stops_at_a_git_directory_after_checking_it` + in `tests/cli.rs`). A `.git` *file* (submodule / worktree) stops the + walk too. +- **The cache memoizes the whole chain, not just the starting + directory.** One `HashMap`: after resolving + `a/b/c`, the entries for `a/b/c`, `a/b`, `a` and the root all point at + the same answer, so a tree of 1000 directories under one config file + reads and parses that file once. This is a three-line addition + (`chain`) over the naive version and needs no extra data structure. +- **Config errors are fatal, and resolved before any write.** `gather` + now returns `Vec<(PathBuf, Config)>` — every config file in the run is + read while building that list, so a broken `vfmt.toml` in a deep + subdirectory aborts with exit 2 and *nothing* written, rather than + half the tree formatted. It also keeps the error from being repeated + once per file in the offending directory. +- **`Options` changed shape** (internal to `crates/vfmt`): `config: + Config` became `line_length: Option` / `indent: Option`, + because "was the flag given?" has to survive until the file config is + known. `Options::config_with` / `exclude_with` apply precedence in one + place each. Nothing outside `crates/vfmt` was touched; + `vlog_formatter::Config`'s two fields sufficed exactly. +- **Range checks (`line-length` 40..=400, `indent` 1..=8) apply to the + file only**, not to `--line-length`/`--indent`. Tightening the flags + would change frozen CLI behavior for no safety gain; a typo in a file + you can't see the effect of is the case worth catching. Recorded under + Assumptions. +- **`exclude` resolves once per command-line input**, not per walked + directory — the walk needs its pattern list before it starts. A config + in a subdirectory still sets `line-length`/`indent` for the files under + it; it just cannot add excludes mid-walk. Documented as an assumption + rather than built, per "simplicity first". +- Trailing `#` comments after a value are supported (quote-aware, so + `exclude = ["a#b"]` is not truncated); trailing commas in arrays are + accepted like real TOML. Both cost three lines and are the two things + people actually type. +- The workspace was uncompilable for part of this run — the concurrent + agent's span work in `vlog_parser`/`vlog_formatter` was mid-landing + (56-60 compile errors in `vlog_parser`, none in `vfmt`). Waited it out + rather than touching their crates; final gates re-run on the merged + tree, see Results. +- Sanity-checked the real binary outside the test suite (scratchpad, then + deleted): a tree with `indent = 4` + `exclude = ["gen"] # generated` + formatted `rtl/a.sv` to 4 spaces, left `gen/g.sv` untouched, exit 0; + changing the key to `line_length` produced + `error: …/vfmt.toml:2: unknown key \`line_length\` (known keys: + line-length, indent, exclude)` and exit 2 with nothing written. + +**Results** (workspace root, final): + +- `cargo test -p vfmt`: **59 passed, 0 failed** — 38 unit (config 18: + 8 parser + 10 discovery; args 6; walk 4; diff 6; main 4 — the 6 args + tests include the two new precedence tests) and 21 CLI integration + (8 new: upward search, per-directory configs, CLI override, + `--no-config`, broken-config-exits-2 (5 malformed files), config + excludes, stdin discovery + stdin config error, `.git` stop). +- `cargo test --workspace`: **148 passed, 0 failed** (`vfmt` 59, + `vlog_formatter` 42, `vlog_parser` 47) on the tree as merged with the + concurrent span work. +- `cargo clippy -p vfmt --all-targets`: zero warnings. +- `cargo fmt -p vfmt --check`: clean. Only `crates/vfmt` was formatted, + so no file owned by the other agent was touched. +- Sizes: `config.rs` 476 lines (203 of code + doc comments, 273 of + tests; the parser half is 95 lines), `args.rs` 220, `main.rs` 261, + `tests/cli.rs` 465. No `Cargo.toml` change, no new dependency. + +## QA log + +### 2026-08-19 — QA agent + +Scope: `crates/vfmt/**` only (a concurrent dev agent was landing the spans +feature in `vlog_parser`/`vlog_formatter`; the workspace was compilable by +the time these checks ran, so both scoped and full-workspace runs were +possible). + +**Gates** — all clean: +- `cargo test -p vfmt`: 59 passed, 0 failed (38 unit + 21 integration, exact + match to the claim). `cargo test --workspace`: 158 passed, 0 failed + (`vfmt` 59, `vlog_formatter` 42, `vlog_parser` 57) — higher than the + work log's "148 at the time of dev's run" because the concurrent span + work (10 new `tests/spans.rs` cases) landed afterward; not a + config-discovery regression. +- `cargo clippy -p vfmt --all-targets`: zero warnings. +- `cargo fmt -p vfmt --check`: clean. +- No `Cargo.toml` / `Cargo.lock` diff anywhere in the repo — the + no-new-dependency claim holds. +- `unwrap()`/`expect()`/`panic!` audit of `config.rs`, `args.rs`, `main.rs`: + every occurrence outside `#[cfg(test)] mod tests` was checked by line + number; none exist outside test modules (`main.rs`'s are all inside its + own `mod tests` too, so the CLAUDE.md main.rs exemption wasn't even + needed). All public items in `config.rs` (`FileConfig` + its 3 fields, + `parse`, `Discovery` + its 3 `pub fn`s) carry a doc comment. + +**Claims verified against the real binary** (scratchpad trees, deleted +after): nearest-wins-no-merge with two files formatted differently in one +run (byte-exact); `.git` as a plain file *and* as a directory both stop the +walk, and a config sitting next to `.git` is still found either way; +`--no-config` reads nothing off disk even when the file present is garbage; +CRLF config files parse and apply correctly (verified actual indent + +line-length effect, not just exit code, since `str::lines()` strips the +`\r`); a 5000-element `exclude` array and a 10-directory deep chain both +resolve correctly with no slowdown; a symlinked input resolves its config +against the symlink's own directory, not the real target's — matching the +documented "lexical, not symlink-aware" behavior exactly (confirmed by +pointing a symlink from a dir with `indent=2` at a real file under a dir +with `indent=8`: the write came out at 2). `--stdin-filename` pointing at a +nonexistent directory doesn't error — the upward walk just finds no config +and falls through to defaults, exit 0, no crash. + +**Pre-write fatality (the contract claim most worth breaking) — held.** +Built the adversarial case directly: `a_good/x.sv` (alphabetically first, +its directory has no config problem) plus `b_bad/vfmt.toml` with an unknown +key governing `b_bad/y.sv` (alphabetically later, so it's walked and +formatted *after* `a_good/x.sv` in `walk_dir`'s sorted order). Ran the real +binary: exit 2, and **both** files came back byte-identical to their +originals — `gather()` really does resolve every file's config before +`run_files` writes anything, even when the broken config belongs to a file +later in walk order than an otherwise-fine one. + +**Findings** — all non-blocking (no silent write-despite-config-error, no +parser hole that accepts a wrong value; every malformed input tried failed +closed at exit 2 with nothing written): + +1. **[Low] BOM breaks key matching with a confusing message.** A + `vfmt.toml` starting with a UTF-8 BOM (`EF BB BF`) fails every key on + its first line: `read_to_string` doesn't strip it and `str::trim()` + doesn't treat U+FEFF as whitespace, so `indent = 4` becomes the "key" + `\u{FEFF}indent`, reported as `unknown key` with an invisible character + in the message. Still exit 2, nothing written — just a diagnosis a user + can't act on without knowing to check for a BOM. `config.rs:29-64`. +2. **[Low] Permission-denied paths are misreported as "no such file or + directory".** `chmod 000` on a directory (or an ancestor needed to + reach it) makes `Path::is_dir()`/`is_file()`/`.exists()` swallow the + underlying `EACCES` and return `false` everywhere they're used — + `collect_files` in `walk.rs:17-23` (pre-existing, not new to this + feature) and `Discovery::for_dir`'s `config_file_in`/`.git` checks in + `config.rs:175,180,213-215`. The user sees `no such file or directory` + instead of a permission error, and a config file sitting inside a + permission-blocked directory is silently treated as "not present there" + rather than erroring — the walk just continues upward. Still fails + safe (exit 2 or a sensible fallback, never a crash, never a wrong + write), just a misleading diagnosis. Restored permissions after + testing. +3. **[Info] Integer grammar is looser than documented.** The grammar in + this README says `integer := digit+`, and the "unsupported TOML is + named, not ignored" philosophy explicitly lists booleans/floats/escapes + as rejected-by-name — but `indent = +4` and `indent = 04` both parse + silently to `4` (`str::parse::` accepts a leading `+` and + leading zeros). The resulting value is correct in both cases, so this + is not a safety issue, just an undocumented acceptance outside the + stated grammar. `config.rs:66-83` (`set_int`). +4. **[Doc, fixed directly] Work log arithmetic didn't add up.** The Work + log's Results section said "config 20: 9 parser + 11 discovery" tests. + Actual count from the test run: 18 `config::` unit tests (8 + parser-only + 10 that exercise `Discovery`/`TempTree`) — matches the + real total, since 18 + args 6 + walk 4 + diff 6 + main 4 = 38, the + verified unit-test count; the original "20" would have made it 40. + Fixed the two numbers directly in place above (small, unambiguous, per + the QA fixing latitude in CLAUDE.md) rather than filing it as a + finding only. + +**Verdict:** all four scope claims (discovery rule, TOML subset parser, +precedence, test counts) hold up under adversarial testing through the +real binary and the unit suite. Nothing here rises to the level CLAUDE.md +cares most about — no masked corruption, no silent wrong write. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed, with two small lead +fixes.** + +Textbook feature: the strict-subset TOML parser is the right reading of +the no-dependencies rule (and the "unknown key is a hard error" behavior +is worth more than the whole rest of the feature — a silently ignored +`line_length` typo is exactly how formatters lose users' trust), the +`.git`-stops-after-check ordering is correct and well documented, and +`gather()` resolving every config before any write is the exit-code +contract taken seriously. QA's walk-order attack on pre-write fatality +was the right test and it held. + +Lead fixes while accepting (QA findings 1 and 3): + +1. **BOM stripped** at the top of `parse()` — a BOM'd config now parses + instead of producing an `unknown key` with an invisible cause. +2. **`+4` rejected** — `from_str` accepts a leading `+` that the + documented `digit+` grammar does not; the parser now enforces the + grammar it documents. (Leading zeros like `04` remain accepted: + they *are* `digit+`.) + +Dispositions: + +- **EACCES swallowed as "not found"** (finding 2): pre-existing in + `walk.rs` too, fails safe (exit 2, nothing written), and fixing it + properly means switching the discovery checks from `is_file()` to + `metadata()` error inspection across both modules — queued as a + follow-up note here rather than patched piecemeal. +- QA's in-place arithmetic fix to the work log (finding 4) was within + its small-fix latitude and is appreciated.