1use std::io::Write;
36use std::path::{Path, PathBuf};
37
38pub const FORMAT: &str = "amont-bypass-v1";
41
42const LEDGER: &str = "amont-bypasses";
44
45const MAX_BYTES: u64 = 64 * 1024;
48
49const KEEP: usize = 500;
53
54#[derive(Debug, Default, Clone, PartialEq, Eq)]
57pub struct Ledger {
58 pub total: usize,
60 pub last: Option<u64>,
62 pub by_script: Vec<ScriptCount>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ScriptCount {
70 pub script: String,
71 pub count: usize,
72 pub last: u64,
74}
75
76fn event(line: &str) -> Option<(u64, &str, &str)> {
81 let mut fields = line.split_whitespace();
82 let (Some(epoch), Some(oid), Some(script), None) =
83 (fields.next(), fields.next(), fields.next(), fields.next())
84 else {
85 return None;
86 };
87 let epoch = epoch.parse::<u64>().ok()?;
88 if !(7..=64).contains(&oid.len()) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) {
89 return None;
90 }
91 if !(1..=32).contains(&script.len()) || !script.bytes().all(|b| b.is_ascii_graphic()) {
92 return None;
93 }
94 Some((epoch, oid, script))
95}
96
97pub fn parse(text: &str) -> Ledger {
100 let mut lines = text.lines().filter(|l| !l.trim().is_empty());
101 if lines.next() != Some(FORMAT) {
102 return Ledger::default();
103 }
104 let mut out = Ledger::default();
105 for line in lines {
106 let Some((epoch, _oid, script)) = event(line) else {
107 continue;
108 };
109 out.total += 1;
110 out.last = Some(out.last.map_or(epoch, |l| l.max(epoch)));
111 match out.by_script.iter_mut().find(|s| s.script == script) {
112 Some(s) => {
113 s.count += 1;
114 s.last = s.last.max(epoch);
115 }
116 None => out.by_script.push(ScriptCount {
117 script: script.to_string(),
118 count: 1,
119 last: epoch,
120 }),
121 }
122 }
123 out.by_script
124 .sort_by(|a, b| b.count.cmp(&a.count).then(a.script.cmp(&b.script)));
125 out
126}
127
128pub fn read_at(common_dir: &Path) -> Ledger {
131 read_file(&common_dir.join(LEDGER))
132}
133
134pub fn read() -> Ledger {
137 ledger_path().map(|p| read_file(&p)).unwrap_or_default()
138}
139
140fn read_file(path: &Path) -> Ledger {
141 std::fs::read_to_string(path)
142 .map(|t| parse(&t))
143 .unwrap_or_default()
144}
145
146pub fn age(now: u64, then: u64) -> String {
150 let d = now.saturating_sub(then);
151 if d < 60 {
152 "just now".to_string()
153 } else if d < 3600 {
154 format!("{}m ago", d / 60)
155 } else if d < 86_400 {
156 format!("{}h ago", d / 3600)
157 } else if d < 7 * 86_400 {
158 format!("{}d ago", d / 86_400)
159 } else if d < 365 * 86_400 {
160 format!("{}w ago", d / (7 * 86_400))
161 } else {
162 format!("{}y ago", d / (365 * 86_400))
163 }
164}
165
166pub(crate) fn note_unverified(manifest: &crate::manifest::Manifest, stamped: &[String]) {
176 let names = crate::hooks::run_tests::gate_names_declared(&manifest.externals);
177 if names.is_empty() {
178 return;
179 }
180 if names.iter().all(|n| stamped.iter().any(|s| s == n)) {
181 return;
182 }
183 let declared = crate::hooks::run_tests::gated_at_commit(&manifest.externals);
186 let missing: Vec<_> = declared
187 .iter()
188 .filter(|d| !stamped.iter().any(|s| s == d.script))
189 .collect();
190 if missing.is_empty() {
191 return;
192 }
193 if !crate::config::boolean_or("amont.recordBypasses", true) {
194 return;
195 }
196 let files = head_files();
197 if files.is_empty() {
198 return; }
200 let scripts: Vec<&str> = missing
201 .iter()
202 .filter(|d| d.scope.matches(&files))
203 .map(|d| d.script)
204 .collect();
205 if scripts.is_empty() {
206 return;
207 }
208 let Some(oid) = crate::git::stdout(&["rev-parse", "HEAD"]) else {
209 return;
210 };
211 let Some(path) = ledger_path() else { return };
212 append(&path, &oid, &scripts);
213}
214
215fn head_files() -> Vec<String> {
220 crate::git::stdout_paths(&[
221 "diff-tree",
222 "--no-commit-id",
223 "--name-only",
224 "-r",
225 "-m",
226 "--root",
227 "HEAD",
228 ])
229 .unwrap_or_default()
230}
231
232fn ledger_path() -> Option<PathBuf> {
234 let dir = crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
235 Some(Path::new(&dir).join(LEDGER))
236}
237
238fn append(path: &Path, commit: &str, scripts: &[&str]) {
242 let _ = std::fs::OpenOptions::new()
245 .write(true)
246 .create_new(true)
247 .open(path)
248 .and_then(|mut f| f.write_all(format!("{FORMAT}\n").as_bytes()));
249 compact_if_large(path);
250 let now = now_epoch();
251 let mut body = String::new();
252 for script in scripts {
253 body.push_str(&format!("{now} {commit} {script}\n"));
254 }
255 let _ = std::fs::OpenOptions::new()
258 .create(true)
259 .append(true)
260 .open(path)
261 .and_then(|mut f| f.write_all(body.as_bytes()));
262}
263
264fn compact_if_large(path: &Path) {
268 let Ok(meta) = std::fs::metadata(path) else {
269 return;
270 };
271 if meta.len() <= MAX_BYTES {
272 return;
273 }
274 let Ok(text) = std::fs::read_to_string(path) else {
275 return;
276 };
277 let events: Vec<&str> = text.lines().filter(|l| event(l).is_some()).collect();
278 let keep = &events[events.len().saturating_sub(KEEP)..];
279 let mut body = String::with_capacity(keep.len() * 64 + FORMAT.len() + 1);
280 body.push_str(FORMAT);
281 body.push('\n');
282 for line in keep {
283 body.push_str(line);
284 body.push('\n');
285 }
286 let tmp = path.with_file_name(format!("{LEDGER}.tmp-{}", std::process::id()));
287 if std::fs::write(&tmp, body).is_ok() {
288 let _ = std::fs::rename(&tmp, path);
289 }
290}
291
292fn now_epoch() -> u64 {
293 std::time::SystemTime::now()
294 .duration_since(std::time::UNIX_EPOCH)
295 .map(|d| d.as_secs())
296 .unwrap_or_default()
297}
298
299pub fn forget() {
301 if let Some(path) = ledger_path() {
302 let _ = std::fs::remove_file(&path);
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 fn ledger(events: &[&str]) -> String {
311 let mut s = format!("{FORMAT}\n");
312 for e in events {
313 s.push_str(e);
314 s.push('\n');
315 }
316 s
317 }
318
319 #[test]
321 fn a_ledger_without_the_header_is_ignored() {
322 assert_eq!(parse("100 abcdef0 typecheck\n"), Ledger::default());
323 assert_eq!(parse(""), Ledger::default());
324 }
325
326 #[test]
328 fn a_ledger_in_an_unknown_format_version_reads_as_empty() {
329 assert_eq!(
330 parse("amont-bypass-v2\n100 abcdef0 typecheck\n"),
331 Ledger::default()
332 );
333 }
334
335 #[test]
337 fn malformed_lines_are_skipped_and_the_rest_still_counted() {
338 let text = ledger(&[
339 "100 abcdef0 typecheck",
340 "not an event line",
341 "101 abcdef0", "102 abcdef0 test extra", "103 nothexg typecheck", "104 abc typecheck", "105 abcdef0 test",
346 ]);
347 let l = parse(&text);
348 assert_eq!(l.total, 2);
349 assert_eq!(l.last, Some(105));
350 }
351
352 #[test]
355 fn a_script_name_with_a_control_byte_is_rejected() {
356 let text = ledger(&["100 abcdef0 type\u{1b}check"]);
357 assert_eq!(parse(&text).total, 0);
358 }
359
360 #[test]
363 fn counts_group_by_script_and_keep_the_latest_timestamp() {
364 let text = ledger(&[
365 "100 aaaaaaa typecheck",
366 "200 bbbbbbb test",
367 "300 ccccccc typecheck",
368 ]);
369 let l = parse(&text);
370 assert_eq!(l.total, 3);
371 assert_eq!(l.last, Some(300));
372 assert_eq!(l.by_script.len(), 2);
373 assert_eq!(l.by_script[0].script, "typecheck");
374 assert_eq!(l.by_script[0].count, 2);
375 assert_eq!(l.by_script[0].last, 300);
376 assert_eq!(l.by_script[1].script, "test");
377 assert_eq!(l.by_script[1].last, 200);
378 }
379
380 #[test]
383 fn an_absent_ledger_reads_as_empty() {
384 let dir = std::env::temp_dir().join(format!("amont-bypass-none-{}", std::process::id()));
385 let _ = std::fs::create_dir_all(&dir);
386 assert_eq!(read_at(&dir), Ledger::default());
387 let _ = std::fs::remove_dir_all(&dir);
388 }
389
390 #[test]
393 fn compaction_keeps_the_header_and_the_newest_events() {
394 let dir = std::env::temp_dir().join(format!("amont-bypass-compact-{}", std::process::id()));
395 let _ = std::fs::create_dir_all(&dir);
396 let path = dir.join(LEDGER);
397 let mut body = format!("{FORMAT}\n");
398 for i in 0..2_600u64 {
400 body.push_str(&format!("{i} abcdef0123456789 typecheck\n"));
401 }
402 std::fs::write(&path, body).unwrap();
403 compact_if_large(&path);
404 let text = std::fs::read_to_string(&path).unwrap();
405 assert!(text.starts_with(FORMAT));
406 let l = parse(&text);
407 assert_eq!(l.total, KEEP);
408 assert_eq!(l.last, Some(2_599), "the newest events survive");
409 let _ = std::fs::remove_dir_all(&dir);
410 }
411
412 #[test]
415 fn appending_twice_writes_exactly_one_header() {
416 let dir = std::env::temp_dir().join(format!("amont-bypass-append-{}", std::process::id()));
417 let _ = std::fs::create_dir_all(&dir);
418 let path = dir.join(LEDGER);
419 append(&path, "abcdef0123456789", &["typecheck"]);
420 append(&path, "abcdef0123456789", &["test"]);
421 let text = std::fs::read_to_string(&path).unwrap();
422 assert_eq!(text.matches(FORMAT).count(), 1, "{text:?}");
423 assert_eq!(parse(&text).total, 2);
424 let _ = std::fs::remove_dir_all(&dir);
425 }
426
427 #[test]
429 fn age_reads_in_the_largest_unit_that_fits() {
430 assert_eq!(age(1000, 990), "just now");
431 assert_eq!(age(1000 + 120, 1000), "2m ago");
432 assert_eq!(age(1000 + 2 * 3600, 1000), "2h ago");
433 assert_eq!(age(1000 + 3 * 86_400, 1000), "3d ago");
434 assert_eq!(age(1000 + 20 * 86_400, 1000), "2w ago");
435 assert_eq!(age(1000 + 800 * 86_400, 1000), "2y ago");
436 }
437
438 #[test]
441 fn a_timestamp_from_the_future_does_not_underflow() {
442 assert_eq!(age(100, 200), "just now");
443 }
444}