| 5c6e92fd Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
use std::io::IsTerminal; |
| 5 |
use std::sync::OnceLock; |
| 6 |
|
| 7 |
static PLAIN: OnceLock<bool> = OnceLock::new(); |
| 8 |
|
| 9 |
pub fn init(plain_flag: bool) { |
| 10 |
let plain = plain_flag || std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) || !std::io::stdout().is_terminal(); |
| 11 |
let _ = PLAIN.set(plain); |
| 12 |
} |
| 13 |
|
| 14 |
fn plain() -> bool { |
| 15 |
*PLAIN.get().unwrap_or(&true) |
| 16 |
} |
| 17 |
|
| 18 |
fn paint(code: &str, s: &str) -> String { |
| 19 |
if plain() { |
| 20 |
s.to_string() |
| 21 |
} else { |
| 22 |
format!("\x1b[{code}m{s}\x1b[0m") |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
pub fn ok(s: &str) -> String { |
| 27 |
paint("32", s) |
| 28 |
} |
| 29 |
pub fn bad(s: &str) -> String { |
| 30 |
paint("31", s) |
| 31 |
} |
| 32 |
pub fn warn(s: &str) -> String { |
| 33 |
paint("35", s) |
| 34 |
} |
| 35 |
pub fn dim(s: &str) -> String { |
| 36 |
paint("2", s) |
| 37 |
} |
| 38 |
pub fn strong(s: &str) -> String { |
| 39 |
paint("1", s) |
| 40 |
} |
| 41 |
|
| 42 |
pub fn kv(key: &str, value: &str) -> String { |
| 43 |
format!("{} {value}", dim(&format!("{key:>16}"))) |
| 44 |
} |
| 45 |
|
| 46 |
|
| 47 |
pub fn status(s: &str) -> String { |
| 48 |
match s { |
| 49 |
"passed" | "success" => ok("✔"), |
| 50 |
"failed" | "failure" | "error" => bad("✘"), |
| 51 |
"running" | "pending" => warn("●"), |
| 52 |
"queued" => dim("○"), |
| 53 |
"skipped" | "neutral" => dim("–"), |
| 56a786aa Andy McCall ↶ |
54 |
"cancelled" => dim("⊘"), |
| 5c6e92fd Andy McCall ↶ |
55 |
_ => dim("?"), |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
pub fn ago(ms: i64) -> String { |
| 61 |
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0); |
| 62 |
let secs = (now - ms).max(0) / 1000; |
| 63 |
let unit = |n: i64, w: &str| format!("{n} {w}{} ago", if n == 1 { "" } else { "s" }); |
| 64 |
match secs { |
| 65 |
0..=44 => "just now".into(), |
| 66 |
45..=89 => "a minute ago".into(), |
| 67 |
90..=2_699 => unit((secs + 59) / 60, "minute"), |
| 68 |
2_700..=5_399 => "an hour ago".into(), |
| 69 |
5_400..=79_199 => unit((secs + 3_599) / 3_600, "hour"), |
| 70 |
79_200..=129_599 => "yesterday".into(), |
| 71 |
_ => unit((secs + 86_399) / 86_400, "day"), |
| 72 |
} |
| 73 |
} |