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
//! ANSI styling — a `Color` enum plus attribute wrappers.
//!
//! Colors are disabled automatically when output is not a terminal, when
//! `NO_COLOR` is set (https://no-color.org/), when `TERM=dumb`, or when the app
//! is in `--quiet`/JSON mode. Callers use [`Color::paint`] or the convenience
//! wrappers and never emit escape codes into pipes or files.

use std::sync::atomic::{AtomicBool, Ordering};

static COLOR_ENABLED: AtomicBool = AtomicBool::new(true);

/// Globally enable or disable color output.
pub fn set_enabled(on: bool) {
    COLOR_ENABLED.store(on, Ordering::Relaxed);
}
/// Whether color is currently enabled.
pub fn enabled() -> bool {
    COLOR_ENABLED.load(Ordering::Relaxed)
}

/// A semantic/basic color. `paint` applies it, honoring the global enable flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    Gray,
    /// No color; `paint` returns the text unchanged.
    None,
}

impl Color {
    fn code(self) -> Option<&'static str> {
        Some(match self {
            Color::Red => "31",
            Color::Green => "32",
            Color::Yellow => "33",
            Color::Blue => "34",
            Color::Magenta => "35",
            Color::Cyan => "36",
            Color::Gray => "90",
            Color::None => return None,
        })
    }
    /// Apply this color to `s`, or return `s` unchanged if color is off or None.
    pub fn paint<S: AsRef<str>>(self, s: S) -> String {
        match (enabled(), self.code()) {
            (true, Some(c)) => format!("\x1b[{}m{}\x1b[0m", c, s.as_ref()),
            _ => s.as_ref().to_string(),
        }
    }
}

/// Decide a sensible default for color from the environment (not counting
/// `--quiet` or piped stdout; the app layer combines this with those).
pub fn env_default() -> bool {
    if std::env::var_os("NO_COLOR").is_some() {
        return false;
    }
    if let Some(term) = std::env::var_os("TERM") {
        if term == "dumb" {
            return false;
        }
    }
    is_stdout_tty()
}

pub fn is_stdout_tty() -> bool {
    is_tty(1)
}
pub fn is_stderr_tty() -> bool {
    is_tty(2)
}

#[cfg(unix)]
fn is_tty(fd: i32) -> bool {
    extern "C" {
        fn isatty(fd: i32) -> i32;
    }
    unsafe { isatty(fd) == 1 }
}
#[cfg(not(unix))]
fn is_tty(_fd: i32) -> bool {
    true
}

macro_rules! attr {
    ($name:ident, $open:expr) => {
        /// Wrap `s` in the ANSI attribute, or return it unchanged when color is off.
        pub fn $name<S: AsRef<str>>(s: S) -> String {
            if enabled() {
                format!("\x1b[{}m{}\x1b[0m", $open, s.as_ref())
            } else {
                s.as_ref().to_string()
            }
        }
    };
}

attr!(bold, "1");
attr!(dim, "2");
attr!(italic, "3");
attr!(underline, "4");

// Convenience color wrappers (thin shims over Color::paint).
pub fn red<S: AsRef<str>>(s: S) -> String { Color::Red.paint(s) }
pub fn green<S: AsRef<str>>(s: S) -> String { Color::Green.paint(s) }
pub fn yellow<S: AsRef<str>>(s: S) -> String { Color::Yellow.paint(s) }
pub fn blue<S: AsRef<str>>(s: S) -> String { Color::Blue.paint(s) }
pub fn magenta<S: AsRef<str>>(s: S) -> String { Color::Magenta.paint(s) }
pub fn cyan<S: AsRef<str>>(s: S) -> String { Color::Cyan.paint(s) }
pub fn gray<S: AsRef<str>>(s: S) -> String { Color::Gray.paint(s) }

/// Bold + the active theme's heading color.
pub fn heading<S: AsRef<str>>(s: S) -> String {
    let c = crate::theme::active().color_heading;
    bold(c.paint(s))
}