返回 CodeWhale
session_image_prune.rs
根目录 / crates / engine / src / session_image_prune.rs
1 use std::collections::{BTreeMap, HashSet};
2 use std::io::{self, Read};
3 use std::path::{Path, PathBuf};
4 use std::time::{Duration, SystemTime};
5
6 use crate::session_secret_scrub::{directory_entries, entry_has_type};
7
8 pub const PRUNE_IMAGES_COMMAND: &str = "codewhale sessions prune-images";
9
10 const NAME_PREFIX: &[u8] = b"clipboard-";
11 const NAME_SUFFIX: &[u8] = b".png";
12 const SCAN_CHUNK: usize = 1 << 20;
13 const NAME_CARRY: usize = 96;
14
15 #[derive(Debug, Default)]
16 pub struct ImagePruneReport {
17 pub images: usize,
18 pub image_bytes: u64,
19 pub referenced: usize,
20 pub recent: usize,
21 pub unreferenced: Vec<(PathBuf, u64)>,
22 pub removed: Vec<(PathBuf, u64)>,
23 pub failed: Vec<(PathBuf, String)>,
24 pub files_scanned: usize,
25 pub unreadable: Vec<PathBuf>,
26 }
27
28 impl ImagePruneReport {
29 #[must_use]
30 pub fn unreferenced_bytes(&self) -> u64 {
31 self.unreferenced.iter().map(|(_, bytes)| bytes).sum()
32 }
33
34 #[must_use]
35 pub fn removed_bytes(&self) -> u64 {
36 self.removed.iter().map(|(_, bytes)| bytes).sum()
37 }
38 }
39
40 #[must_use]
41 pub fn is_clipboard_image_name(name: &str) -> bool {
42 name.strip_prefix("clipboard-")
43 .and_then(|rest| rest.strip_suffix(".png"))
44 .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
45 }
46
47 pub fn prune_clipboard_images(
48 image_dir: &Path,
49 scan_roots: &[PathBuf],
50 grace: Duration,
51 apply: bool,
52 ) -> ImagePruneReport {
53 let mut report = ImagePruneReport::default();
54 let mut images: BTreeMap<String, (PathBuf, u64, SystemTime)> = BTreeMap::new();
55 for entry in directory_entries(image_dir, &mut report.unreadable) {
56 let name = entry.file_name().to_string_lossy().into_owned();
57 if !is_clipboard_image_name(&name) || !entry_has_type(&entry, false, &mut report.unreadable)
58 {
59 continue;
60 }
61 match entry.metadata() {
62 Ok(meta) => {
63 report.image_bytes += meta.len();
64 images.insert(
65 name,
66 (
67 entry.path(),
68 meta.len(),
69 meta.modified().unwrap_or(SystemTime::now()),
70 ),
71 );
72 }
73 Err(_) => report.unreadable.push(entry.path()),
74 }
75 }
76 report.images = images.len();
77 if images.is_empty() {
78 return report;
79 }
80
81 let excluded = std::fs::canonicalize(image_dir).unwrap_or_else(|_| image_dir.to_path_buf());
82 let mut referenced = HashSet::new();
83 let mut seen_roots = HashSet::new();
84 let mut pending: Vec<PathBuf> = Vec::new();
85 for root in scan_roots {
86 if let Ok(root) = std::fs::canonicalize(root)
87 && seen_roots.insert(root.clone())
88 {
89 pending.push(root);
90 }
91 }
92 let mut visited_dirs = HashSet::new();
93 while let Some(dir) = pending.pop() {
94 if dir == excluded || !visited_dirs.insert(dir.clone()) {
95 continue;
96 }
97 for entry in directory_entries(&dir, &mut report.unreadable) {
98 let Ok(kind) = entry.file_type() else {
99 report.unreadable.push(entry.path());
100 continue;
101 };
102 if kind.is_dir() {
103 pending.push(entry.path());
104 } else if kind.is_file() {
105 report.files_scanned += 1;
106 if scan_file(&entry.path(), &mut referenced).is_err() {
107 report.unreadable.push(entry.path());
108 }
109 if images
110 .keys()
111 .all(|name| referenced.contains(name.as_bytes()))
112 {
113 pending.clear();
114 break;
115 }
116 }
117 }
118 }
119
120 let now = SystemTime::now();
121 for (name, (path, bytes, modified)) in images {
122 if referenced.contains(name.as_bytes()) {
123 report.referenced += 1;
124 } else if now.duration_since(modified).unwrap_or_default() < grace {
125 report.recent += 1;
126 } else {
127 report.unreferenced.push((path, bytes));
128 }
129 }
130 report.unreadable.sort();
131 report.unreadable.dedup();
132 if apply && report.unreadable.is_empty() {
133 for (path, bytes) in std::mem::take(&mut report.unreferenced) {
134 match std::fs::remove_file(&path) {
135 Ok(()) => report.removed.push((path, bytes)),
136 Err(error) => report.failed.push((path, error.to_string())),
137 }
138 }
139 }
140 report
141 }
142
143 fn scan_file(path: &Path, referenced: &mut HashSet<Vec<u8>>) -> io::Result<()> {
144 let mut file = std::fs::File::open(path)?;
145 let mut buffer = vec![0_u8; SCAN_CHUNK + NAME_CARRY];
146 let mut carried = 0;
147 loop {
148 let read = file.read(&mut buffer[carried..])?;
149 if read == 0 {
150 break;
151 }
152 let filled = carried + read;
153 let window = &buffer[..filled];
154 let mut start = 0;
155 while let Some(offset) = find(&window[start..], NAME_PREFIX) {
156 let begin = start + offset;
157 let digits_start = begin + NAME_PREFIX.len();
158 let digits_end = window[digits_start..]
159 .iter()
160 .position(|byte| !byte.is_ascii_digit())
161 .map_or(filled, |len| digits_start + len);
162 let end = digits_end + NAME_SUFFIX.len();
163 if digits_end > digits_start && end <= filled && &window[digits_end..end] == NAME_SUFFIX
164 {
165 referenced.insert(window[begin..end].to_vec());
166 }
167 start = digits_start;
168 }
169 carried = filled.min(NAME_CARRY);
170 buffer.copy_within(filled - carried..filled, 0);
171 }
172 Ok(())
173 }
174
175 fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
176 haystack
177 .windows(needle.len())
178 .position(|window| window == needle)
179 }
180
180 lines RUST