cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Output helpers: leveled messages, tables, and a progress bar. All respect
//! the global quiet/color state so command bodies never branch on it themselves.

use crate::style as s;
use std::io::Write;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};

static QUIET: AtomicBool = AtomicBool::new(false);
static VERBOSITY: AtomicU8 = AtomicU8::new(0);

/// Set global quiet mode: suppresses info/success chatter, keeps errors.
pub fn set_quiet(q: bool) {
    QUIET.store(q, Ordering::Relaxed);
}
/// Set verbosity level (number of `-v`); `debug` prints only at >=1.
pub fn set_verbosity(v: u8) {
    VERBOSITY.store(v, Ordering::Relaxed);
}
pub fn is_quiet() -> bool {
    QUIET.load(Ordering::Relaxed)
}
pub fn verbosity() -> u8 {
    VERBOSITY.load(Ordering::Relaxed)
}

/// A neutral informational line to stdout (suppressed when quiet).
pub fn info<S: AsRef<str>>(msg: S) {
    if is_quiet() {
        return;
    }
    println!("{}", msg.as_ref());
}

/// A success line to stdout (suppressed when quiet). Uses the theme's success
/// glyph (empty by default) and success color.
pub fn success<S: AsRef<str>>(msg: S) {
    if is_quiet() {
        return;
    }
    let t = crate::theme::active();
    if t.success_glyph.is_empty() {
        println!("{}", msg.as_ref());
    } else {
        println!("{} {}", t.color_success.paint(&t.success_glyph), msg.as_ref());
    }
}

/// A warning line to stderr. Always shown. Uses the theme's warn label/color.
pub fn warn<S: AsRef<str>>(msg: S) {
    let t = crate::theme::active();
    eprintln!("{} {}", t.color_warn.paint(&t.warn_label), msg.as_ref());
}

/// An error line to stderr. Always shown. Uses the theme's error label/color.
pub fn error<S: AsRef<str>>(msg: S) {
    let t = crate::theme::active();
    eprintln!("{} {}", t.color_error.paint(&t.error_label), msg.as_ref());
}

/// A debug line to stderr, shown only when verbosity >= level.
pub fn debug<S: AsRef<str>>(level: u8, msg: S) {
    if verbosity() >= level {
        let t = crate::theme::active();
        eprintln!("{} {}", t.color_debug.paint(&t.debug_label), msg.as_ref());
    }
}

/// A simple auto-aligned ASCII table.
pub struct Table {
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
}

impl Table {
    pub fn new(headers: &[&str]) -> Self {
        Table {
            headers: headers.iter().map(|h| h.to_string()).collect(),
            rows: Vec::new(),
        }
    }
    pub fn row(&mut self, cells: &[&str]) -> &mut Self {
        self.rows.push(cells.iter().map(|c| c.to_string()).collect());
        self
    }
    pub fn render(&self) -> String {
        let cols = self.headers.len();
        let mut widths = vec![0usize; cols];
        for (i, h) in self.headers.iter().enumerate() {
            widths[i] = h.chars().count();
        }
        for r in &self.rows {
            for (i, c) in r.iter().enumerate() {
                let cw = c.chars().count();
                if i < cols && cw > widths[i] {
                    widths[i] = cw;
                }
            }
        }
        let mut out = String::new();
        // header
        for (i, h) in self.headers.iter().enumerate() {
            out.push_str(&pad_display(&s::bold(h), h, widths[i]));
            if i + 1 < cols {
                out.push_str("  ");
            }
        }
        out.push('\n');
        // separator
        for (i, w) in widths.iter().enumerate() {
            out.push_str(&"-".repeat(*w));
            if i + 1 < cols {
                out.push_str("  ");
            }
        }
        out.push('\n');
        // rows
        for r in &self.rows {
            for (i, c) in r.iter().enumerate() {
                out.push_str(&pad_display(c, c, widths[i]));
                if i + 1 < cols {
                    out.push_str("  ");
                }
            }
            out.push('\n');
        }
        out
    }
    pub fn print(&self) {
        if is_quiet() {
            return;
        }
        print!("{}", self.render());
    }
}

// Left-pad `styled` (which may contain ANSI codes) to `target` display columns,
// measured by the plain text's character count. This keeps columns aligned even
// when the visible text is styled or contains multi-byte characters. Note: it
// counts Unicode scalar values, not grapheme/wcwidth cells, so full-width CJK or
// combining marks can still misalign; adequate for typical CLI table content.
fn pad_display(styled: &str, plain: &str, target: usize) -> String {
    let visible = plain.chars().count();
    let pad = target.saturating_sub(visible);
    format!("{}{}", styled, " ".repeat(pad))
}

/// A minimal progress bar for loops. Renders to stderr, only if stderr is a tty
/// and we are not quiet; otherwise it is a no-op so pipes stay clean.
pub struct Progress {
    total: u64,
    current: u64,
    label: String,
    active: bool,
    width: usize,
}

