colors: respect NO_COLOR spec

Microfetch will now respect the NO_COLOR environment variable if it has
been passed to the program. The performance overhead of this operation
is almost none. In addition, the main function has been updated to lock
stdout.
This commit is contained in:
raf 2024-12-19 17:20:46 +03:00
commit 065216af7c
No known key found for this signature in database
GPG key ID: EED98D11B85A2819
5 changed files with 99 additions and 42 deletions

View file

@ -1,11 +1,57 @@
pub const RESET: &str = "\x1b[0m";
pub const BLUE: &str = "\x1b[34m";
pub const CYAN: &str = "\x1b[36m";
pub const GREEN: &str = "\x1b[32m";
pub const YELLOW: &str = "\x1b[33m";
pub const RED: &str = "\x1b[31m";
pub const MAGENTA: &str = "\x1b[35m";
use std::env;
pub struct Colors {
pub reset: &'static str,
pub blue: &'static str,
pub cyan: &'static str,
pub green: &'static str,
pub yellow: &'static str,
pub red: &'static str,
pub magenta: &'static str,
}
impl Colors {
const fn new(is_no_color: bool) -> Self {
match is_no_color {
true => Self {
reset: "",
blue: "",
cyan: "",
green: "",
yellow: "",
red: "",
magenta: "",
},
false => Self {
reset: "\x1b[0m",
blue: "\x1b[34m",
cyan: "\x1b[36m",
green: "\x1b[32m",
yellow: "\x1b[33m",
red: "\x1b[31m",
magenta: "\x1b[35m",
},
}
}
}
lazy_static::lazy_static! {
pub static ref COLORS: Colors = {
// check for NO_COLOR once at startup
let is_no_color = env::var("NO_COLOR").is_ok();
Colors::new(is_no_color)
};
}
pub fn print_dots() -> String {
format!("{BLUE}{CYAN}{GREEN}{YELLOW}{RED}{MAGENTA}{RESET}")
format!(
"{} {} {} {} {} {} {}",
COLORS.blue,
COLORS.cyan,
COLORS.green,
COLORS.yellow,
COLORS.red,
COLORS.magenta,
COLORS.reset,
)
}