Skip to main content

mago_reporting/
color.rs

1/// Choice for colorizing output.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
3pub enum ColorChoice {
4    /// Automatically detect whether colors should be used based on TTY detection.
5    #[default]
6    Auto,
7    /// Always use colors, regardless of TTY status.
8    Always,
9    /// Never use colors.
10    Never,
11}
12
13impl ColorChoice {
14    /// Determine if colors should be used based on this choice and whether output is a TTY.
15    ///
16    /// # Arguments
17    ///
18    /// * `is_tty` - Whether the output stream is connected to a terminal
19    ///
20    /// # Returns
21    ///
22    /// `true` if colors should be used, `false` otherwise
23    #[must_use]
24    pub fn should_use_colors(self, is_tty: bool) -> bool {
25        // FORCE_COLOR takes precedence (https://force-color.org/).
26        // Any non-empty value forces colors, except "0" which explicitly disables them.
27        if let Some(value) = std::env::var_os("FORCE_COLOR")
28            && !value.is_empty()
29        {
30            return value != "0";
31        }
32
33        // NO_COLOR (https://no-color.org/): when set to any non-empty value,
34        // colors must be suppressed. An empty value has no effect.
35        if std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()) {
36            return false;
37        }
38
39        match self {
40            ColorChoice::Auto => is_tty,
41            ColorChoice::Always => true,
42            ColorChoice::Never => false,
43        }
44    }
45}