amont-runtime 1.6.0

The amont hook logic: registry, dispatchers, checks and the trust model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! One check, one block — and while it runs, one line: per-check output
//! capture plus a live progress region for the concurrent stage.
//!
//! Twenty checks used to print straight to inherited stdio from their own
//! threads, so two failing linters shuffled their lines together and the
//! reader un-shuffled them by hand — the dispatcher's roll-up existed partly
//! to apologise for it. Now every check writes into its own slot, and a
//! completed check's output reaches stdout as ONE locked write: contiguous,
//! whatever the other nineteen were doing.
//!
//! Three writers feed a slot:
//!
//! 1. The check's own thread, through [`say`] — which is what
//!    `common::ok/fail/warn` call. A thread with no slot installed (commit-msg,
//!    `amont install`, the dispatcher itself) prints directly, exactly as
//!    before; nothing outside a stage changes.
//! 2. A captured child's reader threads, through [`Stage::append_raw`] —
//!    they are not the check's thread, so the thread-local cannot carry the
//!    routing; the `Arc` is captured before the spawn instead.
//! 3. Nobody else. The dispatcher's own lines (skips, pins, the roll-up)
//!    happen strictly before or after the fan-out and stay direct.
//!
//! Order across checks is COMPLETION order — deterministic per block, not
//! per stage, which is the same nondeterminism the interleaved version had
//! without the shuffling. `amont.progress false` switches the whole
//! mechanism off and restores raw streaming for anyone who wants to watch a
//! tool write in real time.
//!
//! # The region
//!
//! When stderr is a real terminal ([`watching`]) the stage also paints a
//! live region UNDER the finished blocks: one line per running check —
//! braille spinner, name, elapsed — repainted every 80ms by a ticker
//! thread, shrinking as checks finish, gone without a trace when the stage
//! ends. Blocks go to stdout, the region to stderr; both feed one tty, and
//! every write to either happens under the same [`Stage::out`] lock, so a
//! block never tears a repaint in half. Piped, redirected, `TERM=dumb`, or
//! CI: [`watching`] is false, no ticker starts, and the region costs
//! nothing — which is also why the test suite (piped stdio throughout)
//! exercises capture but never the paint.

use std::cell::RefCell;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::Instant;

/// The fleet spinner's frames (progress.rs) — cycled by elapsed time, so a
/// frame needs no state beyond the clock.
const FRAMES: [char; 10] = ['', '', '', '', '', '', '', '', '', ''];

/// The region never grows past this many check lines; the rest fold into
/// one `… and N more`. Twelve is the whole default fleet on one screen.
const MAX_LINES: usize = 12;

/// One check's place in the stage.
struct Slot {
    /// Sanitised at [`Stage::begin`]: a manifest-declared name is
    /// repo-derived text and the region writes it to a live terminal.
    name: String,
    /// Restamped by [`Stage::enter`], so a serial stage (pre-push) times
    /// each check from its own start, not the stage's.
    started: Instant,
    buf: Vec<u8>,
    /// Entered and not yet finished — the region shows exactly these.
    running: bool,
    done: bool,
}

/// A running stage: the slots, and the one lock every terminal write inside
/// the stage goes through.
pub struct Stage {
    slots: Mutex<Vec<Slot>>,
    /// Serialises block emission and region repaints; the value is how many
    /// region lines are currently painted (what an erase must remove).
    out: Mutex<usize>,
    /// Painting at all? [`enabled`] && [`watching`], decided once at begin.
    live: bool,
    stop: AtomicBool,
}

thread_local! {
    /// Where [`say`] routes on THIS thread: a stage and a slot index.
    static SINK: RefCell<Option<(Arc<Stage>, usize)>> = const { RefCell::new(None) };
}

impl Stage {
    /// A stage over `names`, in dispatch order. Does nothing visible until
    /// checks start entering (the region) or finishing (the blocks).
    pub fn begin(names: &[&str]) -> Arc<Stage> {
        let now = Instant::now();
        let stage = Arc::new(Stage {
            slots: Mutex::new(
                names
                    .iter()
                    .map(|n| Slot {
                        // Every name in a stage carries the stage's own
                        // prefix ("pre-commit-clippy"); the region drops it
                        // — twelve identical prefixes say nothing.
                        name: crate::ui::sanitize(
                            n.strip_prefix("pre-commit-")
                                .or_else(|| n.strip_prefix("pre-push-"))
                                .unwrap_or(n),
                        ),
                        started: now,
                        buf: Vec::new(),
                        running: false,
                        done: false,
                    })
                    .collect(),
            ),
            out: Mutex::new(0),
            live: enabled() && watching(),
            stop: AtomicBool::new(false),
        });
        if stage.live {
            // The ticker holds a Weak: the stage dropping is what ends it,
            // so a paint can never outlive the region's owner.
            let weak = Arc::downgrade(&stage);
            let _ = std::thread::Builder::new()
                .name("amont-live".into())
                .spawn(move || tick(weak));
        }
        stage
    }

