ktstr/cli/util.rs
1//! Terminal-output utilities: color detection, table builders, the
2//! cargo-style status-line layout ([`status_line`] and the
3//! [`crate::ktstr_status`] macro every CLI status print goes through),
4//! status / success / warn helpers, and the `Spinner` progress bar.
5//!
6//! Holds the cross-binary helpers that the rest of the CLI surface
7//! delegates to for visible output. Lives in its own submodule
8//! because the Spinner machinery (panic-hook stash, nesting guard,
9//! termios save/restore) is its own contained subsystem unrelated
10//! to kernel build / list / resolve dispatch.
11
12use std::time::Duration;
13
14/// Whether stderr supports color (cached per process).
15pub fn stderr_color() -> bool {
16 use std::io::IsTerminal;
17 static COLOR: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
18 *COLOR.get_or_init(|| std::io::stderr().is_terminal())
19}
20
21/// Whether stdout supports color (cached per process). Distinct from
22/// [`stderr_color`] because `cargo ktstr perf-delta > report.txt`
23/// pipes stdout to a file while leaving stderr on the TTY — gating
24/// stdout tables on the stderr TTY state would leave ANSI escapes
25/// in the file. Table-rendering code paths gate on this reading;
26/// diagnostic/status prints use [`stderr_status_color`], which folds
27/// [`stderr_color`] together with the force/`NO_COLOR` knobs.
28pub fn stdout_color() -> bool {
29 use std::io::IsTerminal;
30 static COLOR: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
31 *COLOR.get_or_init(|| std::io::stdout().is_terminal())
32}
33
34/// Build a borderless comfy-table with styling gated on
35/// [`stdout_color`]. When stdout is not a TTY (CI, piped-to-file),
36/// `force_no_tty` suppresses cell color escapes so a log or grep
37/// capture does not land raw `\x1b[...` sequences. The NOTHING preset
38/// skips box-drawing characters and keeps whitespace-padded columns,
39/// matching the previous hand-rolled `format!("{:<30}…")` look while
40/// auto-measuring each column from actual cell contents.
41///
42/// `ContentArrangement::Disabled` is the default arrangement: columns
43/// expand to whatever each cell needs, even when the result spills
44/// past the terminal edge. Callers that want terminal-width-aware
45/// cell wrapping use [`new_wrapped_table`] (ctprof compare/show
46/// reaches it via `--wrap`).
47pub fn new_table() -> comfy_table::Table {
48 use comfy_table::{ContentArrangement, Table, presets::NOTHING};
49 let mut t = Table::new();
50 t.load_preset(NOTHING);
51 t.set_content_arrangement(ContentArrangement::Disabled);
52 if !stdout_color() {
53 t.force_no_tty();
54 }
55 t
56}
57
58/// Variant of [`new_table`] that opts into comfy-table's
59/// terminal-width-aware [`comfy_table::ContentArrangement::Dynamic`]
60/// layout. Cells too wide for the available terminal width wrap
61/// inside the cell rather than pushing later columns past the edge,
62/// at the cost of taller rows. Used by `ctprof compare` /
63/// `ctprof show` under the `--wrap` flag; the existing
64/// fixed-column [`new_table`] stays the default for every other
65/// caller (locks, verifier, stats) so their output stays
66/// byte-stable for shell-pipeline consumers.
67///
68/// When stdout is not a TTY, comfy-table's terminal-width probe
69/// returns `None`. The `Dynamic` arrangement is documented to
70/// degrade to `Disabled` in that case; we additionally call
71/// [`comfy_table::Table::force_no_tty`] under the same
72/// `!stdout_color()` gate as [`new_table`], so a piped stdout that
73/// requested `--wrap` still suppresses ANSI escapes. The end-state
74/// behaviour under a non-TTY stdout is therefore equivalent to
75/// [`new_table`]'s — the wrap request is silently dropped rather
76/// than producing unbounded-wrap output without a width.
77pub fn new_wrapped_table() -> comfy_table::Table {
78 use comfy_table::{ContentArrangement, Table, presets::NOTHING};
79 let mut t = Table::new();
80 t.load_preset(NOTHING);
81 t.set_content_arrangement(ContentArrangement::Dynamic);
82 if !stdout_color() {
83 t.force_no_tty();
84 }
85 t
86}
87
88/// Whether the environment ASKS for color on a non-TTY stdout (cached
89/// per process, like [`stdout_color`]): any of `GITHUB_ACTIONS`,
90/// `CLICOLOR_FORCE`, or `FORCE_COLOR` is set. GitHub Actions' log
91/// viewer renders ANSI color but its pipes are not TTYs, so plain
92/// TTY detection would strip the styling CI logs can actually show;
93/// the latter two are the conventional user-facing force-color knobs.
94/// Consulted by [`new_bordered_table`]'s cell policy and by
95/// [`stderr_status_color`] — in both cases only when `NO_COLOR` is
96/// unset, which always wins.
97fn env_forces_color() -> bool {
98 static FORCE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
99 *FORCE.get_or_init(|| {
100 ["GITHUB_ACTIONS", "CLICOLOR_FORCE", "FORCE_COLOR"]
101 .iter()
102 .any(|v| std::env::var_os(v).is_some())
103 })
104}
105
106/// Whether `NO_COLOR` is set (cached per process). Per the no-color
107/// convention, presence — any value — disables color; it outranks
108/// every force-color knob in [`new_bordered_table`]'s cell policy and
109/// in [`stderr_status_color`].
110fn env_no_color() -> bool {
111 static NO: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
112 *NO.get_or_init(|| std::env::var_os("NO_COLOR").is_some())
113}
114
115/// Apply [`new_bordered_table`]'s cell-color policy to `t`, with the
116/// three environment probes passed in as plain bools so unit tests can
117/// pin every branch deterministically (the probes themselves are
118/// process-cached and environment-dependent). Precedence:
119/// 1. `no_color` (NO_COLOR set) — `force_no_tty()`: no styling, ever.
120/// 2. `tty` ([`stdout_color`]) — leave comfy-table's own TTY detection
121/// in charge (it styles, and measures the terminal it sees).
122/// 3. `force_color` ([`env_forces_color`]) — `force_no_tty()` +
123/// `enforce_styling()`: emit cell colors despite the non-TTY stdout.
124/// 4. otherwise — `force_no_tty()`: plain piped output, no escapes.
125fn apply_bordered_color_policy(
126 t: &mut comfy_table::Table,
127 no_color: bool,
128 tty: bool,
129 force_color: bool,
130) {
131 if no_color {
132 t.force_no_tty();
133 } else if tty {
134 // Interactive stdout: comfy-table's default TTY detection
135 // already styles cells; nothing to override.
136 } else if force_color {
137 t.force_no_tty();
138 t.enforce_styling();
139 } else {
140 t.force_no_tty();
141 }
142}
143
144/// Build a BORDERED comfy-table. Unlike [`new_table`] (the borderless
145/// NOTHING preset), this loads comfy-table's `UTF8_FULL` preset plus the
146/// `UTF8_SOLID_INNER_BORDERS` modifier, so the rendered grid carries
147/// solid box-drawing borders (`│`, `─`, `┼`, …) around every cell rather
148/// than the preset's default dashed inner lines (`┆`, `╌`). Same
149/// `ContentArrangement::Disabled` (columns expand to their content, no
150/// terminal-width wrapping) as [`new_table`].
151///
152/// Cell-color policy (see `apply_bordered_color_policy`): colors
153/// render on an interactive TTY as with [`new_table`], but ALSO —
154/// deliberately unlike [`new_table`], which stays escape-free on every
155/// non-TTY stdout — on a non-TTY stdout when `GITHUB_ACTIONS`,
156/// `CLICOLOR_FORCE`, or `FORCE_COLOR` is set (via comfy-table's
157/// `enforce_styling`), so GitHub Actions logs render the PASS/FAIL grid
158/// green/red the way nextest's own output already does there. `NO_COLOR`
159/// outranks everything and disables styling. The env probes are cached
160/// per process like [`stdout_color`].
161///
162/// Used only by the verifier's per-scheduler PASS/FAIL grids
163/// ([`crate::verifier::render_result_table`]), where the border visually
164/// separates the tally line above each grid from the grid itself and
165/// delimits one scheduler's grid from the next. Every other table
166/// (locks, stats, `verified_insns`, the A/B diff) stays on the
167/// borderless [`new_table`] so its output remains byte-stable for
168/// shell-pipeline consumers.
169pub fn new_bordered_table() -> comfy_table::Table {
170 let mut t = bordered_table_base();
171 apply_bordered_color_policy(&mut t, env_no_color(), stdout_color(), env_forces_color());
172 t
173}
174
175/// The preset/arrangement half of [`new_bordered_table`], WITHOUT the
176/// environment-derived color policy. Split out so the policy tests can
177/// start from a virgin table and drive [`apply_bordered_color_policy`]
178/// with explicit bools instead of the process-cached env probes.
179fn bordered_table_base() -> comfy_table::Table {
180 use comfy_table::{
181 ContentArrangement, Table, modifiers::UTF8_SOLID_INNER_BORDERS, presets::UTF8_FULL,
182 };
183 let mut t = Table::new();
184 t.load_preset(UTF8_FULL);
185 t.apply_modifier(UTF8_SOLID_INNER_BORDERS);
186 t.set_content_arrangement(ContentArrangement::Disabled);
187 t
188}
189
190/// Restore SIGPIPE to its default action (terminate the process)
191/// so piping a ktstr binary's output to a reader that closes
192/// early (e.g. `... | head`) does not panic inside `print!` /
193/// `println!`. Rust's startup code sets SIGPIPE to `SIG_IGN`,
194/// which turns the broken-pipe write into an `io::Error` that
195/// `print!` escalates to a panic. Setting `SIG_DFL` restores the
196/// POSIX "process terminates on SIGPIPE" convention that Unix
197/// CLI tools rely on.
198///
199/// Call this at the TOP of each of the three user-facing CLIs'
200/// `main` — `ktstr`, `cargo-ktstr`, and `ktstr-jemalloc-probe` —
201/// before the tracing subscriber installs its stderr handler and
202/// before any stdout write. Shared across `src/bin/ktstr.rs`,
203/// `src/bin/cargo-ktstr.rs`, and `src/bin/jemalloc_probe.rs` so
204/// the three CLIs behave identically under `|` pipelines and a
205/// future reword of the SAFETY rationale lands in one place. The
206/// `ktstr-jemalloc-alloc-worker` binary does NOT call this — it
207/// is a test-fixture target spawned by the probe's closed-loop
208/// integration tests, never piped by a human operator, and its
209/// stdout emission path prints a single "ready" breadcrumb that
210/// the test body ignores, so SIGPIPE restoration there would
211/// add noise without benefit.
212///
213/// No return value; the call is effectively infallible (libc's
214/// `signal(2)` can't fail for a standard signal + SIG_DFL
215/// handler on a live process).
216///
217/// # Safety (FFI)
218///
219/// `libc::signal` is an FFI call with no memory effects (no
220/// pointer dereferences, no mutation of Rust state). `SIG_DFL`
221/// is a well-known constant handler. Call must run before any
222/// stdout writes so the handler is in place by the time
223/// `print!` fires.
224pub fn restore_sigpipe_default() {
225 // SAFETY: see fn-level doc comment.
226 unsafe {
227 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
228 }
229}
230
231/// Width of cargo's status column: `Compiling` / `Finished` and
232/// nextest's `Starting` / `PASS` are right-aligned in 12 columns, with
233/// the message starting at column 14. ktstr's own status lines share
234/// that geometry (see [`status_line`]) so an interleaved build → run
235/// transcript keeps one message column.
236pub const STATUS_LABEL_WIDTH: usize = 12;
237
238/// Longest `<label>:` head [`status_line`] will treat as a ktstr status
239/// prefix. Bounds the colon search so a long message whose first colon
240/// belongs to the payload (a path, a nested error) is left alone.
241const STATUS_LABEL_MAX: usize = 48;
242
243/// SGR prefix for the status label: bold + magenta, ktstr's counterpart
244/// to cargo's bold-green status verbs — a distinct hue so a ktstr line
245/// is not mistaken for one of cargo's or nextest's own.
246const STATUS_LABEL_SGR: &str = "\x1b[1;35m";
247
248/// Whether ktstr's own stderr status lines should carry ANSI color.
249/// A TTY colors; so does a non-TTY under `GITHUB_ACTIONS` /
250/// `CLICOLOR_FORCE` / `FORCE_COLOR` (Actions renders ANSI through a
251/// pipe, which is why cargo and nextest colorize there too); `NO_COLOR`
252/// outranks both. Same precedence as `new_bordered_table`'s cell
253/// policy, applied to stderr instead of stdout.
254pub fn stderr_status_color() -> bool {
255 !env_no_color() && (stderr_color() || env_forces_color())
256}
257
258/// Split a ktstr status line into its family root, its optional scope,
259/// and the message. `None` for any line outside the family, which the
260/// callers pass through untouched.
261///
262/// The family is every line the two CLIs emit as `<label>: <message>`
263/// where `<label>` is `ktstr` / `cargo ktstr` plus an optional scope
264/// (`verifier`, `nextest artifact cache`, `fatal`, …).
265fn split_status_label(head: &str) -> Option<(&'static str, &str, &str)> {
266 let root = ["cargo ktstr", "ktstr"].into_iter().find(|root| {
267 match head.as_bytes().get(root.len()) {
268 Some(b':' | b' ') => head.starts_with(root),
269 _ => false,
270 }
271 })?;
272 let colon = head.find(':').filter(|at| *at < STATUS_LABEL_MAX)?;
273 let scope = head[root.len()..colon].trim();
274 if !scope
275 .bytes()
276 .all(|b| b.is_ascii_alphanumeric() || b == b' ' || b == b'-' || b == b'_')
277 {
278 return None;
279 }
280 Some((root, scope, head[colon + 1..].trim_start_matches(' ')))
281}
282
283/// Render one ktstr status line in cargo's status-column layout: the
284/// family root right-aligned in [`STATUS_LABEL_WIDTH`] columns, the
285/// message at column 14, and any scope demoted into the message so a
286/// long scope cannot push the message column right.
287///
288/// ```text
289/// Compiling ktstr v0.42.0 (/home/you/ktstr)
290/// cargo ktstr: resolved kernel "6.14"
291/// cargo ktstr: nextest artifact cache: artifact-tree hit; role=direct-hit
292/// Starting 1523 tests across 12 binaries
293/// PASS [ 0.021s] ktstr admission::grants
294/// ```
295///
296/// `color` wraps the root in [`STATUS_LABEL_SGR`]; the padding stays
297/// outside the escape so the visible column is identical either way.
298/// Only the first line is re-laid-out — a multi-line message keeps its
299/// continuation lines verbatim.
300fn render_status_parts(line: &str, color: bool) -> Option<(String, String)> {
301 let (head, tail) = match line.find('\n') {
302 Some(at) => (&line[..at], &line[at..]),
303 None => (line, ""),
304 };
305 let (root, scope, message) = split_status_label(head)?;
306 let label = format!("{root}:");
307 let pad = " ".repeat(STATUS_LABEL_WIDTH.saturating_sub(label.len()));
308 let label = if color {
309 format!("{pad}{STATUS_LABEL_SGR}{label}\x1b[0m")
310 } else {
311 format!("{pad}{label}")
312 };
313 let message = match (scope.is_empty(), message.is_empty()) {
314 (true, true) => String::new(),
315 (true, false) => format!(" {message}"),
316 (false, true) => format!(" {scope}:"),
317 (false, false) => format!(" {scope}: {message}"),
318 };
319 Some((label, format!("{message}{tail}")))
320}
321
322/// [`render_status_parts`] rejoined into one line.
323fn render_status_line(line: &str, color: bool) -> Option<String> {
324 render_status_parts(line, color).map(|(label, message)| format!("{label}{message}"))
325}
326
327/// Lay one line out in cargo's status column (see
328/// [`STATUS_LABEL_WIDTH`]) against the live stderr color policy, with
329/// non-family lines passed through unchanged. Use this at the point a
330/// line reaches the terminal, not where it is built: test captures and
331/// diagnostics sinks then keep the plain, escape-free text.
332pub fn status_line(line: &str) -> String {
333 render_status_line(line, stderr_status_color()).unwrap_or_else(|| line.to_owned())
334}
335
336/// Print a status line to stderr in cargo's status-column layout.
337/// Prefer the [`ktstr_status!`](crate::ktstr_status) macro at call
338/// sites that format their line.
339pub fn print_status_line(line: &str) {
340 eprintln!("{}", status_line(line));
341}
342
343/// `eprintln!` for ktstr's own status lines: formats, then lays the
344/// line out through [`print_status_line`] (label right-aligned in
345/// cargo's status column, message at column 14, label colored when the
346/// terminal takes color). Format arguments are `eprintln!`'s.
347///
348/// ```
349/// # use ktstr::ktstr_status;
350/// let version = "6.14";
351/// ktstr_status!("cargo ktstr: resolved kernel {version:?}");
352/// ```
353#[macro_export]
354macro_rules! ktstr_status {
355 ($($arg:tt)*) => {
356 $crate::cli::print_status_line(&format!($($arg)*))
357 };
358}
359
360/// Print one status line whose MESSAGE carries `sgr` (the role color)
361/// while its label keeps [`status_line`]'s layout and label color, so a
362/// success line reads as one purple label plus one green message rather
363/// than a green run interrupted by the label's reset. Non-family lines
364/// take `sgr` whole, preserving the pre-layout behaviour.
365fn print_role_line(msg: &str, sgr: &str) {
366 let color = stderr_status_color();
367 match (render_status_parts(msg, color), color) {
368 (Some((label, message)), true) => eprintln!("{label}{sgr}{message}\x1b[0m"),
369 (Some((label, message)), false) => eprintln!("{label}{message}"),
370 (None, true) => eprintln!("{sgr}{msg}\x1b[0m"),
371 (None, false) => eprintln!("{msg}"),
372 }
373}
374
375/// Print a styled status message to stderr.
376pub(crate) fn status(msg: &str) {
377 print_role_line(msg, "\x1b[1m");
378}
379
380/// Print a green success message to stderr.
381pub(crate) fn success(msg: &str) {
382 print_role_line(msg, "\x1b[32m");
383}
384
385/// Print a blue warning to stderr.
386pub(crate) fn warn(msg: &str) {
387 print_role_line(msg, "\x1b[34m");
388}
389
390/// Stash of the pre-spinner termios for the panic hook's restore
391/// path. Populated by [`Spinner::disable_echo`] before the ECHO flag
392/// is cleared, and cleared by [`Spinner::teardown`] on normal exit.
393/// The panic hook reads this mutex — when populated, it replays the
394/// stashed termios to the terminal BEFORE the default panic handler
395/// emits its message. Under `panic = "abort"`, `Spinner::Drop` never
396/// runs, so without the hook the terminal stays in echo-disabled /
397/// non-canonical mode and the multi-line panic message staircases
398/// (LF without CR) before SIGABRT kills the process.
399static SPINNER_SAVED_TERMIOS: std::sync::Mutex<Option<libc::termios>> = std::sync::Mutex::new(None);
400
401/// Tracks whether a [`Spinner`] is currently alive. `Spinner::start`
402/// flips this from `false` to `true`; `Drop` flips it back. A
403/// `debug_assert!` at start-time fires when the previous value was
404/// already `true`, catching nested `Spinner::start()` calls that
405/// would clobber [`SPINNER_SAVED_TERMIOS`]: the second `start` saves
406/// the outer spinner's ALREADY-ECHO-disabled termios, and the outer
407/// teardown then restores to the disabled state instead of the
408/// original. Release builds skip the check (the assertion compiles
409/// away) rather than panic in production; the flag is still
410/// maintained so a future `debug_assert` → `assert` upgrade would
411/// not need a second seam.
412static SPINNER_ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
413
414/// Install a panic hook that restores stdin termios from
415/// [`SPINNER_SAVED_TERMIOS`] before the default panic handler prints.
416/// Called via [`std::sync::Once`] from [`Spinner::disable_echo`], so
417/// every Spinner that actually mutates termios triggers the install
418/// exactly once per process. Idempotent — subsequent calls hit the
419/// `Once` guard and no-op.
420///
421/// The hook delegates to the default `take_hook()` output after
422/// restoring, preserving the full panic-message contract (message,
423/// location, backtrace under `RUST_BACKTRACE`).
424///
425/// # Panic-hook stacking convention
426///
427/// ktstr installs hooks in two places: this spinner-termios restorer
428/// and the vCPU classifier (`crate::vmm::vcpu_panic::install_once`).
429/// `std::panic::set_hook` is process-wide — whichever site installs
430/// LAST wins, and earlier hooks are reached only via the previous-
431/// hook chain each site captures at install time. Every ktstr-side
432/// installer MUST follow the stacking pattern used here: call
433/// `std::panic::take_hook()` to capture the current hook, then
434/// `set_hook` a closure that runs its own work AND calls the
435/// captured `prev(info)` at the end. Skipping the delegation
436/// breaks the chain and silently drops every earlier-installed
437/// hook. See the module-level doc on `src/vmm/vcpu_panic.rs` for
438/// the full rationale (limitations section) and an alternative
439/// `make_hook(prev)` factoring; the pattern is identical, just
440/// packaged differently.
441fn install_spinner_termios_panic_hook() {
442 static INSTALLED: std::sync::Once = std::sync::Once::new();
443 INSTALLED.call_once(|| {
444 let default = std::panic::take_hook();
445 std::panic::set_hook(Box::new(move |info| {
446 // try_lock, not lock: if the panicking thread is the
447 // one mid-mutation inside Spinner::disable_echo (holds
448 // the mutex across its own libc::tcsetattr call), a
449 // blocking lock would deadlock the hook. try_lock
450 // failure ≈ "mutex held by someone mid-mutation" — the
451 // terminal state is indeterminate and the hook
452 // cannot safely restore, so we fall through to the
453 // default handler unchanged.
454 if let Ok(guard) = SPINNER_SAVED_TERMIOS.try_lock()
455 && let Some(termios) = *guard
456 {
457 unsafe {
458 libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &termios);
459 }
460 }
461 default(info);
462 }));
463 });
464}
465
466/// Progress spinner for long-running CLI operations.
467///
468/// When stderr is a TTY, draws an animated spinner via indicatif,
469/// ticks in the background, and disables stdin echo to prevent
470/// keypress jank. When stderr is not a TTY, skips all indicatif
471/// machinery and falls back to plain stderr writes.
472/// Call `finish` with a completion message to replace it with a
473/// final line, or let it drop to remove it silently; [`Drop`] also
474/// restores echo and clears the bar so a panic or early `?`
475/// propagation leaves the terminal in a usable state. Under
476/// `panic = "abort"`, Drop does NOT run on a panic — the panic hook
477/// installed by `install_spinner_termios_panic_hook` restores
478/// termios instead, so the panic message renders cleanly before
479/// SIGABRT kills the process. Note: Drop also does NOT run on
480/// SIGINT/SIGTERM kill; if the spinner is interrupted mid-operation,
481/// run `stty sane` to restore echo.
482pub struct Spinner {
483 /// None when stderr is not a TTY — no indicatif overhead.
484 pb: Option<indicatif::ProgressBar>,
485 /// Saved termios for echo restore. None when stdin is not a tty
486 /// or when the spinner is inactive (non-TTY stderr). Owned directly
487 /// (not `Arc<Mutex>`) because Spinner is not Clone.
488 saved_termios: Option<libc::termios>,
489}
490
491impl Spinner {
492 /// Start a spinner with the given message (e.g. "Building kernel...").
493 ///
494 /// When stderr is not a TTY, no ProgressBar or ticker thread is
495 /// created — all output methods fall back to plain `eprintln!`.
496 pub fn start(msg: impl Into<std::borrow::Cow<'static, str>>) -> Self {
497 // Nesting rejection: a second `Spinner::start()` while
498 // another Spinner is still live would overwrite
499 // SPINNER_SAVED_TERMIOS with the ALREADY-ECHO-disabled
500 // termios that the outer spinner installed; the outer's
501 // Drop / teardown would then restore the disabled state
502 // instead of the pre-spinner state, leaving the terminal
503 // broken after both exit. `debug_assert!` catches the
504 // misuse under `cargo test` / `cargo nextest` without
505 // paying a release-mode cost. Release builds allow the
506 // nesting and accept the terminal-leakage risk (the
507 // alternative — panicking release binaries — would be
508 // worse than a terminal that needs `reset` after a crash
509 // path that was never exercised in testing). If nesting
510 // is genuinely needed in the future, flip this guard and
511 // add depth-aware save/restore logic to `teardown()`.
512 //
513 // The flag is swapped unconditionally at start (before the
514 // TTY-absence short-circuit) AND cleared in both Drop and
515 // the `is_hidden()` early-return below, so the invariant
516 // `SPINNER_ACTIVE == true iff a Spinner exists` holds
517 // across every exit path.
518 debug_assert!(
519 !SPINNER_ACTIVE.swap(true, std::sync::atomic::Ordering::SeqCst),
520 "Spinner::start called while another Spinner is already \
521 active. Nested spinners clobber SPINNER_SAVED_TERMIOS — \
522 the outer spinner's restore path would reset to the \
523 already-modified termios state instead of the original. \
524 If nesting is genuinely needed, refactor the save/restore \
525 path to depth-count before lifting this assertion.",
526 );
527
528 if !stderr_color() {
529 return Spinner {
530 pb: None,
531 saved_termios: None,
532 };
533 }
534
535 let pb = indicatif::ProgressBar::new_spinner();
536 pb.set_style(
537 indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
538 .expect("valid template"),
539 );
540 pb.set_message(msg);
541 pb.enable_steady_tick(Duration::from_millis(80));
542
543 // indicatif hides the bar when NO_COLOR is set or TERM is
544 // dumb, even on a real TTY. Downgrade to the non-TTY path
545 // so println/finish output is not silently dropped.
546 if pb.is_hidden() {
547 return Spinner {
548 pb: None,
549 saved_termios: None,
550 };
551 }
552
553 let saved_termios = Self::disable_echo();
554
555 Spinner {
556 pb: Some(pb),
557 saved_termios,
558 }
559 }
560
561 fn disable_echo() -> Option<libc::termios> {
562 use std::io::IsTerminal;
563 if !std::io::stdin().is_terminal() {
564 return None;
565 }
566 unsafe {
567 let fd = libc::STDIN_FILENO;
568 let mut termios: libc::termios = std::mem::zeroed();
569 if libc::tcgetattr(fd, &mut termios) != 0 {
570 return None;
571 }
572 let saved = termios;
573 // Stash the pre-mutation termios for the panic hook's
574 // restore path. Under `panic=abort` the Spinner's Drop
575 // never runs, so if a panic fires while the spinner is
576 // active the terminal stays in echo-disabled mode and
577 // the panic message renders with a "staircase" effect
578 // (LF without CR). The hook replays the saved termios
579 // before the default panic handler prints, producing a
580 // readable diagnostic on the way to SIGABRT.
581 install_spinner_termios_panic_hook();
582 *SPINNER_SAVED_TERMIOS.lock().unwrap() = Some(saved);
583 termios.c_lflag &= !libc::ECHO;
584 libc::tcsetattr(fd, libc::TCSANOW, &termios);
585 Some(saved)
586 }
587 }
588
589 /// Restore stdin echo if we disabled it, consuming `saved_termios`
590 /// via [`Option::take`]. Idempotent — `finish` and the `Drop`
591 /// impl both call this; only the first call has any effect. The
592 /// old standalone `clear` method was consolidated into `Drop`
593 /// (calling `drop(spinner)` produces the same effect).
594 fn teardown(&mut self) {
595 if let Some(termios) = self.saved_termios.take() {
596 unsafe {
597 libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &termios);
598 }
599 // Clear the panic-hook stash — further panics without a
600 // live Spinner should NOT try to restore a termios we
601 // already restored via the normal path.
602 *SPINNER_SAVED_TERMIOS.lock().unwrap() = None;
603 }
604 }
605
606 /// Update the spinner message.
607 pub fn set_message(&self, msg: impl Into<std::borrow::Cow<'static, str>>) {
608 if let Some(ref pb) = self.pb {
609 pb.set_message(msg);
610 }
611 }
612
613 /// Finish the spinner, replacing it with a completion message.
614 ///
615 /// In non-TTY mode, prints the message to stderr directly.
616 pub fn finish(mut self, msg: impl Into<std::borrow::Cow<'static, str>>) {
617 self.teardown();
618 match self.pb.take() {
619 Some(pb) => pb.finish_with_message(msg),
620 None => eprintln!("{}", msg.into()),
621 }
622 }
623
624 /// Print a line above the spinner. The spinner redraws below.
625 ///
626 /// In non-TTY mode, prints directly to stderr.
627 pub fn println(&self, msg: impl AsRef<str>) {
628 match self.pb {
629 Some(ref pb) => pb.println(msg),
630 None => eprintln!("{}", msg.as_ref()),
631 }
632 }
633
634 /// Suspend the spinner tick, execute a closure, then resume.
635 /// Use for terminal output that must not race with the spinner.
636 ///
637 /// In non-TTY mode, calls `f` directly (no spinner to suspend).
638 pub fn suspend<F: FnOnce() -> R, R>(&self, f: F) -> R {
639 match self.pb {
640 Some(ref pb) => pb.suspend(f),
641 None => f(),
642 }
643 }
644
645 /// Run `f` under a spinner that starts with `start_msg`, replaces
646 /// itself with `success_msg` on `Ok`, and drops silently on `Err`
647 /// so the error propagates without a stale progress bar obscuring
648 /// the caller's diagnostics. The closure receives the live
649 /// `&Spinner` so it can call [`Self::println`] / [`Self::suspend`]
650 /// / [`Self::set_message`] during the operation.
651 pub fn with_progress<T, E, F>(
652 start_msg: impl Into<std::borrow::Cow<'static, str>>,
653 success_msg: impl Into<std::borrow::Cow<'static, str>>,
654 f: F,
655 ) -> Result<T, E>
656 where
657 F: FnOnce(&Spinner) -> Result<T, E>,
658 {
659 let sp = Spinner::start(start_msg);
660 let result = f(&sp);
661 match result {
662 Ok(v) => {
663 sp.finish(success_msg);
664 Ok(v)
665 }
666 Err(e) => {
667 drop(sp);
668 Err(e)
669 }
670 }
671 }
672}
673
674impl Drop for Spinner {
675 /// Restore terminal echo and clear any live progress bar on drop.
676 ///
677 /// [`finish`](Self::finish) calls `Self::teardown` and takes
678 /// `self.pb` via [`Option::take`], so this impl is a no-op after
679 /// an explicit end. When the spinner is dropped implicitly
680 /// (panic, `?` propagation, `drop(sp)`, or scope exit), this
681 /// restores the termios saved in `Self::disable_echo` and
682 /// clears the live bar so stdin is usable afterwards.
683 fn drop(&mut self) {
684 self.teardown();
685 if let Some(pb) = self.pb.take() {
686 pb.finish_and_clear();
687 }
688 // Release the nesting guard. Paired with the `swap(true)` in
689 // `Spinner::start`: Drop fires exactly once per Spinner
690 // (owned value), so the flag returns to `false` and the
691 // next call to `start` can succeed. Unconditional store
692 // rather than a swap — a nested misuse already panicked
693 // under `debug_assert`, so the ordering of the counter
694 // value on the first observer side is less important than
695 // releasing the guard for the next legitimate caller.
696 SPINNER_ACTIVE.store(false, std::sync::atomic::Ordering::SeqCst);
697 }
698}
699
700#[cfg(test)]
701mod tests {
702 use super::*;
703
704 /// The status column every ktstr line shares with cargo and
705 /// nextest: label right-aligned in [`STATUS_LABEL_WIDTH`], message
706 /// at column 14. `cargo ktstr:` fills the field exactly (so those
707 /// lines keep their historical bytes); the shorter `ktstr:` label
708 /// the `ktstr` binary and the library resolvers emit is indented
709 /// into it instead of hugging the left margin.
710 #[test]
711 fn status_layout_puts_every_label_in_cargos_status_column() {
712 let cargo = render_status_line("cargo ktstr: resolved kernel \"6.14\"", false)
713 .expect("cargo ktstr line is in the family");
714 assert_eq!(cargo, "cargo ktstr: resolved kernel \"6.14\"");
715 let plain = render_status_line("ktstr: kernel cached at /tmp/k", false)
716 .expect("ktstr line is in the family");
717 assert_eq!(plain, " ktstr: kernel cached at /tmp/k");
718 for line in [&cargo, &plain] {
719 assert_eq!(
720 line.find(':').expect("label colon") + 1,
721 STATUS_LABEL_WIDTH,
722 "label must end on the status column: {line:?}",
723 );
724 }
725 }
726
727 /// A scope (`verifier`, `nextest artifact cache`, `fatal`, …) is
728 /// demoted into the message so an arbitrarily long sub-label cannot
729 /// push the message column right. Every word survives, and the
730 /// `cargo ktstr: ` prefix scripts and docs grep for now heads those
731 /// lines too.
732 #[test]
733 fn status_layout_demotes_the_scope_into_the_message() {
734 assert_eq!(
735 render_status_line(
736 "cargo ktstr nextest artifact cache: artifact-tree hit; role=direct-hit",
737 false,
738 )
739 .expect("scoped line is in the family"),
740 "cargo ktstr: nextest artifact cache: artifact-tree hit; role=direct-hit",
741 );
742 assert_eq!(
743 render_status_line(
744 "cargo ktstr verifier: acquiring reserved build capacity",
745 false
746 )
747 .expect("scoped line is in the family"),
748 "cargo ktstr: verifier: acquiring reserved build capacity",
749 );
750 }
751
752 /// Color wraps the label only, with the padding OUTSIDE the escape
753 /// so the visible column is identical to the uncolored rendering,
754 /// and the message stays unstyled (cargo colors its verb, not the
755 /// text after it).
756 #[test]
757 fn status_layout_colors_only_the_label() {
758 let colored = render_status_line("ktstr: fetching latest kernel version", true)
759 .expect("family line renders");
760 assert_eq!(
761 colored,
762 " \x1b[1;35mktstr:\x1b[0m fetching latest kernel version",
763 );
764 let stripped = colored.replace(STATUS_LABEL_SGR, "").replace("\x1b[0m", "");
765 assert_eq!(
766 stripped,
767 render_status_line("ktstr: fetching latest kernel version", false).expect("family"),
768 "escapes must not move the visible column",
769 );
770 }
771
772 /// Lines outside the family are returned untouched by
773 /// [`status_line`] — a `Compiling`/`error:`/bare-text line keeps
774 /// its own layout, and a payload colon (a path, a nested error)
775 /// never gets mistaken for a label.
776 #[test]
777 fn status_layout_passes_non_family_lines_through() {
778 for line in [
779 " Compiling ktstr v0.42.0",
780 "error: no such kernel",
781 "/tmp/x: permission denied",
782 "ktstrfoo: not the family root",
783 "cargo ktstr /tmp/a: colon after a path segment",
784 ] {
785 assert!(
786 render_status_line(line, true).is_none(),
787 "must not be treated as a status label: {line:?}",
788 );
789 assert_eq!(status_line(line), line);
790 }
791 }
792
793 /// Only the FIRST line is re-laid-out: a multi-line status message
794 /// keeps its continuation text verbatim, and a trailing newline
795 /// (the heartbeat writers emit their own) survives the rendering.
796 #[test]
797 fn status_layout_preserves_continuation_lines() {
798 assert_eq!(
799 render_status_line("ktstr: first\n second: still raw\n", false).expect("family"),
800 " ktstr: first\n second: still raw\n",
801 );
802 }
803
804 #[test]
805 fn spinner_drop_without_finish_does_not_panic_in_non_tty() {
806 // Regression: Spinner previously had no Drop impl so early return
807 // or panic leaked the disabled-ECHO termios. The added Drop must
808 // run cleanly even on the non-TTY path (pb is None, saved_termios
809 // is None) that nextest exercises under stderr capture.
810 let sp = Spinner::start("test");
811 drop(sp);
812 }
813
814 #[test]
815 fn spinner_finish_then_drop_is_idempotent() {
816 // finish() takes pb via Option::take so Drop's pb.take() sees None
817 // and is a no-op on the progress bar side. teardown() is
818 // idempotent because it consumes saved_termios via Option::take;
819 // the second call finds None and does nothing. This test
820 // exercises that lifecycle end-to-end.
821 let sp = Spinner::start("test");
822 sp.finish("done");
823 }
824
825 /// Nesting guard pin: starting a second Spinner while another is
826 /// live must panic under `debug_assert!`. Exercises the
827 /// SPINNER_ACTIVE swap — without the guard, the inner spinner
828 /// would stash the outer's already-ECHO-disabled termios into
829 /// SPINNER_SAVED_TERMIOS, and the outer's teardown would restore
830 /// to that broken state instead of the pre-spinner original.
831 ///
832 /// `#[should_panic]` is gated on `debug_assertions` because the
833 /// assertion compiles away in release builds; running the test
834 /// without the debug gate under a release harness would make
835 /// the test fail when the expected panic doesn't fire. The
836 /// sibling `spinner_start_releases_guard_on_drop` test covers
837 /// the happy path (non-nested sequential spinners) and runs
838 /// under both profiles.
839 #[test]
840 #[cfg(debug_assertions)]
841 #[should_panic(expected = "Spinner::start called while another Spinner is already active")]
842 fn spinner_nested_start_panics_under_debug_assertions() {
843 let _outer = Spinner::start("outer");
844 // This call must fire the debug_assert! — the outer is
845 // still live in scope. The test framework captures the
846 // panic via `#[should_panic]`.
847 let _inner = Spinner::start("inner");
848 }
849
850 /// Happy path paired with the nesting-panic test: starting two
851 /// spinners SEQUENTIALLY (with the first dropped before the
852 /// second starts) must succeed. Guards against a regression that
853 /// forgot to clear SPINNER_ACTIVE in Drop and would one-shot the
854 /// guard after a single use.
855 #[test]
856 fn spinner_start_releases_guard_on_drop() {
857 {
858 let _sp = Spinner::start("first");
859 // Drop at end of block.
860 }
861 // After the first Spinner is dropped, the guard must be
862 // cleared so a fresh start succeeds without panicking.
863 let _sp = Spinner::start("second");
864 }
865
866 // ---------------------------------------------------------------
867 // Spinner public-API surface — testable on both TTY and non-TTY
868 // paths without requiring a real terminal.
869 // ---------------------------------------------------------------
870 //
871 // `Spinner::set_message`, `Spinner::println`, and
872 // `Spinner::suspend` all branch on `self.pb.is_some()` —
873 // `Some(pb)` on the TTY-active path delegates to indicatif,
874 // `None` on the non-TTY path falls back to a plain `eprintln!`
875 // or direct closure call. The tests pin the non-TTY arms
876 // (which is what runs under nextest's stderr capture) but
877 // also exercise the TTY arms when the test happens to run
878 // on a TTY-attached host (the assertions are shape-only —
879 // no stderr capture, just no-panic + correct return shape).
880
881 /// `Spinner::set_message` must not panic on either path. Pin
882 /// the non-TTY arm directly: `pb.is_none()` makes the call a
883 /// no-op. A regression that changed the gate (e.g. removed
884 /// the if-let guard) would surface as a panic on `None`.
885 #[test]
886 fn spinner_set_message_no_panic_on_non_tty() {
887 let sp = Spinner::start("initial");
888 sp.set_message("updated");
889 // Drop runs the teardown path — whether TTY or non-TTY,
890 // no panic must escape.
891 drop(sp);
892 }
893
894 /// `Spinner::println` writes through `eprintln!` on the non-TTY
895 /// path. Pin no-panic and the return-type contract (unit) — the
896 /// helper is fire-and-forget by design.
897 #[test]
898 fn spinner_println_no_panic_on_non_tty() {
899 let sp = Spinner::start("operation");
900 sp.println("interleaved log line");
901 drop(sp);
902 }
903
904 /// `Spinner::suspend` invokes the closure synchronously on
905 /// the non-TTY path and returns the closure's result
906 /// verbatim. Pins the value passthrough — a regression that
907 /// returned `Default` or dropped the value would surface
908 /// here.
909 #[test]
910 fn spinner_suspend_returns_closure_value_on_non_tty() {
911 let sp = Spinner::start("operation");
912 let v: u32 = sp.suspend(|| 42);
913 assert_eq!(v, 42);
914 let s: String = sp.suspend(|| "hello".to_string());
915 assert_eq!(s, "hello");
916 drop(sp);
917 }
918
919 /// `Spinner::with_progress` runs the closure under a fresh
920 /// spinner and returns `Ok(value)` on success. Pins the happy
921 /// path: the closure receives a `&Spinner` (testable via
922 /// `set_message`), and the success return propagates the
923 /// closure's `Ok` value verbatim.
924 #[test]
925 fn spinner_with_progress_returns_ok_value_on_success() {
926 let result: Result<u32, String> = Spinner::with_progress("starting", "done", |sp| {
927 sp.set_message("midway");
928 Ok(123)
929 });
930 assert_eq!(result, Ok(123));
931 }
932
933 /// `Spinner::with_progress` propagates `Err` from the
934 /// closure unchanged and drops the spinner silently (no
935 /// success message — the `Err` arm calls `drop(sp)` rather
936 /// than `sp.finish(success_msg)`). Pins the failure-path
937 /// contract: the spinner does not pollute stderr with a
938 /// "success" line when the underlying op failed.
939 #[test]
940 fn spinner_with_progress_propagates_err_without_finish_message() {
941 let result: Result<(), String> = Spinner::with_progress("starting", "done", |_sp| {
942 Err("synthetic failure".to_string())
943 });
944 assert_eq!(result, Err("synthetic failure".to_string()));
945 }
946
947 /// Nested `with_progress` calls are sequential by construction
948 /// — the inner spinner only starts AFTER the outer's closure
949 /// returns. Pins the SPINNER_ACTIVE guard release path under
950 /// the convenience helper: a regression that leaked the
951 /// guard from `with_progress` would break sequential pairs.
952 #[test]
953 fn spinner_with_progress_sequential_pair_succeeds() {
954 let r1: Result<u8, String> = Spinner::with_progress("first", "first done", |_| Ok(1));
955 assert_eq!(r1, Ok(1));
956 // Second invocation must not panic under the nesting guard
957 // because the first's Drop already released it.
958 let r2: Result<u8, String> = Spinner::with_progress("second", "second done", |_| Ok(2));
959 assert_eq!(r2, Ok(2));
960 }
961
962 // ---------------------------------------------------------------
963 // Color helpers — caching contract
964 // ---------------------------------------------------------------
965
966 /// `stderr_color()` is cached via `OnceLock` — repeated calls
967 /// return the same value. Pins the cache invariant: a future
968 /// regression that re-probed `is_terminal()` on every call
969 /// would lose the per-process consistency contract that
970 /// downstream renderers depend on.
971 #[test]
972 fn stderr_color_returns_consistent_value_across_calls() {
973 let a = stderr_color();
974 let b = stderr_color();
975 assert_eq!(a, b, "stderr_color must be cached and stable per process",);
976 }
977
978 /// `stdout_color()` carries the same cached-per-process
979 /// contract as `stderr_color`. Pins the sibling cache.
980 #[test]
981 fn stdout_color_returns_consistent_value_across_calls() {
982 let a = stdout_color();
983 let b = stdout_color();
984 assert_eq!(a, b, "stdout_color must be cached and stable per process",);
985 }
986
987 // ---------------------------------------------------------------
988 // restore_sigpipe_default — FFI shim no-panic
989 // ---------------------------------------------------------------
990
991 /// `restore_sigpipe_default` is an FFI call wrapping
992 /// `libc::signal(SIGPIPE, SIG_DFL)` — infallible by libc's
993 /// own contract for a standard signal + standard handler.
994 /// Pins the no-panic contract: every ktstr CLI binary calls
995 /// this once at top-of-main, and any panic here would
996 /// terminate before the operator's actual subcommand ran.
997 #[test]
998 fn restore_sigpipe_default_does_not_panic() {
999 // Idempotent: calling twice is also infallible (the
1000 // second call sets the handler that's already in place).
1001 // Pins the per-binary "call at top-of-main" pattern —
1002 // future code that re-armed SIG_IGN between calls would
1003 // surface a behavior change here.
1004 restore_sigpipe_default();
1005 restore_sigpipe_default();
1006 }
1007
1008 // ---------------------------------------------------------------
1009 // new_table / new_wrapped_table — comfy-table preset
1010 // ---------------------------------------------------------------
1011
1012 /// `new_table()` returns a comfy-table with NO box-drawing
1013 /// preset (whitespace-padded columns). Pin the rendering
1014 /// shape via a single-cell roundtrip: the rendered table
1015 /// must NOT contain box-drawing chars (`│`, `─`, `┼`, etc.)
1016 /// — those characters are the canonical preset signature
1017 /// that would surface if a regression swapped NOTHING for
1018 /// UTF8_FULL.
1019 #[test]
1020 fn new_table_uses_borderless_preset() {
1021 let mut t = new_table();
1022 t.set_header(["A", "B"]);
1023 t.add_row(["1", "2"]);
1024 let rendered = t.to_string();
1025 for ch in ['│', '─', '┼', '┴', '┬', '├', '┤'] {
1026 assert!(
1027 !rendered.contains(ch),
1028 "borderless table must not contain box-drawing char `{ch}`: {rendered}",
1029 );
1030 }
1031 // Cell content still rendered.
1032 assert!(rendered.contains("A"), "header A must render: {rendered}");
1033 assert!(rendered.contains("1"), "row cell 1 must render: {rendered}");
1034 }
1035
1036 /// `new_bordered_table()` loads the `UTF8_FULL` preset, so the
1037 /// rendered grid MUST contain box-drawing characters — the mirror
1038 /// image of `new_table_uses_borderless_preset`. Pins the border
1039 /// signature the verifier's PASS/FAIL grids rely on: a regression
1040 /// that swapped `UTF8_FULL` back to `NOTHING` would drop every
1041 /// box-drawing char and surface here.
1042 #[test]
1043 fn new_bordered_table_uses_bordered_preset() {
1044 let mut t = new_bordered_table();
1045 t.set_header(["A", "B"]);
1046 t.add_row(["1", "2"]);
1047 let rendered = t.to_string();
1048 let mut saw_box = false;
1049 for ch in ['│', '─', '┼', '┴', '┬', '├', '┤'] {
1050 if rendered.contains(ch) {
1051 saw_box = true;
1052 break;
1053 }
1054 }
1055 assert!(
1056 saw_box,
1057 "bordered table must contain box-drawing chars: {rendered}",
1058 );
1059 // Cell content still rendered alongside the borders.
1060 assert!(rendered.contains("A"), "header A must render: {rendered}");
1061 assert!(rendered.contains("1"), "row cell 1 must render: {rendered}");
1062 }
1063
1064 /// `apply_bordered_color_policy` escape emission per branch, driven
1065 /// with explicit bools so every assertion is deterministic no matter
1066 /// what TTY/env the test process actually has (the real probes are
1067 /// process-cached and CI sets `GITHUB_ACTIONS`):
1068 /// - non-TTY + force-color -> `enforce_styling` -> `Cell::fg` colors
1069 /// ARE emitted (the GITHUB_ACTIONS / CLICOLOR_FORCE / FORCE_COLOR
1070 /// branch that makes GHA logs render green/red);
1071 /// - plain non-TTY -> `force_no_tty` -> colors suppressed;
1072 /// - NO_COLOR -> suppressed, outranking BOTH the force knobs and a
1073 /// real TTY.
1074 ///
1075 /// The TTY branch (leave comfy-table's own detection in charge) is
1076 /// not asserted — its outcome depends on the process's real stdout.
1077 #[test]
1078 fn bordered_color_policy_escape_emission() {
1079 use comfy_table::{Attribute, Cell, Color};
1080 let render = |no_color: bool, tty: bool, force_color: bool| -> String {
1081 let mut t = bordered_table_base();
1082 apply_bordered_color_policy(&mut t, no_color, tty, force_color);
1083 t.set_header(["h"]);
1084 t.add_row([Cell::new("✓")
1085 .fg(Color::Green)
1086 .add_attribute(Attribute::Bold)]);
1087 t.to_string()
1088 };
1089 let styled = render(false, false, true);
1090 assert!(
1091 styled.contains('\x1b'),
1092 "force-color on a non-TTY must emit ANSI escapes: {styled:?}"
1093 );
1094 let plain = render(false, false, false);
1095 assert!(
1096 !plain.contains('\x1b'),
1097 "plain non-TTY must suppress ANSI escapes: {plain:?}"
1098 );
1099 // Styling changes only the escapes, not the visible glyphs.
1100 assert!(
1101 styled.contains('✓') && plain.contains('✓'),
1102 "cell glyph renders on both paths"
1103 );
1104 let no_color_beats_force = render(true, false, true);
1105 assert!(
1106 !no_color_beats_force.contains('\x1b'),
1107 "NO_COLOR outranks the force-color knobs: {no_color_beats_force:?}"
1108 );
1109 let no_color_beats_tty = render(true, true, false);
1110 assert!(
1111 !no_color_beats_tty.contains('\x1b'),
1112 "NO_COLOR outranks a real TTY: {no_color_beats_tty:?}"
1113 );
1114 }
1115
1116 /// `new_wrapped_table()` follows the same NOTHING preset (no
1117 /// box-drawing) but uses Dynamic content arrangement. Pins
1118 /// the borderless-preset contract for the wrapped-table
1119 /// variant — the only difference between `new_table` and
1120 /// `new_wrapped_table` is the `ContentArrangement`, NOT the
1121 /// preset. A regression that drifted the wrapped table to
1122 /// UTF8_FULL would surface here.
1123 #[test]
1124 fn new_wrapped_table_uses_borderless_preset() {
1125 let mut t = new_wrapped_table();
1126 t.set_header(["A"]);
1127 t.add_row(["x"]);
1128 let rendered = t.to_string();
1129 for ch in ['│', '─', '┼'] {
1130 assert!(
1131 !rendered.contains(ch),
1132 "borderless wrapped table must not contain box-drawing char `{ch}`: {rendered}",
1133 );
1134 }
1135 }
1136
1137 // ---------------------------------------------------------------
1138 // Panic hook installer — idempotency
1139 // ---------------------------------------------------------------
1140
1141 /// `install_spinner_termios_panic_hook` is gated by `Once`,
1142 /// so calling it many times must be a no-op after the first
1143 /// call lands. Pins the install path's idempotency: a
1144 /// regression that omitted the `Once` guard would re-take
1145 /// the previous hook into a Box-recursion chain and
1146 /// eventually panic on stack overflow.
1147 #[test]
1148 fn install_spinner_termios_panic_hook_is_idempotent() {
1149 // Direct invocation is safe — `set_hook` is process-wide
1150 // but the helper is gated by `INSTALLED: Once`. Multiple
1151 // calls coalesce into a single hook install. The test
1152 // does not unwind a panic; it pins the no-panic contract
1153 // on repeated install, regardless of whether other tests
1154 // earlier in the run already triggered the install.
1155 install_spinner_termios_panic_hook();
1156 install_spinner_termios_panic_hook();
1157 install_spinner_termios_panic_hook();
1158 // No assertion needed beyond no-panic — the failure mode
1159 // is recursion / overflow, which would surface as a test
1160 // failure, not as a missing assertion.
1161 }
1162}