返回 CodeWhale
io_hygiene.rs
根目录 / crates / engine / tests / io_hygiene.rs
1 use std::collections::BTreeMap;
2 use std::fs;
3 use std::path::{Path, PathBuf};
4
5 const SCANNED_DIRS: &[&str] = &["src/tools", "src/session_manager"];
6
7 const ALLOWED_RAW_WRITES: &[(&str, usize)] = &[
8 ("src/tools/github/shape.rs", 1),
9 ("src/tools/image_ocr.rs", 1),
10 ("src/tools/review.rs", 1),
11 ("src/tools/tasks.rs", 1),
12 ("src/tools/workflow/verified_candidate/artifact.rs", 2),
13 ];
14
15 fn is_test_file(path: &Path) -> bool {
16 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
17 name == "tests.rs"
18 || name.ends_with("_tests.rs")
19 || name.starts_with("test_cases")
20 || path.components().any(|c| c.as_os_str() == "tests")
21 }
22
23 fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
24 let entries = fs::read_dir(dir).unwrap_or_else(|e| panic!("scan {}: {e}", dir.display()));
25 for entry in entries.flatten() {
26 let path = entry.path();
27 if path.is_dir() {
28 rust_files(&path, out);
29 } else if path.extension().is_some_and(|ext| ext == "rs") && !is_test_file(&path) {
30 out.push(path);
31 }
32 }
33 }
34
35 fn raw_writes_in(source: &str) -> usize {
36 let lines: Vec<&str> = source.lines().collect();
37 let mut count = 0;
38 for (index, line) in lines.iter().enumerate() {
39 let trimmed = line.trim();
40 if trimmed.starts_with("#[cfg(")
41 && trimmed.contains("test")
42 && lines[index + 1..]
43 .iter()
44 .map(|l| l.trim())
45 .find(|l| !l.starts_with("#["))
46 .is_some_and(|l| l.starts_with("mod ") || l.starts_with("pub mod "))
47 {
48 break;
49 }
50 if trimmed.starts_with("//") {
51 continue;
52 }
53 let mut rest = *line;
54 while let Some(at) = rest.find("fs::write(") {
55 let preceded_by_ident = rest[..at]
56 .chars()
57 .next_back()
58 .is_some_and(|c| c.is_alphanumeric() || c == '_');
59 if !preceded_by_ident {
60 count += 1;
61 }
62 rest = &rest[at + "fs::write(".len()..];
63 }
64 }
65 count
66 }
67
68 fn scan() -> BTreeMap<String, usize> {
69 let root = Path::new(env!("CARGO_MANIFEST_DIR"));
70 let mut files = Vec::new();
71 for dir in SCANNED_DIRS {
72 rust_files(&root.join(dir), &mut files);
73 }
74 for entry in fs::read_dir(root.join("src")).expect("read src").flatten() {
75 let path = entry.path();
76 let name = entry.file_name().to_string_lossy().into_owned();
77 if name.starts_with("session_") && name.ends_with(".rs") && !is_test_file(&path) {
78 files.push(path);
79 }
80 }
81 assert!(
82 files.iter().any(|p| p.ends_with("src/session_manager.rs")),
83 "session_manager.rs must be scanned"
84 );
85 let mut found = BTreeMap::new();
86 for path in files {
87 let source = fs::read_to_string(&path).expect("read source");
88 let count = raw_writes_in(&source);
89 if count > 0 {
90 let rel = path.strip_prefix(root).expect("under crate root");
91 found.insert(rel.to_string_lossy().replace('\\', "/"), count);
92 }
93 }
94 found
95 }
96
97 #[test]
98 fn no_new_raw_fs_write_in_tools_or_session_manager() {
99 let found = scan();
100 let allowed: BTreeMap<&str, usize> = ALLOWED_RAW_WRITES.iter().copied().collect();
101 let mut problems = Vec::new();
102 for (path, count) in &found {
103 let limit = allowed.get(path.as_str()).copied().unwrap_or(0);
104 if *count > limit {
105 problems.push(format!(
106 "{path}: {count} raw fs::write call(s), baseline {limit}; use write_atomic or WorkspaceFile"
107 ));
108 }
109 }
110 for (path, limit) in &allowed {
111 let count = found.get(*path).copied().unwrap_or(0);
112 if count < *limit {
113 problems.push(format!(
114 "{path}: {count} raw fs::write call(s) < baseline {limit}; lower ALLOWED_RAW_WRITES"
115 ));
116 }
117 }
118 assert!(problems.is_empty(), "{}", problems.join("\n"));
119 }
120
121 #[test]
122 fn detector_counts_production_writes_only() {
123 let source = "fn a() { std::fs::write(p, b)?; }\n// fs::write(x)\nfn b() { tokio::fs::write(p, b).await?; }\n#[cfg(test)]\nmod tests { fn t() { fs::write(p, b); } }\n";
124 assert_eq!(raw_writes_in(source), 2);
125 assert_eq!(
126 raw_writes_in("fn a() { write_atomic(p, b); my_fs::write(p); }"),
127 0
128 );
129 }
130
130 lines RUST