Skip to main content

midenc_session/
color.rs

1use alloc::string::ToString;
2use core::str::FromStr;
3
4/// ColorChoice represents the color preferences of an end user.
5///
6/// The `Default` implementation for this type will select `Auto`, which tries
7/// to do the right thing based on the current environment.
8///
9/// The `FromStr` implementation for this type converts a lowercase kebab-case
10/// string of the variant name to the corresponding variant. Any other string
11/// results in an error.
12#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
13#[cfg_attr(feature = "std", derive(clap::ValueEnum))]
14pub enum ColorChoice {
15    /// Try very hard to emit colors. This includes emitting ANSI colors
16    /// on Windows if the console API is unavailable.
17    Always,
18    /// AlwaysAnsi is like Always, except it never tries to use anything other
19    /// than emitting ANSI color codes.
20    AlwaysAnsi,
21    /// Try to use colors, but don't force the issue. If the console isn't
22    /// available on Windows, or if TERM=dumb, or if `NO_COLOR` is defined, for
23    /// example, then don't use colors.
24    #[default]
25    Auto,
26    /// Never emit colors.
27    Never,
28}
29
30#[cfg(feature = "std")]
31impl From<ColorChoice> for termcolor::ColorChoice {
32    fn from(choice: ColorChoice) -> Self {
33        match choice {
34            ColorChoice::Always => Self::Always,
35            ColorChoice::AlwaysAnsi => Self::AlwaysAnsi,
36            ColorChoice::Auto => Self::Auto,
37            ColorChoice::Never => Self::Never,
38        }
39    }
40}
41
42#[derive(Debug, thiserror::Error)]
43#[error("invalid color choice: {0}")]
44pub struct ColorChoiceParseError(alloc::borrow::Cow<'static, str>);
45
46impl FromStr for ColorChoice {
47    type Err = ColorChoiceParseError;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        match s.to_lowercase().as_str() {
51            "always" => Ok(ColorChoice::Always),
52            "always-ansi" => Ok(ColorChoice::AlwaysAnsi),
53            "never" => Ok(ColorChoice::Never),
54            "auto" => Ok(ColorChoice::Auto),
55            unknown => Err(ColorChoiceParseError(unknown.to_string().into())),
56        }
57    }
58}
59
60impl ColorChoice {
61    /// Returns true if we should attempt to write colored output.
62    pub fn should_attempt_color(&self) -> bool {
63        match *self {
64            ColorChoice::Always => true,
65            ColorChoice::AlwaysAnsi => true,
66            ColorChoice::Never => false,
67            #[cfg(feature = "std")]
68            ColorChoice::Auto => self.env_allows_color(),
69            #[cfg(not(feature = "std"))]
70            ColorChoice::Auto => false,
71        }
72    }
73
74    #[cfg(all(feature = "std", not(windows)))]
75    pub fn env_allows_color(&self) -> bool {
76        match std::env::var_os("TERM") {
77            // If TERM isn't set, then we are in a weird environment that
78            // probably doesn't support colors.
79            None => return false,
80            Some(k) => {
81                if k == "dumb" {
82                    return false;
83                }
84            }
85        }
86        // If TERM != dumb, then the only way we don't allow colors at this
87        // point is if NO_COLOR is set.
88        std::env::var_os("NO_COLOR").is_none()
89    }
90
91    #[cfg(all(feature = "std", windows))]
92    pub fn env_allows_color(&self) -> bool {
93        // On Windows, if TERM isn't set, then we shouldn't automatically
94        // assume that colors aren't allowed. This is unlike Unix environments
95        // where TERM is more rigorously set.
96        if let Some(k) = std::env::var_os("TERM") {
97            if k == "dumb" {
98                return false;
99            }
100        }
101        // If TERM != dumb, then the only way we don't allow colors at this
102        // point is if NO_COLOR is set.
103        std::env::var_os("NO_COLOR").is_none()
104    }
105
106    /// Returns true if this choice should forcefully use ANSI color codes.
107    ///
108    /// It's possible that ANSI is still the correct choice even if this
109    /// returns false.
110    #[cfg(all(feature = "std", windows))]
111    pub fn should_ansi(&self) -> bool {
112        match *self {
113            ColorChoice::Always => false,
114            ColorChoice::AlwaysAnsi => true,
115            ColorChoice::Never => false,
116            ColorChoice::Auto => {
117                match std::env::var("TERM") {
118                    Err(_) => false,
119                    // cygwin doesn't seem to support ANSI escape sequences
120                    // and instead has its own variety. However, the Windows
121                    // console API may be available.
122                    Ok(k) => k != "dumb" && k != "cygwin",
123                }
124            }
125        }
126    }
127
128    /// Returns true if this choice should forcefully use ANSI color codes.
129    ///
130    /// It's possible that ANSI is still the correct choice even if this
131    /// returns false.
132    #[cfg(not(feature = "std"))]
133    pub fn should_ansi(&self) -> bool {
134        match *self {
135            ColorChoice::Always => false,
136            ColorChoice::AlwaysAnsi => true,
137            ColorChoice::Never => false,
138            ColorChoice::Auto => false,
139        }
140    }
141}