mi6_cli/display/
colors.rs

1//! Color formatting helpers for terminal output.
2
3use termion::color;
4use termion::style;
5
6use super::terminal::{use_colors, use_colors_stderr};
7
8/// Format text as bold green.
9pub fn bold_green(text: &str) -> String {
10    if use_colors() {
11        format!(
12            "{}{}{}{}",
13            style::Bold,
14            color::Fg(color::Green),
15            text,
16            style::Reset
17        )
18    } else {
19        text.to_string()
20    }
21}
22
23/// Format text as bold red.
24pub fn bold_red(text: &str) -> String {
25    if use_colors() {
26        format!(
27            "{}{}{}{}",
28            style::Bold,
29            color::Fg(color::Red),
30            text,
31            style::Reset
32        )
33    } else {
34        text.to_string()
35    }
36}
37
38/// Format text as bold white.
39pub fn bold_white(text: &str) -> String {
40    if use_colors() {
41        format!(
42            "{}{}{}{}",
43            style::Bold,
44            color::Fg(color::White),
45            text,
46            style::Reset
47        )
48    } else {
49        text.to_string()
50    }
51}
52
53/// Format text as dark grey (for hints).
54pub fn dark_grey(text: &str) -> String {
55    if use_colors() {
56        format!(
57            "{}{}{}",
58            color::Fg(color::Rgb(128, 128, 128)),
59            text,
60            style::Reset
61        )
62    } else {
63        text.to_string()
64    }
65}
66
67/// ANSI color codes for terminal output to stderr.
68///
69/// This struct provides a set of ANSI escape codes that are automatically
70/// disabled when stderr is not a terminal or when the `NO_COLOR` environment
71/// variable is set.
72pub struct StderrColors {
73    pub reset: &'static str,
74    pub bold: &'static str,
75    pub green: &'static str,
76    pub cyan: &'static str,
77    pub yellow: &'static str,
78}
79
80impl StderrColors {
81    /// Create a new `StderrColors` instance.
82    ///
83    /// If stderr is not a terminal or `NO_COLOR` is set, all color codes
84    /// will be empty strings.
85    pub fn new() -> Self {
86        if use_colors_stderr() {
87            Self {
88                reset: "\x1b[0m",
89                bold: "\x1b[1m",
90                green: "\x1b[32m",
91                cyan: "\x1b[36m",
92                yellow: "\x1b[33m",
93            }
94        } else {
95            Self {
96                reset: "",
97                bold: "",
98                green: "",
99                cyan: "",
100                yellow: "",
101            }
102        }
103    }
104}
105
106impl Default for StderrColors {
107    fn default() -> Self {
108        Self::new()
109    }
110}