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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*!
Determine whether output should use colors or not.

The resulting color choice is determined by taking into account,
in order of priority from higher to lower, the following settings:

- [`CLICOLOR_FORCE`](#clicolor_force) environment variable (requires `clicolor_force` feature),
- explicit user preference (for instance command line arguments),
- [`CLICOLOR`](#clicolor) environment variable (requires `clicolor` feature),
- [`NO_COLOR`](#no_color) environment variable (requires `no_color` feature),
- application default choice.

The specification of `CLICOLOR`, `CLICOLOR_FORCE`, and `NO_COLOR` is inspired by:

- <https://bixense.com/clicolors/>,
- <https://no-color.org>,

with the exception that variables which are set to the empty string `""`
are treated as if they were unset.
The reason is that it is common to override environment variables by executing programs as
`VAR= cmd args...` and expect that `VAR` is unset.

# `CLICOLOR_FORCE`

Requires the <span class="stab portability" title="Available on crate feature `clicolor_force` only"><code>clicolor_force</code></span> feature.

The meaning of the environment variable is the following:

- if not set or `CLICOLOR_FORCE == ""` or `CLICOLOR_FORCE == "0"`: ignore;
- if set and `CLICOLOR_FORCE != ""` and `CLICOLOR_FORCE != "0"`: [`ColorChoice::Always`].

# `CLICOLOR`

Requires the <span class="stab portability" title="Available on crate feature `clicolor` only"><code>clicolor</code></span> feature.

The meaning of the environment variable is the following:

- if not set or `CLICOLOR == ""`: ignore;
- if set and `CLICOLOR == "0"`: [`ColorChoice::Never`];
- if set and `CLICOLOR != ""` and `CLICOLOR != "0"`: [`ColorChoice::Auto`].

# `NO_COLOR`

Requires the <span class="stab portability" title="Available on crate feature `no_color` only"><code>no_color</code></span> feature.

The meaning of the environment variable is the following:

- if not set or `NO_COLOR == ""`: ignore;
- if set and `NO_COLOR != ""`: [`ColorChoice::Never`].

# Compatibility

The goal of this crate is to implement the standards proposed in
<https://no-color.org> and <https://bixense.com/clicolors/>.

Please note that the proposals in the latter are slightly ambiguous and undesirable
(see [this issue](https://github.com/jhasse/clicolors/issues/8)),
hence they are merely taken as an inspiration and not followed too strictly.

Relevant quote from <https://no-color.org>:

> Command-line software which adds ANSI color to its output by default should
  check for a `NO_COLOR` environment variable that, when present and not an
  empty string (regardless of its value), prevents the addition of ANSI color.

Relevant quote from <https://bixense.com/clicolors/>:

> The idea is to have the environment variables `CLICOLOR` and `CLICOLOR_FORCE`
> (which are currently already used for this exact reason on some UNIX systems).
> When set, the following rules should apply:
> - `CLICOLOR != 0`: ANSI colors are supported and should be used when the program isn’t piped,
> - `CLICOLOR == 0`: don’t output ANSI color escape codes,
> - `CLICOLOR_FORCE != 0`: ANSI colors should be enabled no matter what.
*/

#![deny(missing_docs, missing_debug_implementations, warnings)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

/// Name of the `NO_COLOR` environment variable.
#[cfg(feature = "no_color")]
pub const NO_COLOR: &str = "NO_COLOR";
/// Name of the `CLICOLOR` environment variable.
#[cfg(feature = "clicolor")]
pub const CLICOLOR: &str = "CLICOLOR";
/// Name of the `CLICOLOR_FORCE` environment variable.
#[cfg(feature = "clicolor_force")]
pub const CLICOLOR_FORCE: &str = "CLICOLOR_FORCE";

/**
Possible color choices for the output.
*/
#[cfg_attr(
    feature = "clap",
    doc = r#"

# Clap interoperability

If the <span class="stab portability" title="Available on crate feature `clap` only"><code>clap</code></span> feature is enabled then
[`ColorChoice`] can be converted to and from [`clap::ColorChoice`](https://docs.rs/clap/latest/clap/enum.ColorChoice.html).
Moreover it implements [`clap::ValueEnum`](https://docs.rs/clap/latest/clap/trait.ValueEnum.html), hence can be used as

```rust
#[derive(clap::Parser)]
struct Cli {
    /// Coloring of the output
    #[clap(long, value_name = "WHEN", arg_enum, global = true)]
    color: Option<should_color::ColorChoice>,

    // Other arguments...
}
```
"#
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum ColorChoice {
    /// The output will not be colorized.
    Never,
    /// The output will be colorized if the output device is a tty,
    /// i.e. when the output goes directly to a text screen or terminal emulator window.
    Auto,
    /// The output will be colorized.
    Always,
}

// #[cfg(feature = "clap")]
// /// Alias for [`clap::ColorChoice`](https://docs.rs/clap/latest/clap/enum.ColorChoice.html).
// pub type ClapColorChoice = clap::ColorChoice;

#[cfg(feature = "clap")]
impl From<ColorChoice> for clap::ColorChoice {
    fn from(color_choice: ColorChoice) -> clap::ColorChoice {
        match color_choice {
            ColorChoice::Never => clap::ColorChoice::Never,
            ColorChoice::Auto => clap::ColorChoice::Auto,
            ColorChoice::Always => clap::ColorChoice::Always,
        }
    }
}

#[cfg(feature = "clap")]
impl From<clap::ColorChoice> for ColorChoice {
    fn from(color_choice: clap::ColorChoice) -> ColorChoice {
        match color_choice {
            clap::ColorChoice::Never => ColorChoice::Never,
            clap::ColorChoice::Auto => ColorChoice::Auto,
            clap::ColorChoice::Always => ColorChoice::Always,
        }
    }
}

/**
Compute a [`clap::ColorChoice`](https://docs.rs/clap/latest/clap/enum.ColorChoice.html)
suitable for the [`clap::App::color`](https://docs.rs/clap/latest/clap/builder/struct.App.html#method.color) setting.

This is a convenience function equivalent to [`resolve`] without an explicit CLI preference
and a default value of [`clap::ColorChoice::Auto`](https://docs.rs/clap/latest/clap/enum.ColorChoice.html#variant.Auto).

```rust
#[derive(clap::Parser)]
#[clap(color = should_color::clap_color())]
struct Cli {
    // Arguments...
}
```
*/
#[cfg(feature = "clap")]
pub fn clap_color() -> clap::ColorChoice {
    resolve(None).unwrap_or(ColorChoice::Auto).into()
}

/**
Get the setting of the `NO_COLOR` environment variable.

The environment variable is treated as follows:

- if not set or `NO_COLOR == ""`: return `None`;
- if set and `NO_COLOR != ""`: return `Some(`[`ColorChoice::Never`]`)`.
*/
#[cfg(feature = "no_color")]
pub fn no_color() -> Option<ColorChoice> {
    match std::env::var_os(NO_COLOR) {
        Some(s) if !s.is_empty() => Some(ColorChoice::Never),
        _ => None,
    }
}

/**
Get the setting of the `CLICOLOR` environment variable.

The environment variable is treated as follows:

- if not set or `CLICOLOR == ""`: return `None`;
- if set and `CLICOLOR == "0"`: return `Some(`[`ColorChoice::Never`]`)`;
- if set and `CLICOLOR != ""` and `CLICOLOR != "0"`: return `Some(`[`ColorChoice::Auto`]`)`.
*/
#[cfg(feature = "clicolor")]
pub fn clicolor() -> Option<ColorChoice> {
    match std::env::var_os(CLICOLOR) {
        Some(s) if s == "0" => Some(ColorChoice::Never),
        Some(s) if !s.is_empty() => Some(ColorChoice::Auto),
        _ => None,
    }
}

/**
Get the setting of the `CLICOLOR_FORCE` environment variable.

The environment variable is treated as follows:

- if not set or `CLICOLOR_FORCE == ""` or `CLICOLOR_FORCE == "0"`: return `None`;
- if set and `CLICOLOR_FORCE != ""` and `CLICOLOR_FORCE != "0"`: return `Some`[`ColorChoice::Always`]`)`.
*/
#[cfg(feature = "clicolor_force")]
pub fn clicolor_force() -> Option<ColorChoice> {
    match std::env::var_os(CLICOLOR_FORCE) {
        Some(s) if !s.is_empty() && s != "0" => Some(ColorChoice::Always),
        _ => None,
    }
}

/**
Resolve the output color choice from the environment variables and an explicit CLI preference.

Commonly this function will be called as `resolve(cli).unwrap_or(default)` to take into account
a preference expressed through the CLI arguments and the default behavior of the application.

# Examples

The following examples assume that all the features
<span class="stab portability" title="Available on crate feature `clicolor` only"><code>clicolor</code></span>,
<span class="stab portability" title="Available on crate feature `clicolor_force` only"><code>clicolor_force</code></span>, and
<span class="stab portability" title="Available on crate feature `no_color` only"><code>no_color</code></span>
are enabled.

- ```
  # use should_color::{resolve, ColorChoice};
  std::env::set_var("CLICOLOR_FORCE", "false"); // this wins
  # #[cfg(all(feature = "clicolor_force"))]
  assert_eq!(resolve(Some(ColorChoice::Never)), Some(ColorChoice::Always));
  ```

- ```
  # use should_color::{resolve, ColorChoice};
  std::env::remove_var("CLICOLOR_FORCE");
  std::env::set_var("CLICOLOR", "1"); // this wins
  # #[cfg(all(feature = "clicolor"))]
  assert_eq!(resolve(None), Some(ColorChoice::Auto));
  # #[cfg(not(feature = "clicolor"))]
  # assert_eq!(resolve(None), None);
  ```

- ```
  # use should_color::{resolve, ColorChoice};
  std::env::remove_var("CLICOLOR_FORCE");
  std::env::set_var("CLICOLOR", "0"); // this wins
  # #[cfg(all(feature = "clicolor"))]
  assert_eq!(resolve(None), Some(ColorChoice::Never));
  # #[cfg(not(feature = "clicolor"))]
  # assert_eq!(resolve(None), None);
  ```

- ```
  # use should_color::{resolve, ColorChoice};
  std::env::remove_var("CLICOLOR_FORCE");
  std::env::remove_var("CLICOLOR");
  std::env::set_var("NO_COLOR", "1"); // this wins
  # #[cfg(feature = "no_color")]
  assert_eq!(resolve(None), Some(ColorChoice::Never));
  # #[cfg(not(feature = "no_color"))]
  # assert_eq!(resolve(None), None);
  ```

- ```
  # use should_color::{resolve, ColorChoice};
  std::env::remove_var("CLICOLOR_FORCE");
  std::env::remove_var("CLICOLOR");
  std::env::remove_var("NO_COLOR");
  assert_eq!(resolve(None), None);
  ```
*/
pub fn resolve(cli: Option<ColorChoice>) -> Option<ColorChoice> {
    #[cfg(feature = "clicolor_force")]
    let choice = clicolor_force();

    #[cfg(feature = "clicolor_force")]
    let choice = choice.or(cli);
    #[cfg(not(feature = "clicolor_force"))]
    let choice = cli;

    #[cfg(feature = "clicolor")]
    let choice = choice.or_else(clicolor);

    #[cfg(feature = "no_color")]
    let choice = choice.or_else(no_color);

    choice
}

#[cfg(test)]
mod tests {
    #[test]
    #[cfg(feature = "no_color")]
    fn test_no_color() {
        use super::*;

        std::env::remove_var(NO_COLOR);
        assert_eq!(no_color(), None);

        std::env::set_var(NO_COLOR, "");
        assert_eq!(no_color(), None);

        for s in ["0", "1", "false", "true", "="] {
            std::env::set_var(NO_COLOR, s);
            assert_eq!(no_color(), Some(ColorChoice::Never));
        }
    }

    #[test]
    #[cfg(feature = "clicolor")]
    fn test_clicolor() {
        use super::*;

        std::env::remove_var(CLICOLOR);
        assert_eq!(clicolor(), None);

        std::env::set_var(CLICOLOR, "");
        assert_eq!(clicolor(), None);

        std::env::set_var(CLICOLOR, "0");
        assert_eq!(clicolor(), Some(ColorChoice::Never));

        for s in ["1", "false", "true", "="] {
            std::env::set_var(CLICOLOR, s);
            assert_eq!(clicolor(), Some(ColorChoice::Auto));
        }
    }

    #[test]
    #[cfg(feature = "clicolor_force")]
    fn test_clicolor_force() {
        use super::*;

        std::env::remove_var(CLICOLOR_FORCE);
        assert_eq!(clicolor_force(), None);

        std::env::set_var(CLICOLOR_FORCE, "");
        assert_eq!(clicolor_force(), None);

        std::env::set_var(CLICOLOR_FORCE, "0");
        assert_eq!(clicolor_force(), None);

        for s in ["1", "false", "true", "="] {
            std::env::set_var(CLICOLOR_FORCE, s);
            assert_eq!(clicolor_force(), Some(ColorChoice::Always));
        }
    }
}