Skip to main content

tree_sitter_cli/
paint.rs

1use anstyle::{AnsiColor, Color, Style};
2
3pub const RED: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));
4pub const YELLOW: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));
5
6/// Wraps a `Display` value with a style; emits ANSI codes only when
7/// [`color_enabled`] is true.
8pub struct Paint<T>(pub Style, pub T);
9
10pub fn color_enabled() -> bool {
11    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
12    *ENABLED.get_or_init(|| std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty()))
13}
14
15pub fn paint<T>(color: Option<impl Into<Color>>, text: T) -> Paint<T> {
16    Paint(Style::new().fg_color(color.map(Into::into)), text)
17}
18
19impl<T: std::fmt::Display> std::fmt::Display for Paint<T> {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        if color_enabled() {
22            write!(f, "{}{}{:#}", self.0, self.1, self.0)
23        } else {
24            self.1.fmt(f)
25        }
26    }
27}