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::blocking_commit_decls(&manifest.externals);
188 let missing: Vec<_> = declared
189 .iter()
190 .filter(|d| !stamped.contains(&d.script))
191 .collect();
192 if missing.is_empty() {
193 return;
194 }
195 if !crate::config::boolean_or("amont.recordBypasses", true) {
196 return;
197 }
198 let files = head_files();
199 if files.is_empty() {
200 return; }
202 let scripts: Vec<&str> = missing
203 .iter()
204 .filter(|d| d.scope.matches(&files))
205 .map(|d| d.script.as_str())
206 .collect();
207 if scripts.is_empty() {
208 return;
209 }
210 let Some(oid) = crate::git::stdout(&["rev-parse", "HEAD"]) else {
211 return;
212 };
213 let Some(path) = ledger_path() else { return };
214 append(&path, &oid, &scripts);
215}
216
217fn head_files() -> Vec<String> {
222 crate::git::stdout_paths(&[
223 "diff-tree",
224 "--no-commit-id",
225 "--name-only",
226 "-r",
227 "-m",
228 "--root",
229 "HEAD",
230 ])
231 .unwrap_or_default()
232}
233
234fn ledger_path() -> Option<PathBuf> {
236 let dir = crate::git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
237 Some(Path::new(&dir).join(LEDGER))
238}
239
240fn append(path: &Path, commit: &str, scripts: &[&str]) {
244 let _ = std::fs::OpenOptions::new()
247 .write(true)
248 .create_new(true)
249 .open(path)
250 .and_then(|mut f| f.write_all(format!("{FORMAT}\n").as_bytes()));
251 compact_if_large(path);
252 let now = now_epoch();
253 let mut body = String::new();
254 for script in scripts {
255 body.push_str(&format!("{now} {commit} {script}\n"));
256 }
257 let _ = std::fs::OpenOptions::new()
260 .create(true)
261 .append(true)
262 .open(path)
263 .and_then(|mut f| f.write_all(body.as_bytes()));
264}
265
266fn compact_if_large(path: &Path) {
270 let Ok(meta) = std::fs::metadata(path) else {
271 return;
272 };
273 if meta.len() <= MAX_BYTES {
274 return;
275 }
276 let Ok(text) = std::fs::read_to_string(path) else {
277 return;
278 };
279 let events: Vec<&str> = text.lines().filter(|l| event(l).is_some()).collect();
280 let keep = &events[events.len().saturating_sub(KEEP)..];
281 let mut body = String::with_capacity(keep.len() * 64 + FORMAT.len() + 1);
282 body.push_str(FORMAT);
283 body.push('\n');
284 for line in keep {
285 body.push_str(line);
286 body.push('\n');
287 }
288 let tmp = path.with_file_name(format!("{LEDGER}.tmp-{}", std::process::id()));
289 if std::fs::write(&tmp, body).is_ok() {
290 let _ = std::fs::rename(&tmp, path);
291 }
292}
293
294fn now_epoch() -> u64 {
295 std::time::SystemTime::now()
296 .duration_since(std::time::UNIX_EPOCH)
297 .map(|d| d.as_secs())
298 .unwrap_or_default()
299}
300
301pub fn forget() -> bool {
303 ledger_path().is_some_and(|path| std::fs::remove_file(&path).is_ok())
304}
305
306pub fn forget_in(repo: &Path) -> bool {
311 let Some(dir) = crate::git::stdout_in(
312 repo,
313 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
314 ) else {
315 return false;
316 };
317 std::fs::remove_file(Path::new(&dir).join(LEDGER)).is_ok()
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 fn ledger(events: &[&str]) -> String {
325 let mut s = format!("{FORMAT}\n");
326 for e in events {
327 s.push_str(e);
328 s.push('\n');
329 }
330 s
331 }
332
333 #[test]
335 fn a_ledger_without_the_header_is_ignored() {
336 assert_eq!(parse("100 abcdef0 typecheck\n"), Ledger::default());
337 assert_eq!(parse(""), Ledger::default());
338 }
339
340 #[test]
342 fn a_ledger_in_an_unknown_format_version_reads_as_empty() {
343 assert_eq!(
344 parse("amont-bypass-v2\n100 abcdef0 typecheck\n"),
345 Ledger::default()
346 );
347 }
348
349 #[test]
351 fn malformed_lines_are_skipped_and_the_rest_still_counted() {
352 let text = ledger(&[
353 "100 abcdef0 typecheck",
354 "not an event line",
355 "101 abcdef0", "102 abcdef0 test extra", "103 nothexg typecheck", "104 abc typecheck", "105 abcdef0 test",
360 ]);
361 let l = parse(&text);
362 assert_eq!(l.total, 2);
363 assert_eq!(l.last, Some(105));
364 }
365
366 #[test]
369 fn a_script_name_with_a_control_byte_is_rejected() {
370 let text = ledger(&["100 abcdef0 type\u{1b}check"]);
371 assert_eq!(parse(&text).total, 0);
372 }
373
374 #[test]
377 fn counts_group_by_script_and_keep_the_latest_timestamp() {
378 let text = ledger(&[
379 "100 aaaaaaa typecheck",
380 "200 bbbbbbb test",
381 "300 ccccccc typecheck",
382 ]);
383 let l = parse(&text);
384 assert_eq!(l.total, 3);
385 assert_eq!(l.last, Some(300));
386 assert_eq!(l.by_script.len(), 2);
387 assert_eq!(l.by_script[0].script, "typecheck");
388 assert_eq!(l.by_script[0].count, 2);
389 assert_eq!(l.by_script[0].last, 300);
390 assert_eq!(l.by_script[1].script, "test");
391 assert_eq!(l.by_script[1].last, 200);
392 }
393
394 #[test]
397 fn an_absent_ledger_reads_as_empty() {
398 let dir = std::env::temp_dir().join(format!("amont-bypass-none-{}", std::process::id()));
399 let _ = std::fs::create_dir_all(&dir);
400 assert_eq!(read_at(&dir), Ledger::default());
401 let _ = std::fs::remove_dir_all(&dir);
402 }
403
404 #[test]
407 fn compaction_keeps_the_header_and_the_newest_events() {
408 let dir = std::env::temp_dir().join(format!("amont-bypass-compact-{}", std::process::id()));
409 let _ = std::fs::create_dir_all(&dir);
410 let path = dir.join(LEDGER);
411 let mut body = format!("{FORMAT}\n");
412 for i in 0..2_600u64 {
414 body.push_str(&format!("{i} abcdef0123456789 typecheck\n"));
415 }
416 std::fs::write(&path, body).unwrap();
417 compact_if_large(&path);
418 let text = std::fs::read_to_string(&path).unwrap();
419 assert!(text.starts_with(FORMAT));
420 let l = parse(&text);
421 assert_eq!(l.total, KEEP);
422 assert_eq!(l.last, Some(2_599), "the newest events survive");
423 let _ = std::fs::remove_dir_all(&dir);
424 }
425
426 #[test]
429 fn appending_twice_writes_exactly_one_header() {
430 let dir = std::env::temp_dir().join(format!("amont-bypass-append-{}", std::process::id()));
431 let _ = std::fs::create_dir_all(&dir);
432 let path = dir.join(LEDGER);
433 append(&path, "abcdef0123456789", &["typecheck"]);
434 append(&path, "abcdef0123456789", &["test"]);
435 let text = std::fs::read_to_string(&path).unwrap();
436 assert_eq!(text.matches(FORMAT).count(), 1, "{text:?}");
437 assert_eq!(parse(&text).total, 2);
438 let _ = std::fs::remove_dir_all(&dir);
439 }
440
441 #[test]
443 fn age_reads_in_the_largest_unit_that_fits() {
444 assert_eq!(age(1000, 990), "just now");
445 assert_eq!(age(1000 + 120, 1000), "2m ago");
446 assert_eq!(age(1000 + 2 * 3600, 1000), "2h ago");
447 assert_eq!(age(1000 + 3 * 86_400, 1000), "3d ago");
448 assert_eq!(age(1000 + 20 * 86_400, 1000), "2w ago");
449 assert_eq!(age(1000 + 800 * 86_400, 1000), "2y ago");
450 }
451
452 #[test]
455 fn a_timestamp_from_the_future_does_not_underflow() {
456 assert_eq!(age(100, 200), "just now");
457 }
458}