Skip to main content

error_forge/
console_theme.rs

1//! Console theming for error display in CLI applications.
2//!
3//! This module provides ANSI color formatting for error messages
4//! displayed in terminal environments. It auto-detects terminal
5//! capabilities via [`std::io::IsTerminal`] and disables colors when
6//! stderr is not a TTY, when `TERM=dumb`, or when `NO_COLOR` is set
7//! to a non-empty value (<https://no-color.org/>).
8
9use std::io::IsTerminal;
10
11/// Color theme for console error output.
12///
13/// The fields are `&'static str` ANSI escapes — no allocation per
14/// construction, and `const`-constructible for the two preset
15/// constructors ([`ConsoleTheme::with_colors`], [`ConsoleTheme::plain`]).
16pub struct ConsoleTheme {
17    error_color: &'static str,
18    warning_color: &'static str,
19    info_color: &'static str,
20    success_color: &'static str,
21    caption_color: &'static str,
22    reset: &'static str,
23    bold: &'static str,
24    dim: &'static str,
25}
26
27/// Detect if the current terminal supports ANSI colors.
28fn terminal_supports_ansi() -> bool {
29    // Cache the answer for the process. The decision is based on
30    // env vars + the `stderr` handle, both of which are effectively
31    // process-static, so caching is correct (and removes per-call
32    // env-var reads from the hot path).
33    static SUPPORTS_ANSI: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
34
35    *SUPPORTS_ANSI.get_or_init(|| {
36        // Stderr must be a terminal — applies to every platform.
37        if !std::io::stderr().is_terminal() {
38            return false;
39        }
40
41        // Explicit terminal-dumb signal.
42        if let Ok(term) = std::env::var("TERM") {
43            if term == "dumb" {
44                return false;
45            }
46        }
47
48        if no_color_requested(std::env::var_os("NO_COLOR").as_deref()) {
49            return false;
50        }
51
52        // Windows Terminal explicitly signals ANSI support.
53        #[cfg(windows)]
54        {
55            if std::env::var_os("WT_SESSION").is_some() {
56                return true;
57            }
58        }
59
60        // Default to enabled on every supported platform — modern
61        // Windows builds (10.0.10586+) honour ANSI escapes in stderr.
62        true
63    })
64}
65
66/// Whether a `NO_COLOR` value asks for colour to be disabled.
67///
68/// Per <https://no-color.org/>, colour is disabled when the variable is
69/// present and not an empty string, regardless of its value. An unset or
70/// empty `NO_COLOR` leaves colour on.
71fn no_color_requested(value: Option<&std::ffi::OsStr>) -> bool {
72    value.is_some_and(|v| !v.is_empty())
73}
74
75impl Default for ConsoleTheme {
76    fn default() -> Self {
77        if terminal_supports_ansi() {
78            Self::with_colors()
79        } else {
80            Self::plain()
81        }
82    }
83}
84
85impl ConsoleTheme {
86    /// Create a new theme with default colors. Auto-detects terminal
87    /// color support; falls back to [`Self::plain`] if stderr is not
88    /// a TTY, `TERM=dumb`, or `NO_COLOR` is set to a non-empty value.
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// Create a new theme with colors forced on, regardless of
94    /// terminal detection.
95    pub const fn with_colors() -> Self {
96        Self {
97            error_color: "\x1b[31m",   // Red
98            warning_color: "\x1b[33m", // Yellow
99            info_color: "\x1b[34m",    // Blue
100            success_color: "\x1b[32m", // Green
101            caption_color: "\x1b[36m", // Cyan
102            reset: "\x1b[0m",
103            bold: "\x1b[1m",
104            dim: "\x1b[2m",
105        }
106    }
107
108    /// Create a new theme with no colors (plain text). Useful for
109    /// piping output to a file or non-TTY consumer.
110    pub const fn plain() -> Self {
111        Self {
112            error_color: "",
113            warning_color: "",
114            info_color: "",
115            success_color: "",
116            caption_color: "",
117            reset: "",
118            bold: "",
119            dim: "",
120        }
121    }
122
123    /// Format an error message with the error color.
124    pub fn error(&self, text: &str) -> String {
125        format!("{}{}{}", self.error_color, text, self.reset)
126    }
127
128    /// Format a warning message with the warning color.
129    pub fn warning(&self, text: &str) -> String {
130        format!("{}{}{}", self.warning_color, text, self.reset)
131    }
132
133    /// Format an info message with the info color.
134    pub fn info(&self, text: &str) -> String {
135        format!("{}{}{}", self.info_color, text, self.reset)
136    }
137
138    /// Format a success message with the success color.
139    pub fn success(&self, text: &str) -> String {
140        format!("{}{}{}", self.success_color, text, self.reset)
141    }
142
143    /// Format a caption with the caption color.
144    pub fn caption(&self, text: &str) -> String {
145        format!("{}{}{}", self.caption_color, text, self.reset)
146    }
147
148    /// Format text as bold.
149    pub fn bold(&self, text: &str) -> String {
150        format!("{}{}{}", self.bold, text, self.reset)
151    }
152
153    /// Format text as dim.
154    pub fn dim(&self, text: &str) -> String {
155        format!("{}{}{}", self.dim, text, self.reset)
156    }
157
158    /// Format an error display in a structured way.
159    ///
160    /// Writes the caption, the error's `Display` output, the
161    /// retryability marker, and the optional source chain into a
162    /// single `String` buffer. Allocates exactly once.
163    pub fn format_error<E: crate::error::ForgeError>(&self, err: &E) -> String {
164        use std::fmt::Write as _;
165        let mut buf = String::with_capacity(160);
166
167        // Caption — written via the helper formatters so the colour
168        // escapes match the rest of the output.
169        let _ = writeln!(buf, "{}", self.caption(&format!("⚠️  {}", err.caption())));
170
171        // Error message.
172        let _ = writeln!(buf, "{}", self.error(&err.to_string()));
173
174        // Retryable status.
175        let marker = if err.is_retryable() {
176            self.success("Yes")
177        } else {
178            self.error("No")
179        };
180        let _ = writeln!(buf, "{}Retryable: {}{}", self.dim, marker, self.reset);
181
182        // Source error if available.
183        if let Some(source) = err.source() {
184            let _ = writeln!(
185                buf,
186                "{}Caused by: {}{}",
187                self.dim,
188                self.error(&source.to_string()),
189                self.reset
190            );
191        }
192
193        buf
194    }
195}
196
197/// Pretty-print an error to stderr with the default theme.
198///
199/// The default theme is cached process-wide via `OnceLock` — the
200/// terminal-capability check runs at most once regardless of how
201/// many errors are printed.
202pub fn print_error<E: crate::error::ForgeError>(err: &E) {
203    static DEFAULT_THEME: std::sync::OnceLock<ConsoleTheme> = std::sync::OnceLock::new();
204    let theme = DEFAULT_THEME.get_or_init(ConsoleTheme::default);
205    eprintln!("{}", theme.format_error(err));
206}
207
208/// Install a panic hook that formats panics using the ConsoleTheme
209pub fn install_panic_hook() {
210    let theme = ConsoleTheme::default();
211    std::panic::set_hook(Box::new(move |panic_info| {
212        let message = match panic_info.payload().downcast_ref::<&str>() {
213            Some(s) => *s,
214            None => match panic_info.payload().downcast_ref::<String>() {
215                Some(s) => s.as_str(),
216                None => "Unknown panic",
217            },
218        };
219
220        let location = if let Some(location) = panic_info.location() {
221            format!("at {}:{}", location.file(), location.line())
222        } else {
223            "at unknown location".to_string()
224        };
225
226        eprintln!("{}", theme.caption("💥 PANIC"));
227        eprintln!(
228            "{}",
229            theme.error(&format!("{} {}", message, theme.dim(&location)))
230        );
231    }));
232}
233
234#[cfg(test)]
235mod tests {
236    use super::no_color_requested;
237    use std::ffi::OsStr;
238
239    #[test]
240    fn test_no_color_follows_spec() {
241        // An empty `NO_COLOR` used to disable colour too, contrary to
242        // no-color.org ("when present and not an empty string").
243        assert!(!no_color_requested(None));
244        assert!(!no_color_requested(Some(OsStr::new(""))));
245        assert!(no_color_requested(Some(OsStr::new("1"))));
246        assert!(no_color_requested(Some(OsStr::new("0"))));
247        assert!(no_color_requested(Some(OsStr::new("false"))));
248    }
249}