use std::path::{Path, PathBuf};
const NEEDLES: &[&str] = &["fs::write(", "File::create("];
const ALLOWED_RAW_WRITES: &[(&str, &str, usize, &str)] = &[(
"watch.rs",
"fs::write(",
1,
"test-only readiness marker: written to <path>.tmp then renamed — already atomic",
)];
#[test]
fn write_sites_are_funnelled() {
let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let files = rust_files(&src_dir);
assert!(
files.len() >= 5,
"non-vacuity: expected to walk at least 5 source files under {}, found {}",
src_dir.display(),
files.len()
);
let mut violations: Vec<String> = Vec::new();
let mut allowed_seen = vec![0usize; ALLOWED_RAW_WRITES.len()];
let mut durability_pin_checked = false;
for file in &files {
let name = file
.file_name()
.and_then(|n| n.to_str())
.expect("source file names are UTF-8");
let raw = std::fs::read_to_string(file).expect("source must be readable");
let code = strip_cfg_test_mods(&mask_comments_and_strings(&raw));
if name == "output.rs" {
assert!(
code.contains(".sync_all()"),
"output.rs must still call .sync_all() before the rename — the funnel \
guard is pointless if the choke point stops being durable"
);
assert!(
code.contains(".persist("),
"output.rs must still finish the write with a .persist() rename"
);
durability_pin_checked = true;
}
for needle in NEEDLES {
let hits = needle_lines(&code, needle);
if hits.is_empty() {
continue;
}
let allowed = match ALLOWED_RAW_WRITES
.iter()
.position(|(f, n, _, _)| *f == name && n == needle)
{
Some(idx) => {
allowed_seen[idx] += hits.len();
ALLOWED_RAW_WRITES[idx].2
}
None => 0,
};
for line in hits.iter().skip(allowed) {
violations.push(format!(
" {name}:{line}: raw `{needle}` ({allowed} allow-listed for this file)"
));
}
}
}
assert!(
durability_pin_checked,
"non-vacuity: output.rs was never scanned — the walk did not reach the choke point"
);
let dead: Vec<String> = ALLOWED_RAW_WRITES
.iter()
.zip(&allowed_seen)
.filter(|((_, _, max, _), seen)| *seen != max)
.map(|((f, n, max, _), seen)| format!(" {f}: `{n}` expected {max} hit(s), found {seen}"))
.collect();
assert!(
dead.is_empty(),
"allow-list entry is dead or drifted ({} entr(ies)). Update ALLOWED_RAW_WRITES \
to match reality — a stale entry is a licence for a raw write nobody reviewed.\n{}",
dead.len(),
dead.join("\n")
);
assert!(
violations.is_empty(),
"raw write sites outside the atomic funnel ({} found).\n{}\n\n\
Route the write through `crate::output::atomic_write_file` (and create the parent \
directory first — the primitive deliberately does not). If a site genuinely must \
stay raw, add it to ALLOWED_RAW_WRITES with a written justification.",
violations.len(),
violations.join("\n")
);
}
#[test]
fn the_guard_flags_a_planted_raw_write() {
assert_eq!(
scan_violation_count("fn f(p: &Path, s: &str) { std::fs::write(&p, s).unwrap(); }"),
1,
"a planted std::fs::write in a plain fn must be flagged"
);
assert_eq!(
scan_violation_count(
"fn f() {}\n#[cfg(test)]\nmod tests {\n fn t(p: &Path) { std::fs::write(&p, \"x\").unwrap(); }\n}\n"
),
0,
"a write inside #[cfg(test)] mod tests must not be flagged"
);
assert_eq!(
scan_violation_count("fn f() {\n // std::fs::write(&p, s);\n}\n"),
0,
"a needle inside a // comment must not be flagged"
);
assert_eq!(
scan_violation_count("fn f() -> &'static str { \"std::fs::write(&p, s)\" }"),
0,
"a needle inside a string literal must not be flagged"
);
assert_eq!(
scan_violation_count("fn f(p: &Path) { let _ = std::fs::File::create(p); }"),
1,
"a planted File::create in a plain fn must be flagged"
);
}
#[test]
fn every_allowlist_entry_is_live() {
let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
for (file, needle, max, why) in ALLOWED_RAW_WRITES {
let path = src_dir.join(file);
assert!(
path.is_file(),
"allow-list names {file}, which does not exist under {} (justification: {why})",
src_dir.display()
);
let raw = std::fs::read_to_string(&path).expect("source must be readable");
let code = strip_cfg_test_mods(&mask_comments_and_strings(&raw));
let hits = count_occurrences(&code, needle);
assert_eq!(
hits, *max,
"allow-list expects {max} raw `{needle}` in {file}, found {hits} \
(justification: {why})"
);
}
}
fn scan_violation_count(src: &str) -> usize {
let code = strip_cfg_test_mods(&mask_comments_and_strings(src));
NEEDLES.iter().map(|n| count_occurrences(&code, n)).sum()
}
fn needle_lines(code: &str, needle: &str) -> Vec<usize> {
let mut lines = Vec::new();
let mut start = 0usize;
while let Some(pos) = code[start..].find(needle) {
let abs = start + pos;
lines.push(code[..abs].matches('\n').count() + 1);
start = abs + needle.len();
}
lines
}
fn count_occurrences(haystack: &str, needle: &str) -> usize {
let mut count = 0;
let mut start = 0;
while let Some(pos) = haystack[start..].find(needle) {
count += 1;
start += pos + needle.len();
}
count
}
fn rust_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for entry in rd.flatten() {
let p = entry.path();
let Ok(ft) = entry.file_type() else { continue };
if ft.is_dir() {
stack.push(p);
} else if ft.is_file() && p.extension().and_then(|e| e.to_str()) == Some("rs") {
out.push(p);
}
}
}
out.sort();
out
}
fn mask_comments_and_strings(src: &str) -> String {
let b = src.as_bytes();
let mut out = vec![b' '; b.len()];
for (i, &c) in b.iter().enumerate() {
if c == b'\n' {
out[i] = b'\n';
}
}
let mut i = 0usize;
while i < b.len() {
if b[i] == b'/' && b.get(i + 1) == Some(&b'/') {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
continue;
}
if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
i += 2;
while i < b.len() && !(b[i] == b'*' && b.get(i + 1) == Some(&b'/')) {
i += 1;
}
i = (i + 2).min(b.len());
continue;
}
if b[i] == b'r'
&& matches!(b.get(i + 1), Some(&b'"') | Some(&b'#'))
&& !prev_is_ident_byte(b, i)
{
let mut hashes = 0usize;
let mut j = i + 1;
while b.get(j) == Some(&b'#') {
hashes += 1;
j += 1;
}
if b.get(j) == Some(&b'"') {
j += 1;
while j < b.len() {
if b[j] == b'"' && (0..hashes).all(|k| b.get(j + 1 + k) == Some(&b'#')) {
j += 1 + hashes;
break;
}
j += 1;
}
i = j.min(b.len());
continue;
}
}
if b[i] == b'"' {
let mut j = i + 1;
while j < b.len() {
if b[j] == b'\\' {
j += 2;
continue;
}
if b[j] == b'"' {
j += 1;
break;
}
j += 1;
}
i = j.min(b.len());
continue;
}
if b[i] == b'\'' {
let mut j = i + 1;
let mut closed = false;
let mut steps = 0;
while j < b.len() && steps < 8 {
if b[j] == b'\\' {
j += 2;
steps += 1;
continue;
}
if b[j] == b'\'' {
closed = true;
j += 1;
break;
}
j += 1;
steps += 1;
}
if closed {
i = j.min(b.len());
continue;
}
}
out[i] = b[i];
i += 1;
}
String::from_utf8(out).expect("masking preserves UTF-8 boundaries on ASCII delimiters")
}
fn strip_cfg_test_mods(code: &str) -> String {
let mut result = code.to_string();
while let Some(attr) = result.find("#[cfg(test)]") {
let after = attr + "#[cfg(test)]".len();
let Some(mod_rel) = result[after..].find("mod ") else {
result.replace_range(attr..after, &" ".repeat(after - attr));
continue;
};
let mod_start = after + mod_rel;
let brace = result[mod_start..].find('{');
let semi = result[mod_start..].find(';');
match (brace, semi) {
(Some(bo), semi_opt) if semi_opt.is_none_or(|s| bo < s) => {
let open = mod_start + bo;
if let Some(close) = match_brace(&result, open) {
result.replace_range(attr..=close, "");
} else {
result.replace_range(attr..open, "");
}
}
(_, Some(so)) => {
let end = mod_start + so + 1;
result.replace_range(attr..end, "");
}
_ => {
result.replace_range(attr..after, &" ".repeat(after - attr));
}
}
}
result
}
fn prev_is_ident_byte(b: &[u8], i: usize) -> bool {
i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')
}
fn match_brace(text: &str, open: usize) -> Option<usize> {
let b = text.as_bytes();
let mut depth = 0i32;
let mut i = open;
while i < b.len() {
match b[i] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
i += 1;
}
None
}