    /// Route this thread's [`say`] calls into slot `idx` until the guard
    /// drops. Installed by the dispatcher around each `check.run`. Also
    /// starts the slot's clock and puts it in the region.
    pub fn enter(self: &Arc<Stage>, idx: usize) -> SinkGuard {
        {
            let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
            if let Some(slot) = slots.get_mut(idx) {
                slot.running = true;
                slot.started = Instant::now();
            }
        }
        SINK.with(|s| *s.borrow_mut() = Some((Arc::clone(self), idx)));
        SinkGuard
    }

    /// Append raw bytes (a captured child's output) to slot `idx`.
    pub fn append_raw(&self, idx: usize, bytes: &[u8]) {
        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(slot) = slots.get_mut(idx) {
            if !slot.done {
                slot.buf.extend_from_slice(bytes);
            }
        }
    }

    fn append_line(&self, idx: usize, line: &str) {
        let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
        if let Some(slot) = slots.get_mut(idx) {
            if !slot.done {
                slot.buf.extend_from_slice(line.as_bytes());
                slot.buf.push(b'\n');
            }
        }
    }

    /// The check is over: emit everything it said as ONE contiguous write,
    /// with the region lifted out of the way first and repainted after —
    /// blocks pile up above, spinners stay below.
    ///
    /// Called by the dispatcher after `check.run` returns (still on the
    /// check's thread, so a torn-down thread cannot strand a buffer — the
    /// same `catch_unwind` that feeds the dead-check outcome runs first).
    pub fn finish(&self, idx: usize) {
        let block = {
            let mut slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
            let Some(slot) = slots.get_mut(idx) else {
                return;
            };
            slot.done = true;
            slot.running = false;
            std::mem::take(&mut slot.buf)
        };
        if block.is_empty() && !self.live {
            return;
        }
        let mut drawn = self.out.lock().unwrap_or_else(|p| p.into_inner());
        if !block.is_empty() {
            if *drawn > 0 {
                let mut err = std::io::stderr().lock();
                let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
                let _ = err.flush();
                *drawn = 0;
            }
            let stdout = std::io::stdout();
            let mut handle = stdout.lock();
            let _ = handle.write_all(&block);
            let _ = handle.flush();
        }
        self.repaint(&mut drawn);
    }

    /// Erase and redraw the region in one stderr write. Lock order is
    /// `out` → `slots`, everywhere — never the reverse.
    fn repaint(&self, drawn: &mut usize) {
        if !self.live {
            return;
        }
        let entries: Vec<(String, f64)> = {
            let slots = self.slots.lock().unwrap_or_else(|p| p.into_inner());
            let now = Instant::now();
            slots
                .iter()
                .filter(|s| s.running && !s.done)
                .map(|s| (s.name.clone(), now.duration_since(s.started).as_secs_f64()))
                .collect()
        };
        let text = region(&entries, term_width());
        let mut paint = String::new();
        if *drawn > 0 {
            paint.push_str(&format!("\x1b[{}A\x1b[J", *drawn));
        }
        paint.push_str(&text);
        if paint.is_empty() {
            return;
        }
        let mut err = std::io::stderr().lock();
        let _ = err.write_all(paint.as_bytes());
        let _ = err.flush();
        *drawn = text.matches('\n').count();
    }
}

impl Drop for Stage {
    /// The stage's end erases whatever the region still shows — a Block
    /// verdict, a panic on the dispatcher path, anything: no spinner junk
    /// above the roll-up. (`get_mut`: dropping proves no other thread holds
    /// the stage, so the locks are free.)
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if !self.live {
            return;
        }
        let drawn = self.out.get_mut().unwrap_or_else(|p| p.into_inner());
        if *drawn > 0 {
            let mut err = std::io::stderr().lock();
            let _ = write!(err, "\x1b[{}A\x1b[J", *drawn);
            let _ = err.flush();
            *drawn = 0;
        }
    }
}

