1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5use sha2::{Digest, Sha256};
6use thiserror::Error;
7
8use crate::finding::Finding;
9use crate::rule::Rule;
10
11const RULES_HASH_FILE: &str = "rules.hash";
12const CACHE_GITIGNORE: &str = "*\n";
13
14#[derive(Debug, Error)]
15pub enum CacheError {
16 #[error("cache I/O error: {0}")]
17 Io(#[from] io::Error),
18}
19
20pub fn rules_hash(rules: &[Rule]) -> String {
23 let mut ids: Vec<&str> = rules.iter().map(|r| r.id.as_str()).collect();
24 ids.sort();
25
26 let mut hasher = Sha256::new();
27 for id in &ids {
28 hasher.update(id.as_bytes());
29 hasher.update(b"\0");
30 }
31 format!("{:x}", hasher.finalize())
32}
33
34pub fn file_content_hash(content: &[u8]) -> String {
36 let mut hasher = Sha256::new();
37 hasher.update(content);
38 format!("{:x}", hasher.finalize())
39}
40
41pub struct CacheStore {
43 dir: PathBuf,
44}
45
46impl CacheStore {
47 pub fn new(project_root: &Path) -> Self {
48 Self {
49 dir: project_root.join(".slopguard-cache"),
50 }
51 }
52
53 pub fn dir(&self) -> &Path {
54 &self.dir
55 }
56
57 fn ensure_dir(&self) -> Result<(), CacheError> {
58 if !self.dir.exists() {
59 fs::create_dir_all(&self.dir)?;
60 fs::write(self.dir.join(".gitignore"), CACHE_GITIGNORE)?;
61 }
62 Ok(())
63 }
64
65 fn stored_rules_hash(&self) -> Option<String> {
66 fs::read_to_string(self.dir.join(RULES_HASH_FILE)).ok()
67 }
68
69 fn write_rules_hash(&self, hash: &str) -> Result<(), CacheError> {
70 self.ensure_dir()?;
71 fs::write(self.dir.join(RULES_HASH_FILE), hash)?;
72 Ok(())
73 }
74
75 pub fn check_rules_changed(&self, current_hash: &str) -> Result<bool, CacheError> {
78 match self.stored_rules_hash() {
79 Some(stored) if stored == current_hash => Ok(false),
80 _ => {
81 self.invalidate_all()?;
82 self.write_rules_hash(current_hash)?;
83 Ok(true)
84 }
85 }
86 }
87
88 fn invalidate_all(&self) -> Result<(), CacheError> {
89 if self.dir.exists() {
90 for entry in fs::read_dir(&self.dir)? {
91 let entry = entry?;
92 let name = entry.file_name();
93 let name_str = name.to_string_lossy();
94 if name_str != ".gitignore" && name_str != RULES_HASH_FILE {
95 fs::remove_file(entry.path())?;
96 }
97 }
98 }
99 Ok(())
100 }
101
102 fn entry_path(&self, file_hash: &str) -> PathBuf {
103 self.dir.join(format!("{file_hash}.bin"))
104 }
105
106 pub fn get(&self, file_hash: &str) -> Option<Vec<Finding>> {
108 let path = self.entry_path(file_hash);
109 let data = fs::read(&path).ok()?;
110 rmp_serde::from_slice(&data).ok()
111 }
112
113 pub fn put(&self, file_hash: &str, findings: &[Finding]) -> Result<(), CacheError> {
115 self.ensure_dir()?;
116 let data = rmp_serde::to_vec_named(findings).map_err(io::Error::other)?;
117 fs::write(self.entry_path(file_hash), data)?;
118 Ok(())
119 }
120
121 pub fn cleanup(&self, current_hashes: &[String]) -> Result<usize, CacheError> {
124 if !self.dir.exists() {
125 return Ok(0);
126 }
127 let mut removed = 0;
128 for entry in fs::read_dir(&self.dir)? {
129 let entry = entry?;
130 let name = entry.file_name();
131 let name_str = name.to_string_lossy();
132 if name_str == ".gitignore" || name_str == RULES_HASH_FILE {
133 continue;
134 }
135 let hash = name_str.trim_end_matches(".bin");
136 if !current_hashes.iter().any(|h| h == hash) {
137 fs::remove_file(entry.path())?;
138 removed += 1;
139 }
140 }
141 Ok(removed)
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use std::path::PathBuf;
148 use std::slice;
149
150 use tempfile::tempdir;
151
152 use super::*;
153 use crate::rule::{parse_rule, RuleId, Severity};
154
155 fn test_rule() -> Rule {
156 parse_rule(
157 r#"
158id: test-unwrap
159language: rust
160severity: error
161category: correctness
162message: ".unwrap() forbidden"
163rule:
164 kind: call_expression
165 regex: '\.unwrap\(\)\s*$'
166"#,
167 )
168 .unwrap()
169 }
170
171 fn sample_finding() -> Finding {
172 Finding {
173 rule_id: RuleId::from("test-unwrap"),
174 severity: Severity::Error,
175 category: crate::rule::Category::Correctness,
176 message: ".unwrap() forbidden".to_string(),
177 note: None,
178 fix: None,
179 file: PathBuf::from("src/main.rs"),
180 line: 2,
181 column: 5,
182 end_line: 2,
183 end_column: 20,
184 matched_text: "foo().unwrap()".to_string(),
185 }
186 }
187
188 #[test]
189 fn cache_miss() {
190 let dir = tempdir().unwrap();
191 let store = CacheStore::new(dir.path());
192 let hash = file_content_hash(b"fn main() { foo().unwrap(); }");
193
194 assert!(store.get(&hash).is_none());
195 }
196
197 #[test]
198 fn cache_hit() {
199 let dir = tempdir().unwrap();
200 let store = CacheStore::new(dir.path());
201 let content = b"fn main() { foo().unwrap(); }";
202 let hash = file_content_hash(content);
203 let findings = vec![sample_finding()];
204
205 store.put(&hash, &findings).unwrap();
206 let cached = store.get(&hash).unwrap();
207
208 assert_eq!(cached.len(), 1);
209 assert_eq!(cached[0].rule_id, RuleId::from("test-unwrap"));
210 assert_eq!(cached[0].line, 2);
211 assert_eq!(cached[0].matched_text, "foo().unwrap()");
212 }
213
214 #[test]
215 fn invalidation_file_change() {
216 let dir = tempdir().unwrap();
217 let store = CacheStore::new(dir.path());
218
219 let content_v1 = b"fn main() { foo().unwrap(); }";
220 let content_v2 = b"fn main() { foo()?; }";
221 let hash_v1 = file_content_hash(content_v1);
222 let hash_v2 = file_content_hash(content_v2);
223
224 store.put(&hash_v1, &[sample_finding()]).unwrap();
225
226 assert!(store.get(&hash_v1).is_some());
227 assert!(store.get(&hash_v2).is_none());
228 }
229
230 #[test]
231 fn invalidation_rule_change() {
232 let dir = tempdir().unwrap();
233 let store = CacheStore::new(dir.path());
234
235 let rules_v1 = [test_rule()];
236 let hash_v1 = rules_hash(&rules_v1);
237
238 let content_hash = file_content_hash(b"fn main() {}");
239 store.put(&content_hash, &[]).unwrap();
240 store.write_rules_hash(&hash_v1).unwrap();
241
242 assert!(store.get(&content_hash).is_some());
243
244 let mut rule_v2 = test_rule();
245 rule_v2.id = RuleId::from("different-rule");
246 let rules_v2 = [rule_v2];
247 let hash_v2 = rules_hash(&rules_v2);
248 assert_ne!(hash_v1, hash_v2);
249
250 store.check_rules_changed(&hash_v2).unwrap();
251
252 assert!(
253 store.get(&content_hash).is_none(),
254 "cache entries should be invalidated when rules change"
255 );
256 }
257
258 #[test]
259 fn cleanup_orphan_entries() {
260 let dir = tempdir().unwrap();
261 let store = CacheStore::new(dir.path());
262
263 let hash_a = file_content_hash(b"file a");
264 let hash_b = file_content_hash(b"file b");
265 store.put(&hash_a, &[]).unwrap();
266 store.put(&hash_b, &[sample_finding()]).unwrap();
267
268 let removed = store.cleanup(slice::from_ref(&hash_a)).unwrap();
269
270 assert_eq!(removed, 1);
271 assert!(store.get(&hash_a).is_some());
272 assert!(store.get(&hash_b).is_none());
273 }
274
275 #[test]
276 fn corrupted_cache_entry() {
277 let dir = tempdir().unwrap();
278 let store = CacheStore::new(dir.path());
279
280 store.ensure_dir().unwrap();
281 let hash = file_content_hash(b"some content");
282 fs::write(store.entry_path(&hash), b"not valid bincode data!!!").unwrap();
283
284 assert!(
285 store.get(&hash).is_none(),
286 "corrupted entry should return None, not panic"
287 );
288 }
289}