Skip to main content

pcf_debug/render/
color.rs

1//! Minimal ANSI colouring with no external crate.
2//!
3//! When colour is disabled (`--no-color`, the `NO_COLOR` env var, or a
4//! non-terminal stdout) every helper returns the text unchanged, so callers can
5//! colour unconditionally and let the [`Palette`] decide.
6
7/// A colour policy: either emits ANSI SGR codes or is the identity.
8#[derive(Debug, Clone, Copy)]
9pub struct Palette {
10    enabled: bool,
11}
12
13impl Palette {
14    pub fn new(enabled: bool) -> Self {
15        Self { enabled }
16    }
17
18    fn wrap(self, code: &str, s: &str) -> String {
19        if self.enabled {
20            format!("\x1b[{code}m{s}\x1b[0m")
21        } else {
22            s.to_string()
23        }
24    }
25
26    pub fn bold(self, s: &str) -> String {
27        self.wrap("1", s)
28    }
29    pub fn dim(self, s: &str) -> String {
30        self.wrap("2", s)
31    }
32    pub fn red(self, s: &str) -> String {
33        self.wrap("31", s)
34    }
35    pub fn green(self, s: &str) -> String {
36        self.wrap("32", s)
37    }
38    pub fn yellow(self, s: &str) -> String {
39        self.wrap("33", s)
40    }
41    pub fn blue(self, s: &str) -> String {
42        self.wrap("34", s)
43    }
44    pub fn magenta(self, s: &str) -> String {
45        self.wrap("35", s)
46    }
47    pub fn cyan(self, s: &str) -> String {
48        self.wrap("36", s)
49    }
50}