clicolors_control/
common.rs

1use std::env;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4#[cfg(unix)]
5pub use unix::*;
6#[cfg(windows)]
7pub use windows::*;
8
9#[cfg(all(not(unix), not(windows)))]
10pub use generic::*;
11
12/// Returns the default value for `colors_enabled`.
13pub fn enable_colors_by_default() -> bool {
14    (is_a_color_terminal() && &env::var("CLICOLOR").unwrap_or("1".into()) != "0")
15        || &env::var("CLICOLOR_FORCE").unwrap_or("0".into()) != "0"
16}
17
18lazy_static! {
19    static ref ENABLE_COLORS: AtomicBool = AtomicBool::new(enable_colors_by_default());
20}
21
22/// Returns `true` if colors should be enabled.
23///
24/// This honors the [clicolors spec](http://bixense.com/clicolors/).
25///
26/// * `CLICOLOR != 0`: ANSI colors are supported and should be used when the program isn't piped.
27/// * `CLICOLOR == 0`: Don't output ANSI color escape codes.
28/// * `CLICOLOR_FORCE != 0`: ANSI colors should be enabled no matter what.
29pub fn colors_enabled() -> bool {
30    ENABLE_COLORS.load(Ordering::Relaxed)
31}
32
33/// Forces colorization on or off.
34///
35/// This overrides the default for the current process and changes the return value of the
36/// `colors_enabled` function.
37pub fn set_colors_enabled(val: bool) {
38    ENABLE_COLORS.store(val, Ordering::Relaxed)
39}
40
41/// Configures the terminal for ANSI color support.
42///
43/// This is not needed on UNIX systems and normally automatically happens on windows
44/// the first time `colors_enabled()` is called.  This automatic behavior however
45/// can be disabled by removing the `terminal_autoconfig` feature flag.
46///
47/// When this function is called and the terminal was reconfigured, changes from
48/// `set_colors_enabled` are reverted.
49///
50/// It returns `true` if the terminal supports colors after configuration or
51/// `false` if not.
52pub fn configure_terminal() -> bool {
53    #[cfg(windows)]
54    {
55        if enable_ansi_mode() {
56            // if the terminal is configured we override the cached colors value
57            // with the default as otherwise we might have a wrong value.
58            set_colors_enabled(enable_colors_by_default());
59            true
60        } else {
61            false
62        }
63    }
64    #[cfg(not(windows))]
65    {
66        true
67    }
68}