Skip to main content

cornerstone/
style.rs

1//! ANSI styling — a `Color` enum plus attribute wrappers.
2//!
3//! Colors are disabled automatically when output is not a terminal, when
4//! `NO_COLOR` is set (https://no-color.org/), when `TERM=dumb`, or when the app
5//! is in `--quiet`/JSON mode. Callers use [`Color::paint`] or the convenience
6//! wrappers and never emit escape codes into pipes or files.
7
8use std::sync::atomic::{AtomicBool, Ordering};
9
10static COLOR_ENABLED: AtomicBool = AtomicBool::new(true);
11
12/// Globally enable or disable color output.
13pub fn set_enabled(on: bool) {
14    COLOR_ENABLED.store(on, Ordering::Relaxed);
15}
16/// Whether color is currently enabled.
17pub fn enabled() -> bool {
18    COLOR_ENABLED.load(Ordering::Relaxed)
19}
20
21/// A semantic/basic color. `paint` applies it, honoring the global enable flag.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum Color {
24    Red,
25    Green,
26    Yellow,
27    Blue,
28    Magenta,
29    Cyan,
30    Gray,
31    /// No color; `paint` returns the text unchanged.
32    None,
33}
34
35impl Color {
36    fn code(self) -> Option<&'static str> {
37        Some(match self {
38            Color::Red => "31",
39            Color::Green => "32",
40            Color::Yellow => "33",
41            Color::Blue => "34",
42            Color::Magenta => "35",
43            Color::Cyan => "36",
44            Color::Gray => "90",
45            Color::None => return None,
46        })
47    }
48    /// Apply this color to `s`, or return `s` unchanged if color is off or None.
49    pub fn paint<S: AsRef<str>>(self, s: S) -> String {
50        match (enabled(), self.code()) {
51            (true, Some(c)) => format!("\x1b[{}m{}\x1b[0m", c, s.as_ref()),
52            _ => s.as_ref().to_string(),
53        }
54    }
55}
56
57/// Decide a sensible default for color from the environment (not counting
58/// `--quiet` or piped stdout; the app layer combines this with those).
59pub fn env_default() -> bool {
60    if std::env::var_os("NO_COLOR").is_some() {
61        return false;
62    }
63    if let Some(term) = std::env::var_os("TERM") {
64        if term == "dumb" {
65            return false;
66        }
67    }
68    is_stdout_tty()
69}
70
71pub fn is_stdout_tty() -> bool {
72    is_tty(1)
73}
74pub fn is_stderr_tty() -> bool {
75    is_tty(2)
76}
77
78#[cfg(unix)]
79fn is_tty(fd: i32) -> bool {
80    extern "C" {
81        fn isatty(fd: i32) -> i32;
82    }
83    unsafe { isatty(fd) == 1 }
84}
85#[cfg(not(unix))]
86fn is_tty(_fd: i32) -> bool {
87    true
88}
89
90macro_rules! attr {
91    ($name:ident, $open:expr) => {
92        /// Wrap `s` in the ANSI attribute, or return it unchanged when color is off.
93        pub fn $name<S: AsRef<str>>(s: S) -> String {
94            if enabled() {
95                format!("\x1b[{}m{}\x1b[0m", $open, s.as_ref())
96            } else {
97                s.as_ref().to_string()
98            }
99        }
100    };
101}
102
103attr!(bold, "1");
104attr!(dim, "2");
105attr!(italic, "3");
106attr!(underline, "4");
107
108// Convenience color wrappers (thin shims over Color::paint).
109pub fn red<S: AsRef<str>>(s: S) -> String { Color::Red.paint(s) }
110pub fn green<S: AsRef<str>>(s: S) -> String { Color::Green.paint(s) }
111pub fn yellow<S: AsRef<str>>(s: S) -> String { Color::Yellow.paint(s) }
112pub fn blue<S: AsRef<str>>(s: S) -> String { Color::Blue.paint(s) }
113pub fn magenta<S: AsRef<str>>(s: S) -> String { Color::Magenta.paint(s) }
114pub fn cyan<S: AsRef<str>>(s: S) -> String { Color::Cyan.paint(s) }
115pub fn gray<S: AsRef<str>>(s: S) -> String { Color::Gray.paint(s) }
116
117/// Bold + the active theme's heading color.
118pub fn heading<S: AsRef<str>>(s: S) -> String {
119    let c = crate::theme::active().color_heading;
120    bold(c.paint(s))
121}