Skip to main content

cornerstone/
out.rs

1//! Output helpers: leveled messages, tables, and a progress bar. All respect
2//! the global quiet/color state so command bodies never branch on it themselves.
3
4use crate::style as s;
5use std::io::Write;
6use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
7
8static QUIET: AtomicBool = AtomicBool::new(false);
9static VERBOSITY: AtomicU8 = AtomicU8::new(0);
10
11/// Set global quiet mode: suppresses info/success chatter, keeps errors.
12pub fn set_quiet(q: bool) {
13    QUIET.store(q, Ordering::Relaxed);
14}
15/// Set verbosity level (number of `-v`); `debug` prints only at >=1.
16pub fn set_verbosity(v: u8) {
17    VERBOSITY.store(v, Ordering::Relaxed);
18}
19pub fn is_quiet() -> bool {
20    QUIET.load(Ordering::Relaxed)
21}
22pub fn verbosity() -> u8 {
23    VERBOSITY.load(Ordering::Relaxed)
24}
25
26/// A neutral informational line to stdout (suppressed when quiet).
27pub fn info<S: AsRef<str>>(msg: S) {
28    if is_quiet() {
29        return;
30    }
31    println!("{}", msg.as_ref());
32}
33
34/// A success line to stdout (suppressed when quiet). Uses the theme's success
35/// glyph (empty by default) and success color.
36pub fn success<S: AsRef<str>>(msg: S) {
37    if is_quiet() {
38        return;
39    }
40    let t = crate::theme::active();
41    if t.success_glyph.is_empty() {
42        println!("{}", msg.as_ref());
43    } else {
44        println!("{} {}", t.color_success.paint(&t.success_glyph), msg.as_ref());
45    }
46}
47
48/// A warning line to stderr. Always shown. Uses the theme's warn label/color.
49pub fn warn<S: AsRef<str>>(msg: S) {
50    let t = crate::theme::active();
51    eprintln!("{} {}", t.color_warn.paint(&t.warn_label), msg.as_ref());
52}
53
54/// An error line to stderr. Always shown. Uses the theme's error label/color.
55pub fn error<S: AsRef<str>>(msg: S) {
56    let t = crate::theme::active();
57    eprintln!("{} {}", t.color_error.paint(&t.error_label), msg.as_ref());
58}
59
60/// A debug line to stderr, shown only when verbosity >= level.
61pub fn debug<S: AsRef<str>>(level: u8, msg: S) {
62    if verbosity() >= level {
63        let t = crate::theme::active();
64        eprintln!("{} {}", t.color_debug.paint(&t.debug_label), msg.as_ref());
65    }
66}
67
68/// A simple auto-aligned ASCII table.
69pub struct Table {
70    headers: Vec<String>,
71    rows: Vec<Vec<String>>,
72}
73
74impl Table {
75    pub fn new(headers: &[&str]) -> Self {
76        Table {
77            headers: headers.iter().map(|h| h.to_string()).collect(),
78            rows: Vec::new(),
79        }
80    }
81    pub fn row(&mut self, cells: &[&str]) -> &mut Self {
82        self.rows.push(cells.iter().map(|c| c.to_string()).collect());
83        self
84    }
85    pub fn render(&self) -> String {
86        let cols = self.headers.len();
87        let mut widths = vec![0usize; cols];
88        for (i, h) in self.headers.iter().enumerate() {
89            widths[i] = h.chars().count();
90        }
91        for r in &self.rows {
92            for (i, c) in r.iter().enumerate() {
93                let cw = c.chars().count();
94                if i < cols && cw > widths[i] {
95                    widths[i] = cw;
96                }
97            }
98        }
99        let mut out = String::new();
100        // header
101        for (i, h) in self.headers.iter().enumerate() {
102            out.push_str(&pad_display(&s::bold(h), h, widths[i]));
103            if i + 1 < cols {
104                out.push_str("  ");
105            }
106        }
107        out.push('\n');
108        // separator
109        for (i, w) in widths.iter().enumerate() {
110            out.push_str(&"-".repeat(*w));
111            if i + 1 < cols {
112                out.push_str("  ");
113            }
114        }
115        out.push('\n');
116        // rows
117        for r in &self.rows {
118            for (i, c) in r.iter().enumerate() {
119                out.push_str(&pad_display(c, c, widths[i]));
120                if i + 1 < cols {
121                    out.push_str("  ");
122                }
123            }
124            out.push('\n');
125        }
126        out
127    }
128    pub fn print(&self) {
129        if is_quiet() {
130            return;
131        }
132        print!("{}", self.render());
133    }
134}
135
136// Left-pad `styled` (which may contain ANSI codes) to `target` display columns,
137// measured by the plain text's character count. This keeps columns aligned even
138// when the visible text is styled or contains multi-byte characters. Note: it
139// counts Unicode scalar values, not grapheme/wcwidth cells, so full-width CJK or
140// combining marks can still misalign; adequate for typical CLI table content.
141fn pad_display(styled: &str, plain: &str, target: usize) -> String {
142    let visible = plain.chars().count();
143    let pad = target.saturating_sub(visible);
144    format!("{}{}", styled, " ".repeat(pad))
145}
146
147/// A minimal progress bar for loops. Renders to stderr, only if stderr is a tty
148/// and we are not quiet; otherwise it is a no-op so pipes stay clean.
149pub struct Progress {
150    total: u64,
151    current: u64,
152    label: String,
153    active: bool,
154    width: usize,
155}
156
157impl Progress {
158    pub fn new(total: u64, label: &str) -> Self {
159        let active = !is_quiet() && s::is_stderr_tty();
160        let width = crate::theme::active().progress_width;
161        Progress {
162            total,
163            current: 0,
164            label: label.to_string(),
165            active,
166            width,
167        }
168    }
169    pub fn inc(&mut self, by: u64) {
170        self.current = (self.current + by).min(self.total);
171        self.draw();
172    }
173    pub fn set(&mut self, value: u64) {
174        self.current = value.min(self.total);
175        self.draw();
176    }
177    fn draw(&self) {
178        if !self.active {
179            return;
180        }
181        let t = crate::theme::active();
182        let frac = if self.total == 0 {
183            1.0
184        } else {
185            self.current as f64 / self.total as f64
186        };
187        let filled = (frac * self.width as f64).round() as usize;
188        let bar = format!(
189            "{}{}",
190            t.progress_fill.repeat(filled),
191            t.progress_empty.repeat(self.width - filled)
192        );
193        eprint!(
194            "\r{} [{}] {}/{}",
195            self.label,
196            t.color_accent.paint(&bar),
197            self.current,
198            self.total
199        );
200        let _ = std::io::stderr().flush();
201    }
202    pub fn finish(&self, msg: &str) {
203        if !self.active {
204            return;
205        }
206        let t = crate::theme::active();
207        eprint!("\r{}\r", " ".repeat(self.label.len() + self.width + 20));
208        if t.success_glyph.is_empty() {
209            eprintln!("{}", msg);
210        } else {
211            eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
212        }
213    }
214}
215
216// ---------- spinner, timer, tree, key/value ----------
217
218/// An indeterminate spinner for work of unknown length. Like `Progress`, it is
219/// a no-op unless stderr is a tty and not quiet, so pipes stay clean. Call
220/// `tick` periodically; call `finish` when done.
221pub struct Spinner {
222    frames: Vec<char>,
223    idx: usize,
224    label: String,
225    active: bool,
226}
227
228impl Spinner {
229    pub fn new(label: &str) -> Self {
230        Spinner {
231            frames: vec!['|', '/', '-', '\\'],
232            idx: 0,
233            label: label.to_string(),
234            active: !is_quiet() && s::is_stderr_tty(),
235        }
236    }
237    pub fn tick(&mut self) {
238        if !self.active {
239            return;
240        }
241        let f = self.frames[self.idx % self.frames.len()];
242        self.idx += 1;
243        eprint!("\r{} {}", crate::theme::active().color_accent.paint(f.to_string()), self.label);
244        let _ = std::io::stderr().flush();
245    }
246    pub fn finish(&self, msg: &str) {
247        if !self.active {
248            return;
249        }
250        eprint!("\r{}\r", " ".repeat(self.label.len() + 4));
251        let t = crate::theme::active();
252        if t.success_glyph.is_empty() {
253            eprintln!("{}", msg);
254        } else {
255            eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
256        }
257    }
258}
259
260/// A scoped stopwatch. [`Timer::elapsed_ms`] returns raw milliseconds and
261/// [`Timer::human`] a friendly string, for "how long did this take" reporting.
262pub struct Timer {
263    start: std::time::Instant,
264}
265
266impl Timer {
267    pub fn start() -> Self {
268        Timer {
269            start: std::time::Instant::now(),
270        }
271    }
272    pub fn elapsed_ms(&self) -> u128 {
273        self.start.elapsed().as_millis()
274    }
275    /// A human-friendly elapsed string: `920ms`, `1.5s`, `2m 3s`.
276    pub fn human(&self) -> String {
277        let ms = self.elapsed_ms();
278        if ms < 1000 {
279            format!("{}ms", ms)
280        } else if ms < 60_000 {
281            format!("{:.1}s", ms as f64 / 1000.0)
282        } else {
283            let s = ms / 1000;
284            format!("{}m {}s", s / 60, s % 60)
285        }
286    }
287}
288
289/// Print an aligned key/value block (suppressed when quiet). Keys are dimmed and
290/// right-padded to align values.
291pub fn kv(pairs: &[(&str, &str)]) {
292    if is_quiet() {
293        return;
294    }
295    let w = pairs.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
296    for (k, v) in pairs {
297        println!("{}  {}", pad_display(&s::dim(k), k, w), v);
298    }
299}
300
301/// A simple tree node for rendering hierarchical output.
302pub struct Tree {
303    pub label: String,
304    pub children: Vec<Tree>,
305}
306
307impl Tree {
308    pub fn new<S: Into<String>>(label: S) -> Self {
309        Tree {
310            label: label.into(),
311            children: Vec::new(),
312        }
313    }
314    pub fn child(mut self, node: Tree) -> Self {
315        self.children.push(node);
316        self
317    }
318    pub fn push(&mut self, node: Tree) -> &mut Self {
319        self.children.push(node);
320        self
321    }
322    /// Render the tree with box-drawing connectors.
323    pub fn render(&self) -> String {
324        let mut out = String::new();
325        out.push_str(&self.label);
326        out.push('\n');
327        self.render_children(&mut out, "");
328        out
329    }
330    fn render_children(&self, out: &mut String, prefix: &str) {
331        let n = self.children.len();
332        for (i, child) in self.children.iter().enumerate() {
333            let last = i + 1 == n;
334            let (branch, cont) = if last {
335                ("└── ", "    ")
336            } else {
337                ("├── ", "│   ")
338            };
339            out.push_str(prefix);
340            out.push_str(branch);
341            out.push_str(&child.label);
342            out.push('\n');
343            child.render_children(out, &format!("{}{}", prefix, cont));
344        }
345    }
346    pub fn print(&self) {
347        if is_quiet() {
348            return;
349        }
350        print!("{}", self.render());
351    }
352}