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() {
303 if let Some(path) = ledger_path() {
304 let _ = std::fs::remove_file(&path);
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn ledger(events: &[&str]) -> String {
313 let mut s = format!("{FORMAT}\n");
314 for e in events {
315 s.push_str(e);
316 s.push('\n');
317 }
318 s
319 }
320
321 #[test]
323 fn a_ledger_without_the_header_is_ignored() {
324 assert_eq!(parse("100 abcdef0 typecheck\n"), Ledger::default());
325 assert_eq!(parse(""), Ledger::default());
326 }
327
328 #[test]
330 fn a_ledger_in_an_unknown_format_version_reads_as_empty() {
331 assert_eq!(
332 parse("amont-bypass-v2\n100 abcdef0 typecheck\n"),
333 Ledger::default()
334 );
335 }
336
337 #[test]
339 fn malformed_lines_are_skipped_and_the_rest_still_counted() {
340 let text = ledger(&[
341 "100 abcdef0 typecheck",
342 "not an event line",
343 "101 abcdef0", "102 abcdef0 test extra", "103 nothexg typecheck", "104 abc typecheck", "105 abcdef0 test",
348 ]);
349 let l = parse(&text);
350 assert_eq!(l.total, 2);
351 assert_eq!(l.last, Some(105));
352 }
353
354 #[test]
357 fn a_script_name_with_a_control_byte_is_rejected() {
358 let text = ledger(&["100 abcdef0 type\u{1b}check"]);
359 assert_eq!(parse(&text).total, 0);
360 }
361
362 #[test]
365 fn counts_group_by_script_and_keep_the_latest_timestamp() {
366 let text = ledger(&[
367 "100 aaaaaaa typecheck",
368 "200 bbbbbbb test",
369 "300 ccccccc typecheck",
370 ]);
371 let l = parse(&text);
372 assert_eq!(l.total, 3);
373 assert_eq!(l.last, Some(300));
374 assert_eq!(l.by_script.len(), 2);
375 assert_eq!(l.by_script[0].script, "typecheck");
376 assert_eq!(l.by_script[0].count, 2);
377 assert_eq!(l.by_script[0].last, 300);
378 assert_eq!(l.by_script[1].script, "test");
379 assert_eq!(l.by_script[1].last, 200);
380 }
381
382 #[test]
385 fn an_absent_ledger_reads_as_empty() {
386 let dir = std::env::temp_dir().join(format!("amont-bypass-none-{}", std::process::id()));
387 let _ = std::fs::create_dir_all(&dir);
388 assert_eq!(read_at(&dir), Ledger::default());
389 let _ = std::fs::remove_dir_all(&dir);
390 }
391
392 #[test]
395 fn compaction_keeps_the_header_and_the_newest_events() {
396 let dir = std::env::temp_dir().join(format!("amont-bypass-compact-{}", std::process::id()));
397 let _ = std::fs::create_dir_all(&dir);
398 let path = dir.join(LEDGER);
399 let mut body = format!("{FORMAT}\n");
400 for i in 0..2_600u64 {
402 body.push_str(&format!("{i} abcdef0123456789 typecheck\n"));
403 }
404 std::fs::write(&path, body).unwrap();
405 compact_if_large(&path);
406 let text = std::fs::read_to_string(&path).unwrap();
407 assert!(text.starts_with(FORMAT));
408 let l = parse(&text);
409 assert_eq!(l.total, KEEP);
410 assert_eq!(l.last, Some(2_599), "the newest events survive");
411 let _ = std::fs::remove_dir_all(&dir);
412 }
413
414 #[test]
417 fn appending_twice_writes_exactly_one_header() {
418 let dir = std::env::temp_dir().join(format!("amont-bypass-append-{}", std::process::id()));
419 let _ = std::fs::create_dir_all(&dir);
420 let path = dir.join(LEDGER);
421 append(&path, "abcdef0123456789", &["typecheck"]);
422 append(&path, "abcdef0123456789", &["test"]);
423 let text = std::fs::read_to_string(&path).unwrap();
424 assert_eq!(text.matches(FORMAT).count(), 1, "{text:?}");
425 assert_eq!(parse(&text).total, 2);
426 let _ = std::fs::remove_dir_all(&dir);
427 }
428
429 #[test]
431 fn age_reads_in_the_largest_unit_that_fits() {
432 assert_eq!(age(1000, 990), "just now");
433 assert_eq!(age(1000 + 120, 1000), "2m ago");
434 assert_eq!(age(1000 + 2 * 3600, 1000), "2h ago");
435 assert_eq!(age(1000 + 3 * 86_400, 1000), "3d ago");
436 assert_eq!(age(1000 + 20 * 86_400, 1000), "2w ago");
437 assert_eq!(age(1000 + 800 * 86_400, 1000), "2y ago");
438 }
439
440 #[test]
443 fn a_timestamp_from_the_future_does_not_underflow() {
444 assert_eq!(age(100, 200), "just now");
445 }
446}