1use std::cmp::Reverse;
5use std::path::{Path, PathBuf};
6
7use anyhow::Result;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize, Deserialize, Default)]
13pub struct ScanSummarySnapshot {
14 pub files_analyzed: u64,
15 pub files_skipped: u64,
16 pub total_physical_lines: u64,
17 pub code_lines: u64,
18 pub comment_lines: u64,
19 pub blank_lines: u64,
20 #[serde(default)]
21 pub functions: u64,
22 #[serde(default)]
23 pub classes: u64,
24 #[serde(default)]
25 pub variables: u64,
26 #[serde(default)]
27 pub imports: u64,
28 #[serde(default)]
29 pub test_count: u64,
30 #[serde(default)]
31 pub coverage_lines_found: u64,
32 #[serde(default)]
33 pub coverage_lines_hit: u64,
34 #[serde(default)]
35 pub coverage_functions_found: u64,
36 #[serde(default)]
37 pub coverage_functions_hit: u64,
38 #[serde(default)]
39 pub coverage_branches_found: u64,
40 #[serde(default)]
41 pub coverage_branches_hit: u64,
42}
43
44impl From<&crate::SummaryTotals> for ScanSummarySnapshot {
45 fn from(t: &crate::SummaryTotals) -> Self {
49 Self {
50 files_analyzed: t.files_analyzed,
51 files_skipped: t.files_skipped,
52 total_physical_lines: t.total_physical_lines,
53 code_lines: t.code_lines,
54 comment_lines: t.comment_lines,
55 blank_lines: t.blank_lines,
56 functions: t.functions,
57 classes: t.classes,
58 variables: t.variables,
59 imports: t.imports,
60 test_count: t.test_count,
61 coverage_lines_found: t.coverage_lines_found,
62 coverage_lines_hit: t.coverage_lines_hit,
63 coverage_functions_found: t.coverage_functions_found,
64 coverage_functions_hit: t.coverage_functions_hit,
65 coverage_branches_found: t.coverage_branches_found,
66 coverage_branches_hit: t.coverage_branches_hit,
67 }
68 }
69}
70
71#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct RegistryEntry {
74 pub run_id: String,
75 pub timestamp_utc: DateTime<Utc>,
76 pub project_label: String,
77 pub input_roots: Vec<String>,
78 pub json_path: Option<PathBuf>,
79 pub html_path: Option<PathBuf>,
80 #[serde(default)]
81 pub pdf_path: Option<PathBuf>,
82 #[serde(default)]
83 pub csv_path: Option<PathBuf>,
84 #[serde(default)]
85 pub xlsx_path: Option<PathBuf>,
86 pub summary: ScanSummarySnapshot,
87 #[serde(default)]
89 pub git_branch: Option<String>,
90 #[serde(default)]
92 pub git_commit: Option<String>,
93 #[serde(default)]
95 pub git_commit_long: Option<String>,
96 #[serde(default)]
98 pub git_author: Option<String>,
99 #[serde(default)]
101 pub git_tags: Option<String>,
102 #[serde(default)]
104 pub git_nearest_tag: Option<String>,
105 #[serde(default)]
107 pub git_commit_date: Option<String>,
108}
109
110#[derive(Debug, Default, Serialize, Deserialize)]
113pub struct WatchedDirsStore {
114 pub dirs: Vec<PathBuf>,
115}
116
117impl WatchedDirsStore {
118 #[must_use]
119 pub fn load(path: &Path) -> Self {
120 std::fs::read_to_string(path)
121 .ok()
122 .and_then(|s| serde_json::from_str(&s).ok())
123 .unwrap_or_default()
124 }
125
126 pub fn save(&self, path: &Path) -> Result<()> {
130 if let Some(parent) = path.parent() {
131 std::fs::create_dir_all(parent)?;
132 }
133 std::fs::write(path, serde_json::to_string_pretty(self)?)?;
134 Ok(())
135 }
136
137 pub fn add(&mut self, dir: PathBuf) {
138 if !self.dirs.contains(&dir) {
139 self.dirs.push(dir);
140 }
141 }
142
143 pub fn remove(&mut self, dir: &Path) {
144 self.dirs.retain(|d| d != dir);
145 }
146}
147
148#[derive(Debug, Default, Serialize, Deserialize)]
151pub struct ScanRegistry {
152 pub entries: Vec<RegistryEntry>,
153}
154
155impl ScanRegistry {
156 #[must_use]
158 pub fn load(registry_path: &Path) -> Self {
159 std::fs::read_to_string(registry_path)
160 .ok()
161 .and_then(|s| serde_json::from_str(&s).ok())
162 .unwrap_or_default()
163 }
164
165 pub fn save(&self, registry_path: &Path) -> Result<()> {
169 if let Some(parent) = registry_path.parent() {
170 std::fs::create_dir_all(parent)?;
171 }
172 let json = serde_json::to_string_pretty(self)?;
173 std::fs::write(registry_path, json)?;
174 Ok(())
175 }
176
177 pub fn add_entry(&mut self, entry: RegistryEntry) {
178 self.entries.retain(|e| e.run_id != entry.run_id);
179 self.entries.push(entry);
180 self.entries.sort_by_key(|e| Reverse(e.timestamp_utc));
181 }
182
183 #[must_use]
185 pub fn entries_for_roots(&self, roots: &[String]) -> Vec<&RegistryEntry> {
186 self.entries
187 .iter()
188 .filter(|e| e.input_roots == roots)
189 .collect()
190 }
191
192 #[must_use]
193 pub fn find_by_run_id(&self, run_id: &str) -> Option<&RegistryEntry> {
194 self.entries.iter().find(|e| e.run_id == run_id)
195 }
196
197 pub fn prune_stale(&mut self) {
199 self.entries
200 .retain(|e| e.json_path.as_ref().is_none_or(|p| p.exists()));
201 }
202
203 pub fn remove_entries_under(&mut self, dir: &Path) -> usize {
207 let before = self.entries.len();
208 self.entries.retain(|e| {
209 let under = |p: &Option<PathBuf>| p.as_ref().is_some_and(|path| path.starts_with(dir));
210 !(under(&e.json_path) || under(&e.html_path))
211 });
212 before - self.entries.len()
213 }
214
215 pub fn retain_under_roots(&mut self, roots: &[PathBuf]) -> usize {
221 let before = self.entries.len();
222 self.entries.retain(|e| {
223 let under = |p: &Option<PathBuf>| {
224 p.as_ref()
225 .is_some_and(|path| roots.iter().any(|r| path.starts_with(r)))
226 };
227 under(&e.json_path) || under(&e.html_path)
228 });
229 before - self.entries.len()
230 }
231}
232
233const fn default_interval_hours() -> u32 {
234 24
235}
236
237#[derive(Debug, Clone, Serialize, Deserialize)]
239pub struct CleanupPolicy {
240 pub enabled: bool,
241 #[serde(default)]
243 pub max_age_days: Option<u32>,
244 #[serde(default)]
246 pub max_run_count: Option<u32>,
247 #[serde(default = "default_interval_hours")]
249 pub interval_hours: u32,
250}
251
252#[derive(Debug, Default, Clone, Serialize, Deserialize)]
255pub struct CleanupPolicyStore {
256 pub policy: Option<CleanupPolicy>,
257 #[serde(default)]
259 pub last_run_at: Option<DateTime<Utc>>,
260 #[serde(default)]
262 pub last_run_deleted: Option<u32>,
263}
264
265impl CleanupPolicyStore {
266 #[must_use]
267 pub fn load(path: &Path) -> Self {
268 std::fs::read_to_string(path)
269 .ok()
270 .and_then(|s| serde_json::from_str(&s).ok())
271 .unwrap_or_default()
272 }
273
274 pub fn save(&self, path: &Path) -> Result<()> {
278 if let Some(parent) = path.parent() {
279 std::fs::create_dir_all(parent)?;
280 }
281 std::fs::write(path, serde_json::to_string_pretty(self)?)?;
282 Ok(())
283 }
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 fn entry(run_id: &str, json: &str) -> RegistryEntry {
291 RegistryEntry {
292 run_id: run_id.to_string(),
293 timestamp_utc: Utc::now(),
294 project_label: "proj".to_string(),
295 input_roots: vec![],
296 json_path: Some(PathBuf::from(json)),
297 html_path: None,
298 pdf_path: None,
299 csv_path: None,
300 xlsx_path: None,
301 summary: ScanSummarySnapshot::default(),
302 git_branch: None,
303 git_commit: None,
304 git_commit_long: None,
305 git_author: None,
306 git_tags: None,
307 git_nearest_tag: None,
308 git_commit_date: None,
309 }
310 }
311
312 #[test]
313 fn remove_entries_under_drops_only_matching_folder() {
314 let mut reg = ScanRegistry::default();
315 reg.entries
316 .push(entry("a", "/watched/scans/run1/result.json"));
317 reg.entries
318 .push(entry("b", "/watched/scans/sub/json/result.json"));
319 reg.entries.push(entry("c", "/other/place/result.json"));
320
321 let removed = reg.remove_entries_under(Path::new("/watched/scans"));
322 assert_eq!(removed, 2);
323 assert_eq!(reg.entries.len(), 1);
324 assert_eq!(reg.entries[0].run_id, "c");
325 }
326
327 #[test]
328 fn remove_entries_under_no_match_is_noop() {
329 let mut reg = ScanRegistry::default();
330 reg.entries.push(entry("a", "/other/result.json"));
331 assert_eq!(reg.remove_entries_under(Path::new("/watched")), 0);
332 assert_eq!(reg.entries.len(), 1);
333 }
334
335 #[test]
336 fn retain_under_roots_keeps_only_watched_and_native() {
337 let mut reg = ScanRegistry::default();
338 reg.entries
339 .push(entry("native", "/app/out/web/run1/json/result.json"));
340 reg.entries
341 .push(entry("watched", "/watched/scans/run2/json/result.json"));
342 reg.entries
343 .push(entry("orphan", "/removed/folder/run3/json/result.json"));
344
345 let roots = vec![
346 PathBuf::from("/app/out/web"),
347 PathBuf::from("/watched/scans"),
348 ];
349 let removed = reg.retain_under_roots(&roots);
350 assert_eq!(removed, 1);
351 assert_eq!(reg.entries.len(), 2);
352 assert!(reg.entries.iter().all(|e| e.run_id != "orphan"));
353 }
354
355 #[test]
356 fn retain_under_roots_empty_roots_clears_all() {
357 let mut reg = ScanRegistry::default();
358 reg.entries.push(entry("a", "/somewhere/result.json"));
359 reg.entries.push(entry("b", "/elsewhere/result.json"));
360 assert_eq!(reg.retain_under_roots(&[]), 2);
361 assert!(reg.entries.is_empty());
362 }
363}