impl Progress {
    pub fn new(total: u64, label: &str) -> Self {
        let active = !is_quiet() && s::is_stderr_tty();
        let width = crate::theme::active().progress_width;
        Progress {
            total,
            current: 0,
            label: label.to_string(),
            active,
            width,
        }
    }
    pub fn inc(&mut self, by: u64) {
        self.current = (self.current + by).min(self.total);
        self.draw();
    }
    pub fn set(&mut self, value: u64) {
        self.current = value.min(self.total);
        self.draw();
    }
    fn draw(&self) {
        if !self.active {
            return;
        }
        let t = crate::theme::active();
        let frac = if self.total == 0 {
            1.0
        } else {
            self.current as f64 / self.total as f64
        };
        let filled = (frac * self.width as f64).round() as usize;
        let bar = format!(
            "{}{}",
            t.progress_fill.repeat(filled),
            t.progress_empty.repeat(self.width - filled)
        );
        eprint!(
            "\r{} [{}] {}/{}",
            self.label,
            t.color_accent.paint(&bar),
            self.current,
            self.total
        );
        let _ = std::io::stderr().flush();
    }
    pub fn finish(&self, msg: &str) {
        if !self.active {
            return;
        }
        let t = crate::theme::active();
        eprint!("\r{}\r", " ".repeat(self.label.len() + self.width + 20));
        if t.success_glyph.is_empty() {
            eprintln!("{}", msg);
        } else {
            eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
        }
    }
}

// ---------- spinner, timer, tree, key/value ----------

/// An indeterminate spinner for work of unknown length. Like `Progress`, it is
/// a no-op unless stderr is a tty and not quiet, so pipes stay clean. Call
/// `tick` periodically; call `finish` when done.
pub struct Spinner {
    frames: Vec<char>,
    idx: usize,
    label: String,
    active: bool,
}

impl Spinner {
    pub fn new(label: &str) -> Self {
        Spinner {
            frames: vec!['|', '/', '-', '\\'],
            idx: 0,
            label: label.to_string(),
            active: !is_quiet() && s::is_stderr_tty(),
        }
    }
    pub fn tick(&mut self) {
        if !self.active {
            return;
        }
        let f = self.frames[self.idx % self.frames.len()];
        self.idx += 1;
        eprint!("\r{} {}", crate::theme::active().color_accent.paint(f.to_string()), self.label);
        let _ = std::io::stderr().flush();
    }
    pub fn finish(&self, msg: &str) {
        if !self.active {
            return;
        }
        eprint!("\r{}\r", " ".repeat(self.label.len() + 4));
        let t = crate::theme::active();
        if t.success_glyph.is_empty() {
            eprintln!("{}", msg);
        } else {
            eprintln!("{} {}", t.color_success.paint(&t.success_glyph), msg);
        }
    }
}

/// A scoped stopwatch. [`Timer::elapsed_ms`] returns raw milliseconds and
/// [`Timer::human`] a friendly string, for "how long did this take" reporting.
pub struct Timer {
    start: std::time::Instant,
}

impl Timer {
    pub fn start() -> Self {
        Timer {
            start: std::time::Instant::now(),
        }
    }
    pub fn elapsed_ms(&self) -> u128 {
        self.start.elapsed().as_millis()
    }
    /// A human-friendly elapsed string: `920ms`, `1.5s`, `2m 3s`.
    pub fn human(&self) -> String {
        let ms = self.elapsed_ms();
        if ms < 1000 {
            format!("{}ms", ms)
        } else if ms < 60_000 {
            format!("{:.1}s", ms as f64 / 1000.0)
        } else {
            let s = ms / 1000;
            format!("{}m {}s", s / 60, s % 60)
        }
    }
}

/// Print an aligned key/value block (suppressed when quiet). Keys are dimmed and
/// right-padded to align values.
pub fn kv(pairs: &[(&str, &str)]) {
    if is_quiet() {
        return;
    }
    let w = pairs.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
    for (k, v) in pairs {
        println!("{}  {}", pad_display(&s::dim(k), k, w), v);
    }
}

/// A simple tree node for rendering hierarchical output.
pub struct Tree {
    pub label: String,
    pub children: Vec<Tree>,
}

impl Tree {
    pub fn new<S: Into<String>>(label: S) -> Self {
        Tree {
            label: label.into(),
            children: Vec::new(),
        }
    }
    pub fn child(mut self, node: Tree) -> Self {
        self.children.push(node);
        self
    }
    pub fn push(&mut self, node: Tree) -> &mut Self {
        self.children.push(node);
        self
    }
    /// Render the tree with box-drawing connectors.
    pub fn render(&self) -> String {
        let mut out = String::new();
        out.push_str(&self.label);
        out.push('\n');
        self.render_children(&mut out, "");
        out
    }
    fn render_children(&self, out: &mut String, prefix: &str) {
        let n = self.children.len();
        for (i, child) in self.children.iter().enumerate() {
            let last = i + 1 == n;
            let (branch, cont) = if last {
                ("└── ", "    ")
            } else {
                ("├── ", "│   ")
            };
            out.push_str(prefix);
            out.push_str(branch);
            out.push_str(&child.label);
            out.push('\n');
            child.render_children(out, &format!("{}{}", prefix, cont));
        }
    }
    pub fn print(&self) {
        if is_quiet() {
            return;
        }
        print!("{}", self.render());
    }
}