/// The ticker: repaint every 80ms until the stage drops or tells it to
/// stop. Holds only a `Weak`, so it can never keep a finished stage alive.
fn tick(weak: Weak<Stage>) {
    loop {
        std::thread::sleep(std::time::Duration::from_millis(80));
        let Some(stage) = weak.upgrade() else { return };
        if stage.stop.load(Ordering::Relaxed) {
            return;
        }
        let mut drawn = stage.out.lock().unwrap_or_else(|p| p.into_inner());
        stage.repaint(&mut drawn);
    }
}

/// The region's text: one `⠹ name  12.3s` line per running check, capped at
/// [`MAX_LINES`] plus a `… and N more` overflow line. Pure — the ticker is
/// a thin shell around this, and the tests drive it directly.
fn region(entries: &[(String, f64)], width: usize) -> String {
    if entries.is_empty() {
        return String::new();
    }
    let pad = entries
        .iter()
        .take(MAX_LINES)
        .map(|(name, _)| name.chars().count())
        .max()
        .unwrap_or(0);
    let mut out = String::new();
    for (name, secs) in entries.iter().take(MAX_LINES) {
        let frame = FRAMES[((secs * 10.0) as usize) % FRAMES.len()];
        let line = format!("{frame} {name:<pad$} {secs:>5.1}s");
        if line.chars().count() > width {
            out.extend(line.chars().take(width));
        } else {
            out.push_str(&line);
        }
        out.push('\n');
    }
    if entries.len() > MAX_LINES {
        out.push_str(&format!("… and {} more\n", entries.len() - MAX_LINES));
    }
    out
}

/// `$COLUMNS` when it is exported and sane, else a conservative 100 — the
/// region's lines are short and an ioctl is not worth its portability.
fn term_width() -> usize {
    std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.parse::<usize>().ok())
        .filter(|w| *w >= 20)
        .unwrap_or(100)
}

/// Emits slot `idx`'s block when dropped — however the check's closure
/// exits, a panic included: the partial output of a check that died still
/// reaches the reader, above the dead-check verdict the runner fills in.
pub struct FinishOnDrop<'a> {
    stage: &'a Stage,
    idx: usize,
}

impl<'a> FinishOnDrop<'a> {
    pub fn new(stage: &'a Stage, idx: usize) -> FinishOnDrop<'a> {
        FinishOnDrop { stage, idx }
    }
}

impl Drop for FinishOnDrop<'_> {
    fn drop(&mut self) {
        self.stage.finish(self.idx);
    }
}

/// Uninstalls the thread's sink on drop, whatever path the check took out.
pub struct SinkGuard;

impl Drop for SinkGuard {
    fn drop(&mut self) {
        SINK.with(|s| *s.borrow_mut() = None);
    }
}

/// The sink installed on THIS thread, if any — how a child-capture helper on
/// the check's own thread learns where the reader threads should append.
pub fn current_sink() -> Option<(Arc<Stage>, usize)> {
    SINK.with(|s| s.borrow().clone())
}

/// One line of check output, wherever it should go.
///
/// THE funnel: `common::ok/fail/warn` call this, so a check's helper prints
/// land in its slot during a stage and on stdout everywhere else. `line` is
/// taken without a trailing newline, exactly like `println!`.
pub fn say(line: &str) {
    let routed = SINK.with(|s| {
        s.borrow().as_ref().map(|(stage, idx)| {
            stage.append_line(*idx, line);
        })
    });
    if routed.is_none() {
        println!("{line}");
    }
}

/// `println!`, stage-aware: formats and routes through [`say`]. What every
/// direct print inside a CHECK BODY becomes — a line printed raw from a
/// check thread bypasses the slot and interleaves, which is the bug this
/// module exists to close.
#[macro_export]
macro_rules! say {
    ($($arg:tt)*) => {
        $crate::live::say(&format!($($arg)*))
    };
}

/// Whether the capture mechanism is on at all. `amont.progress false` is the
/// escape hatch back to raw streaming — one knob, read once.
pub fn enabled() -> bool {
    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ENABLED.get_or_init(|| crate::config::boolean_or("amont.progress", true))
}

