nu_protocol/config/
ansi_coloring.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use super::{ConfigErrors, ConfigPath, IntoValue, ShellError, UpdateFromValue, Value};
use crate::{self as nu_protocol, engine::EngineState, FromValue};
use serde::{Deserialize, Serialize};
use std::io::IsTerminal;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, IntoValue, Serialize, Deserialize)]
pub enum UseAnsiColoring {
    #[default]
    Auto,
    True,
    False,
}

impl UseAnsiColoring {
    /// Determines whether ANSI colors should be used.
    ///
    /// This method evaluates the `UseAnsiColoring` setting and considers environment variables
    /// (`FORCE_COLOR`, `NO_COLOR`, and `CLICOLOR`) when the value is set to `Auto`.
    /// The configuration value (`UseAnsiColoring`) takes precedence over environment variables, as
    /// it is more direct and internally may be modified to override ANSI coloring behavior.
    ///
    /// Most users should have the default value `Auto` which allows the environment variables to
    /// control ANSI coloring.
    /// However, when explicitly set to `True` or `False`, the environment variables are ignored.
    ///
    /// Behavior based on `UseAnsiColoring`:
    /// - `True`: Forces ANSI colors to be enabled, ignoring terminal support and environment variables.
    /// - `False`: Disables ANSI colors completely.
    /// - `Auto`: Determines whether ANSI colors should be used based on environment variables and terminal support.
    ///
    /// When set to `Auto`, the following environment variables are checked in order:
    /// 1. `FORCE_COLOR`: If set, ANSI colors are always enabled, overriding all other settings.
    /// 2. `NO_COLOR`: If set, ANSI colors are disabled, overriding `CLICOLOR` and terminal checks.
    /// 3. `CLICOLOR`: If set, its value determines whether ANSI colors are enabled (`1` for enabled, `0` for disabled).
    ///
    /// If none of these variables are set, ANSI coloring is enabled only if the standard output is
    /// a terminal.
    ///
    /// By prioritizing the `UseAnsiColoring` value, we ensure predictable behavior and prevent
    /// conflicts with internal overrides that depend on this configuration.
    pub fn get(self, engine_state: &EngineState) -> bool {
        let is_terminal = match self {
            Self::Auto => std::io::stdout().is_terminal(),
            Self::True => return true,
            Self::False => return false,
        };

        let env_value = |env_name| {
            engine_state
                .get_env_var_insensitive(env_name)
                .map(|(_, v)| v)
                .and_then(|v| v.coerce_bool().ok())
                .unwrap_or(false)
        };

        if env_value("force_color") {
            return true;
        }

        if env_value("no_color") {
            return false;
        }

        if let Some((_, cli_color)) = engine_state.get_env_var_insensitive("clicolor") {
            if let Ok(cli_color) = cli_color.coerce_bool() {
                return cli_color;
            }
        }

        is_terminal
    }
}

impl From<bool> for UseAnsiColoring {
    fn from(value: bool) -> Self {
        match value {
            true => Self::True,
            false => Self::False,
        }
    }
}

impl FromValue for UseAnsiColoring {
    fn from_value(v: Value) -> Result<Self, ShellError> {
        if let Ok(v) = v.as_bool() {
            return Ok(v.into());
        }

        #[derive(FromValue)]
        enum UseAnsiColoringString {
            Auto = 0,
            True = 1,
            False = 2,
        }

        Ok(match UseAnsiColoringString::from_value(v)? {
            UseAnsiColoringString::Auto => Self::Auto,
            UseAnsiColoringString::True => Self::True,
            UseAnsiColoringString::False => Self::False,
        })
    }
}

impl UpdateFromValue for UseAnsiColoring {
    fn update<'a>(
        &mut self,
        value: &'a Value,
        path: &mut ConfigPath<'a>,
        errors: &mut ConfigErrors,
    ) {
        let Ok(value) = UseAnsiColoring::from_value(value.clone()) else {
            errors.type_mismatch(path, UseAnsiColoring::expected_type(), value);
            return;
        };

        *self = value;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nu_protocol::Config;

    fn set_env(engine_state: &mut EngineState, name: &str, value: bool) {
        engine_state.add_env_var(name.to_string(), Value::test_bool(value));
    }

    #[test]
    fn test_use_ansi_coloring_true() {
        let mut engine_state = EngineState::new();
        engine_state.config = Config {
            use_ansi_coloring: UseAnsiColoring::True,
            ..Default::default()
        }
        .into();

        // explicit `True` ignores environment variables
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));

        set_env(&mut engine_state, "clicolor", false);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "clicolor", true);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "no_color", true);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "force_color", true);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
    }

    #[test]
    fn test_use_ansi_coloring_false() {
        let mut engine_state = EngineState::new();
        engine_state.config = Config {
            use_ansi_coloring: UseAnsiColoring::False,
            ..Default::default()
        }
        .into();

        // explicit `False` ignores environment variables
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));

        set_env(&mut engine_state, "clicolor", false);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "clicolor", true);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "no_color", true);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
        set_env(&mut engine_state, "force_color", true);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
    }

    #[test]
    fn test_use_ansi_coloring_auto() {
        let mut engine_state = EngineState::new();
        engine_state.config = Config {
            use_ansi_coloring: UseAnsiColoring::Auto,
            ..Default::default()
        }
        .into();

        // no environment variables, behavior depends on terminal state
        let is_terminal = std::io::stdout().is_terminal();
        assert_eq!(
            engine_state
                .get_config()
                .use_ansi_coloring
                .get(&engine_state),
            is_terminal
        );

        // `clicolor` determines ANSI behavior if no higher-priority variables are set
        set_env(&mut engine_state, "clicolor", true);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));

        set_env(&mut engine_state, "clicolor", false);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));

        // `no_color` overrides `clicolor` and terminal state
        set_env(&mut engine_state, "no_color", true);
        assert!(!engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));

        // `force_color` overrides everything
        set_env(&mut engine_state, "force_color", true);
        assert!(engine_state
            .get_config()
            .use_ansi_coloring
            .get(&engine_state));
    }
}