Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
test(guards): one walk behind the guards that scan source as text (#3914)
Maximilian Roose4238e83697d
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex cef11a54f..1e6c87d25 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -561,6 +561,40 @@ the pragmatic user experience when the complete rendering is the contract. Acustom verifier must fail for every violation it claims to check—diagnostic`println!` output is not an oracle.+### Guards that scan source text++Several guards read `src/`, or the snapshot corpus, as text rather than+compiling it: no stray `println!` outside the allowlist, no `eprintln!` that+resolves to std's macro instead of anstream's, no bare `env!("VERGEN_…")`, no+`include_str!` of a path the package won't ship, no host path in a `.snap`, and+nothing but `src/testing/mod.rs` spawning `wt` through `CARGO_BIN_EXE_wt`.+Each one asserts *absence* over what its walk handed it.++That polarity is what makes the failure mode silent. A file that drops out of+the walk is indistinguishable from a file with nothing wrong in it: the+violation it carried is never looked for, `violations` stays empty, and the+test passes green over less than it claims.++So that walk lives once, in `tests/common/source_scan.rs`, and panics on every+read rather than skipping; its module docstring carries the rest. Other tests+recurse through directories for their own reasons, and this is about the ones+whose assertion is absence. A read that returns early is the shape to look+for. `Err(_) => return` and `let Ok(..) else { return }` are the obvious two,+and `entries.flatten()` is the one that hides, because it drops a per-entry+`io::Error` without looking like a `return` at all.++Each guard also proves its walk reached something, since a walk that reads+cleanly and yields nothing passes just as green. `visit_files` returns the+number of files it visited and is `#[must_use]`, so forgetting to answer for+coverage is a compile error rather than a rule someone has to remember — which+is what the swallowed reads it replaced had going for them. A guard that+already asserts something an empty walk cannot satisfy discards the count with+`let _ =`, and that discard is the claim: its proof is the assertion below it,+and a count beside it would be a second mechanism for one guarantee.++A guard walking several roots counts per root. A layout change moves one root+and leaves the others, and an aggregate count survives that.+### Snapshot env drift: cosmetic vs. a leak`insta_cmd` snapshots record the test's environment variables in an `env:`diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 938a12188..b23ff9907 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -8,6 +8,7 @@ pub use worktrunk::testing::mock_commands;pub use worktrunk::testing::*;pub mod list_snapshots;+pub mod source_scan;// Progressive output tests use PTY and are Unix-only for now#[cfg(unix)]pub mod progressive_output;@@ -1442,16 +1443,14 @@ mod tests {}fn scan_for_needle(dir: &Path, needle: &str, root: &Path, offenders: &mut Vec<PathBuf>) {- for entry in std::fs::read_dir(dir).unwrap().flatten() {- let path = entry.path();- if path.is_dir() {- scan_for_needle(&path, needle, root, offenders);- } else if path.extension().and_then(|s| s.to_str()) == Some("rs")- && std::fs::read_to_string(&path).unwrap().contains(needle)- {- offenders.push(path.strip_prefix(root).unwrap().to_path_buf());- }- }+ // The count is discarded: asserting the offender list *equals* one named+ // file already fails over an empty walk.+ let _ =+ super::source_scan::visit_files(dir, "rs", "spawn-pin scan", &mut |path, contents| {+ if contents.contains(needle) {+ offenders.push(path.strip_prefix(root).unwrap().to_path_buf());+ }+ });}/// Every PTY spawn routes through [`configure_pty_command`] (directly ordiff --git a/tests/common/source_scan.rs b/tests/common/source_scan.rsnew file mode 100644index 000000000..3efc74829--- /dev/null+++ b/tests/common/source_scan.rs@@ -0,0 +1,66 @@+//! One recursive walk for the guards that read source as text.+//!+//! Those guards assert *absence*, which is what makes a swallowed read+//! dangerous here in a way it isn't for code that acts on what it finds — see+//! "Guards that scan source text" in `tests/CLAUDE.md` for the shape of that+//! failure and the rules it sets.+//!+//! Every read below panics rather than skipping, so the walk either covers the+//! tree or says which read stopped it.++use std::fs;+use std::path::Path;++/// Visit every `.{extension}` file under `dir`, recursively, passing each+/// file's path and contents to `f`.+///+/// `scan` names the calling guard in panic messages (`"stdout scan"`,+/// `"snapshot scan"`), so a failure says which guard was running — several+/// guards walk the same tree, so the path alone doesn't. The three reads that+/// can fail are worded apart: listing a directory, reading one entry of a+/// listed directory, and reading a file's contents. The entry case is the one+/// that most needs saying, because the directory it names checks out healthy+/// and the obvious next step leads nowhere.+///+/// Returns the number of files visited. It is `#[must_use]` because an+/// absence-asserting guard also passes over an empty walk, so every caller has+/// to answer for coverage — either by asserting this count, or by discarding it+/// with `let _ =` where it already asserts something an empty walk cannot+/// satisfy. Leaving that to prose is how the swallowed reads this walk replaced+/// survived in four copies.+#[must_use]+pub fn visit_files(+ dir: &Path,+ extension: &str,+ scan: &str,+ f: &mut impl FnMut(&Path, &str),+) -> usize {+ let mut visited = 0usize;+ let entries = fs::read_dir(dir)+ .unwrap_or_else(|e| panic!("{} unreadable during the {scan}: {e}", dir.display()));++ for entry in entries {+ // `flatten()` here would drop a per-entry error — a file removed+ // mid-walk, a failing `stat` — and skip a file without saying so.+ let entry = entry.unwrap_or_else(|e| {+ panic!(+ "an entry in {} unreadable during the {scan}: {e}",+ dir.display()+ )+ });+ let path = entry.path();+ if path.is_dir() {+ visited += visit_files(&path, extension, scan, f);+ } else if path.extension().and_then(|s| s.to_str()) == Some(extension) {+ let contents = fs::read_to_string(&path).unwrap_or_else(|e| {+ panic!(+ "the contents of {} are unreadable during the {scan}: {e}",+ path.display()+ )+ });+ f(&path, &contents);+ visited += 1;+ }+ }+ visited+}diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 3e99364bf..75aed854c 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -3828,9 +3828,11 @@ fn test_plugin_layout_is_consolidated() {Codex's installer drops symlinks");let mut dirs = vec![plugin_skills];+ let mut mirrored = 0usize;while let Some(dir) = dirs.pop() {for entry in fs::read_dir(&dir).unwrap() {let entry = entry.unwrap();+ mirrored += 1;assert!(!entry.path().is_symlink(),"{} is a symlink — the plugin skills mirror must hold only regular files \@@ -3842,11 +3844,21 @@ fn test_plugin_layout_is_consolidated() {}}}+ // The assertion above is absence, so an empty mirror satisfies it over+ // nothing — see "Guards that scan source text" in `tests/CLAUDE.md`.+ assert!(+ mirrored > 0,+ "plugins/worktrunk/skills is empty — the mirror never generated, so the \+ symlink invariant above just passed over nothing"+ );+// Every repo-root skill dir carries a SKILL.md, since the convention scan// silently ignores a directory without one.+ let mut skill_dirs = 0usize;for entry in fs::read_dir(root.join("skills")).unwrap() {let entry = entry.unwrap();if entry.file_type().unwrap().is_dir() {+ skill_dirs += 1;assert!(entry.path().join("SKILL.md").exists(),"skills/{} has no SKILL.md — Claude's convention scan silently ignores it",@@ -3854,6 +3866,7 @@ fn test_plugin_layout_is_consolidated() {);}}+ assert!(skill_dirs > 0, "skills/ holds no skill directories");// The WorktreeRemove hook must not force-delete unmerged branches (#2939).// Claude Code auto-fires WorktreeRemove on session exit for any worktreediff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex bf9888e1c..11245f892 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -33,13 +33,13 @@//! what that buys — narration redirected to a file carries no escapes.use std::collections::HashSet;-use std::fs;use std::path::Path;use std::process::Stdio;use path_slash::PathExt as _;use rstest::rstest;+use crate::common::source_scan::visit_files;use crate::common::{TestRepo, repo};/// Paths (relative to src/) that are allowed to use println!/print! for stdout.@@ -125,7 +125,15 @@ fn check_no_unexpected_stdout_writes() {let mut violations = Vec::new();// Recursively scan all .rs files under src/- scan_directory(&src_dir, &stdout_tokens, &mut violations, &src_dir);+ let scanned = visit_files(&src_dir, "rs", "stdout scan", &mut |path, contents| {+ check_file(path, contents, &stdout_tokens, &mut violations, &src_dir)+ });+ assert!(+ scanned > 0,+ "scanned no files under {} — this test asserts absence, so it would have \+ passed over nothing",+ src_dir.display()+ );if !violations.is_empty() {panic!(@@ -139,25 +147,13 @@ fn check_no_unexpected_stdout_writes() {}}-fn scan_directory(dir: &Path, tokens: &[&str], violations: &mut Vec<String>, scan_root: &Path) {- // A directory the walk can't read contributes no violations, so swallowing- // the error lets the guard pass over a tree it never inspected — a missing- // or relocated `src/` reads as a clean crate. Surface it instead.- let entries = fs::read_dir(dir)- .unwrap_or_else(|e| panic!("{} unreadable during the src/ scan: {e}", dir.display()));-- for entry in entries.flatten() {- let path = entry.path();-- if path.is_dir() {- scan_directory(&path, tokens, violations, scan_root);- } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {- check_file(&path, tokens, violations, scan_root);- }- }-}--fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, scan_root: &Path) {+fn check_file(+ path: &Path,+ contents: &str,+ tokens: &[&str],+ violations: &mut Vec<String>,+ scan_root: &Path,+) {// Get path relative to src/ for matching against STDOUT_ALLOWED_PATHSlet relative_path = path.strip_prefix(scan_root)@@ -169,11 +165,6 @@ fn check_file(path: &Path, tokens: &[&str], violations: &mut Vec<String>, scan_rreturn;}- let contents = match fs::read_to_string(path) {- Ok(c) => c,- Err(_) => return,- };-let relative_path = path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap_or(path)@@ -297,7 +288,20 @@ fn allowlisted_paths_still_exist() {fn check_stderr_macros_come_from_styling() {let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");let mut violations = Vec::new();- scan_stderr_macros(&src_dir, &src_dir, &mut violations);+ let scanned = visit_files(+ &src_dir,+ "rs",+ "stderr-macro scan",+ &mut |path, contents| {+ check_stderr_macros_in_file(path, contents, &src_dir, &mut violations)+ },+ );+ assert!(+ scanned > 0,+ "scanned no files under {} — this test asserts absence, so it would have \+ passed over nothing",+ src_dir.display()+ );violations.sort();assert!(@@ -313,21 +317,12 @@ fn check_stderr_macros_come_from_styling() {);}-fn scan_stderr_macros(dir: &Path, src_dir: &Path, violations: &mut Vec<String>) {- let entries = fs::read_dir(dir)- .unwrap_or_else(|e| panic!("{} unreadable during the src/ scan: {e}", dir.display()));-- for entry in entries.flatten() {- let path = entry.path();- if path.is_dir() {- scan_stderr_macros(&path, src_dir, violations);- } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {- check_stderr_macros_in_file(&path, src_dir, violations);- }- }-}--fn check_stderr_macros_in_file(path: &Path, src_dir: &Path, violations: &mut Vec<String>) {+fn check_stderr_macros_in_file(+ path: &Path,+ contents: &str,+ src_dir: &Path,+ violations: &mut Vec<String>,+) {let relative_path = path.strip_prefix(src_dir).map(|p| p.to_slash_lossy())@@ -336,11 +331,7 @@ fn check_stderr_macros_in_file(path: &Path, src_dir: &Path, violations: &mut Vecreturn;}- let contents = match fs::read_to_string(path) {- Ok(c) => c,- Err(_) => return,- };- let imported = styling_imports(&contents);+ let imported = styling_imports(contents);for (line_num, line) in contents.lines().enumerate() {// A doc comment quoting `eprintln!` is prose, not a write.diff --git a/tests/integration_tests/packaged_assets.rs b/tests/integration_tests/packaged_assets.rsindex ab9c616f0..bb6701b89 100644--- a/tests/integration_tests/packaged_assets.rs+++ b/tests/integration_tests/packaged_assets.rs@@ -37,6 +37,7 @@ use std::fs;use std::path::{Component, Path, PathBuf};use std::process::Command;+use crate::common::source_scan::visit_files;use path_slash::PathExt as _;/// askama resolves `#[template(path = "…")]` relative to `templates/` at the@@ -51,9 +52,16 @@ fn embedded_assets_ship_in_package() {// 1. Discover every compile-time-embedded path under `src/`, as a// repo-root-relative forward-slash string.let mut assets = BTreeSet::new();- scan_directory(&src_dir, manifest_dir, &mut assets);- // `scan_directory` and `scan_file` panic when the tree or one of its files- // can't be read. This catches the remaining way discovery comes back empty:+ // The count is discarded: `assets` being non-empty below already fails over+ // an empty walk, so asserting the count too would be a second mechanism.+ let _ = visit_files(+ &src_dir,+ "rs",+ "embedded-asset scan",+ &mut |path, contents| scan_file(path, contents, manifest_dir, &mut assets),+ );+ // `visit_files` panics when the tree or one of its files can't be read.+ // This catches the remaining way discovery comes back empty:// every file read, and the `include_str!` / `include_bytes!` / `#[template]`// matching recognizing none of them. The comparison below iterates `assets`,// so an empty set checks nothing and passes.@@ -97,39 +105,7 @@ fn embedded_assets_ship_in_package() {);}-fn scan_directory(dir: &Path, manifest_dir: &Path, assets: &mut BTreeSet<String>) {- // A directory the walk can't read yields no assets, so swallowing the- // error lets an unreadable or relocated `src/` read as a crate that embeds- // nothing — every violation below goes unchecked. Surface it instead.- let entries = fs::read_dir(dir)- .unwrap_or_else(|e| panic!("{} unreadable during the src/ scan: {e}", dir.display()));-- for entry in entries {- // `flatten()` here would drop a per-entry error, so a file that never- // reaches `scan_file` takes whatever it embeds with it while the rest- // keep `assets` non-empty — past both the panic and the assert.- let entry = entry.unwrap_or_else(|e| {- panic!(- "an entry in {} unreadable during the src/ scan: {e}",- dir.display()- )- });- let path = entry.path();- if path.is_dir() {- scan_directory(&path, manifest_dir, assets);- } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {- scan_file(&path, manifest_dir, assets);- }- }-}--fn scan_file(path: &Path, manifest_dir: &Path, assets: &mut BTreeSet<String>) {- // Returning here would drop whatever this file embeds while the rest keep- // `assets` non-empty, so the empty-scan assert above wouldn't catch it- // either. A `.rs` file under `src/` that isn't readable UTF-8 is broken in a- // way the crate wouldn't compile through.- let contents = fs::read_to_string(path)- .unwrap_or_else(|e| panic!("{} unreadable during the src/ scan: {e}", path.display()));+fn scan_file(path: &Path, contents: &str, manifest_dir: &Path, assets: &mut BTreeSet<String>) {let source_dir = path.parent().unwrap_or(manifest_dir);for line in contents.lines() {diff --git a/tests/integration_tests/snapshot_formatting_guard.rs b/tests/integration_tests/snapshot_formatting_guard.rsindex 9a9b9d992..68a0db447 100644--- a/tests/integration_tests/snapshot_formatting_guard.rs+++ b/tests/integration_tests/snapshot_formatting_guard.rs@@ -29,9 +29,9 @@//! `.args[]` redaction in `add_repo_and_worktree_path_filters` (both in//! `tests/common/mod.rs`); see tests/CLAUDE.md "Snapshot env drift".+use crate::common::source_scan::visit_files;use ansi_str::AnsiStr;use regex::Regex;-use std::fs;use std::path::Path;use std::sync::LazyLock;@@ -178,20 +178,12 @@ fn test_no_host_specific_paths_in_snapshots() {/// Visit every committed `.snap` file. Snapshot dirs live under `src`/// (unit tests), `tests` (integration tests), and `docs` (demo fixtures).fn for_each_snapshot(project_root: &Path, mut f: impl FnMut(&Path, &str)) {- // Every caller asserts *absence* over the corpus, so snapshots that stop- // being walked pass vacuously. The panic in `visit_snap_files` covers a root- // that can't be read; this covers one that reads fine and has stopped- // holding snapshots. Per root rather than in aggregate, because a layout- // change moves one root and leaves the others: `tests` alone holds the large- // majority of the corpus, so an aggregate non-empty check would survive- // losing it. That makes each root load-bearing — a root that legitimately- // stops holding snapshots belongs out of this list, not exempted from it.+ // Per root rather than in aggregate: `tests` alone holds the large majority+ // of the corpus, so a total count survives that root moving away. Each root+ // is load-bearing as a result — one that legitimately stops holding+ // snapshots belongs out of this list, not exempted from it.for root in ["src", "tests", "docs"] {- let mut seen = 0usize;- visit_snap_files(&project_root.join(root), &mut |path, content| {- seen += 1;- f(path, content);- });+ let seen = visit_files(&project_root.join(root), "snap", "snapshot scan", &mut f);assert!(seen > 0,"{root}/ holds no .snap files — the corpus has moved, so these \@@ -200,38 +192,6 @@ fn for_each_snapshot(project_root: &Path, mut f: impl FnMut(&Path, &str)) {}}-fn visit_snap_files(dir: &Path, f: &mut impl FnMut(&Path, &str)) {- // A root that can't be read yields no snapshots, and every caller asserts- // absence, so swallowing the error would let an unreadable directory read as- // a clean corpus. `for_each_snapshot` covers the separate case where the- // roots read fine and simply hold nothing.- let entries = fs::read_dir(dir)- .unwrap_or_else(|e| panic!("{} unreadable during the snapshot scan: {e}", dir.display()));-- for entry in entries {- // `flatten()` here would drop a per-entry error — a file removed- // mid-walk, a failing `stat` — and skip a snapshot without saying so.- let entry = entry.unwrap_or_else(|e| {- panic!(- "an entry in {} unreadable during the snapshot scan: {e}",- dir.display()- )- });- let path = entry.path();- if path.is_dir() {- visit_snap_files(&path, f);- } else if path.extension().and_then(|s| s.to_str()) == Some("snap") {- let content = fs::read_to_string(&path).unwrap_or_else(|e| {- panic!(- "{} unreadable during the snapshot scan: {e}",- path.display()- )- });- f(&path, &content);- }- }-}-/// Extract labeled output sections from a snapshot file.////// Handles two formats:diff --git a/tests/integration_tests/version_build.rs b/tests/integration_tests/version_build.rsindex aaa9119a0..ab8a7c40e 100644--- a/tests/integration_tests/version_build.rs+++ b/tests/integration_tests/version_build.rs@@ -19,10 +19,10 @@//! mechanism directly: forbid `env!` on any build-script-provided `VERGEN_*`//! variable, since none are guaranteed to exist on the crates.io archive.-use std::fs;use std::path::Path;use std::process::Command;+use crate::common::source_scan::visit_files;use path_slash::PathExt as _;#[test]@@ -30,7 +30,15 @@ fn vergen_env_vars_are_read_optionally() {let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");let mut violations = Vec::new();- scan_directory(&src_dir, &src_dir, &mut violations);+ let scanned = visit_files(&src_dir, "rs", "vergen scan", &mut |path, contents| {+ check_file(path, contents, &src_dir, &mut violations)+ });+ assert!(+ scanned > 0,+ "scanned no files under {} — this test asserts absence, so it would have \+ passed over nothing",+ src_dir.display()+ );assert!(violations.is_empty(),@@ -42,27 +50,7 @@ fn vergen_env_vars_are_read_optionally() {);}-fn scan_directory(dir: &Path, src_dir: &Path, violations: &mut Vec<String>) {- // Swallowing this error would let a missing or relocated `src/` read as a- // crate with no `env!("VERGEN_…")` in it — the vacuous pass that makes this- // guard, the one standing between a bare `env!` and another #3123, useless.- let entries = fs::read_dir(dir)- .unwrap_or_else(|e| panic!("{} unreadable during the src/ scan: {e}", dir.display()));-- for entry in entries.flatten() {- let path = entry.path();- if path.is_dir() {- scan_directory(&path, src_dir, violations);- } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {- check_file(&path, src_dir, violations);- }- }-}--fn check_file(path: &Path, src_dir: &Path, violations: &mut Vec<String>) {- let Ok(contents) = fs::read_to_string(path) else {- return;- };+fn check_file(path: &Path, contents: &str, src_dir: &Path, violations: &mut Vec<String>) {let relative = path.strip_prefix(src_dir).unwrap_or(path).to_slash_lossy();for (i, line) in contents.lines().enumerate() {