/// Is anyone watching? True only when stderr is a real terminal that speaks
/// VT: not piped, not redirected, not `TERM=dumb` — and on Windows only
/// with `TERM` actually set, because bare conhost may not interpret the
/// cursor codes the region depends on. This is the paint gate; capture
/// ([`enabled`]) does not consult it.
pub fn watching() -> bool {
    static WATCHING: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *WATCHING.get_or_init(|| {
        if !std::io::stderr().is_terminal() {
            return false;
        }
        match std::env::var("TERM") {
            Ok(term) => term != "dumb",
            Err(_) => !cfg!(windows),
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The atomicity contract at the unit level: two threads writing
    /// interleaved lines into their own slots come out as two contiguous
    /// buffers, whatever the scheduler did.
    #[test]
    fn slots_do_not_share_a_buffer() {
        let stage = Stage::begin(&["a", "b"]);
        std::thread::scope(|scope| {
            for idx in 0..2 {
                let stage = Arc::clone(&stage);
                scope.spawn(move || {
                    let _guard = stage.enter(idx);
                    for i in 0..50 {
                        say(&format!("check-{idx} line-{i}"));
                        std::thread::yield_now();
                    }
                });
            }
        });
        let slots = stage.slots.lock().unwrap();
        for idx in 0..2 {
            let text = String::from_utf8(slots[idx].buf.clone()).unwrap();
            assert_eq!(text.lines().count(), 50);
            assert!(
                text.lines()
                    .all(|l| l.starts_with(&format!("check-{idx} "))),
                "a foreign line landed in slot {idx}"
            );
        }
    }

    /// A thread with no sink prints; its lines never land in anyone's slot.
    #[test]
    fn no_sink_means_no_capture() {
        let stage = Stage::begin(&["a"]);
        say("goes to stdout, not to a slot");
        let slots = stage.slots.lock().unwrap();
        assert!(slots[0].buf.is_empty());
    }

    /// After finish, late writes are dropped rather than stranded — a child
    /// reader thread that outlives its check must not corrupt a later block.
    #[test]
    fn a_finished_slot_takes_no_more_writes() {
        let stage = Stage::begin(&["a"]);
        stage.append_raw(0, b"before\n");
        stage.finish(0);
        stage.append_raw(0, b"after\n");
        let slots = stage.slots.lock().unwrap();
        assert!(slots[0].buf.is_empty(), "a write landed after finish");
    }

    /// A repo-derived check name cannot smuggle control bytes onto a live
    /// terminal: sanitised at begin, once, for every later paint.
    #[test]
    fn a_slot_name_is_sanitised_at_begin() {
        let stage = Stage::begin(&["evil\u{1b}[2Jname\rhere"]);
        let slots = stage.slots.lock().unwrap();
        assert!(!slots[0].name.contains('\u{1b}'), "{:?}", slots[0].name);
        assert!(!slots[0].name.contains('\r'), "{:?}", slots[0].name);
    }

    /// Region names drop the stage's own prefix — it is the same twelve
    /// characters on every line.
    #[test]
    fn a_slot_name_drops_the_stage_prefix() {
        let stage = Stage::begin(&["pre-commit-clippy", "pre-push-run-tests", "bare"]);
        let slots = stage.slots.lock().unwrap();
        assert_eq!(slots[0].name, "clippy");
        assert_eq!(slots[1].name, "run-tests");
        assert_eq!(slots[2].name, "bare");
    }

    /// The spinner frame comes from the clock: different elapsed, different
    /// frame; same elapsed, same frame.
    #[test]
    fn frames_advance_with_time() {
        let a = region(&[("clippy".into(), 0.0)], 80);
        let b = region(&[("clippy".into(), 0.1)], 80);
        let c = region(&[("clippy".into(), 1.0)], 80);
        assert_ne!(a.chars().next(), b.chars().next());
        assert_eq!(a.chars().next(), c.chars().next(), "10 frames per second");
    }

    /// Names pad to a column so the elapsed figures align.
    #[test]
    fn region_lines_align() {
        let text = region(&[("a".into(), 0.0), ("longer-name".into(), 0.0)], 80);
        let widths: Vec<usize> = text.lines().map(|l| l.chars().count()).collect();
        assert_eq!(widths[0], widths[1], "{text:?}");
    }

    /// Thirteen running checks paint as twelve lines and one overflow.
    #[test]
    fn region_caps_and_counts_the_rest() {
        let entries: Vec<(String, f64)> = (0..13).map(|i| (format!("check-{i}"), 0.0)).collect();
        let text = region(&entries, 80);
        assert_eq!(text.lines().count(), MAX_LINES + 1);
        assert!(text.ends_with("… and 1 more\n"), "{text:?}");
    }

    /// A narrow terminal truncates rather than wraps — a wrapped region
    /// line would break the erase arithmetic.
    #[test]
    fn region_respects_width() {
        let text = region(&[("a-name-much-longer-than-the-terminal".into(), 0.0)], 20);
        assert!(text.lines().all(|l| l.chars().count() <= 20), "{text:?}");
    }

    /// No running checks, no region — not even a blank line.
    #[test]
    fn an_empty_region_is_empty() {
        assert_eq!(region(&[], 80), "");
    }
}