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
use std::ffi::OsStr;
/// Whether `--color WHEN` colors the output, given whether stdout is a
/// terminal and the value of NO_COLOR.
pub fn color_enabled(when: &str, is_tty: bool, no_color: Option<&OsStr>) -> bool {
match when {
"always" => true,
"never" => false,
_ => is_tty && no_color.is_none_or(OsStr::is_empty),
}
}
/// What a piece of output is colored as.
#[derive(Clone, Copy)]
pub(crate) enum Paint {
Id,
Ready,
Claimed,
Blocked,
Done,
}
impl Paint {
fn code(self) -> &'static str {
match self {
Self::Ready => "32",
Self::Claimed => "33",
Self::Blocked => "31",
Self::Done => "90",
Self::Id => "35",
}
}
}
pub(crate) fn paint(color: bool, text: &str, key: Paint) -> String {
if color && !text.is_empty() {
format!("\x1b[{}m{text}\x1b[0m", key.code())
} else {
text.to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auto_colors_only_a_terminal_without_no_color() {
assert!(color_enabled("auto", true, None));
assert!(color_enabled("auto", true, Some(OsStr::new(""))));
assert!(!color_enabled("auto", true, Some(OsStr::new("1"))));
assert!(!color_enabled("auto", false, None));
}
#[test]
fn always_and_never_ignore_the_terminal() {
assert!(color_enabled("always", false, Some(OsStr::new("1"))));
assert!(!color_enabled("never", true, None));
}
#[test]
fn empty_text_stays_plain() {
assert_eq!(paint(true, "", Paint::Id), "");
assert_eq!(paint(true, "x", Paint::Id), "\x1b[35mx\x1b[0m");
}
}