OXYGENHUB
# d98a93c10a0d oxygenhub / crates / oh / src / ui.rs
2.0 KiB · Rust · last changed oh: OxygenHub from the command line 1 month ago source blame history raw
1
//! Output styling in the manner of `oxy`: colour and glyphs on a terminal,
2
//! plain text with `--plain`, `NO_COLOR` or when piped.
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
/// A run's or job's or check's status, as a glyph.
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("–"),
54
        _ => dim("?"),
55
    }
56
}
57
58
/// "3 minutes ago", as oxy says it.
59
pub fn ago(ms: i64) -> String {
60
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0);
61
    let secs = (now - ms).max(0) / 1000;
62
    let unit = |n: i64, w: &str| format!("{n} {w}{} ago", if n == 1 { "" } else { "s" });
63
    match secs {
64
        0..=44 => "just now".into(),
65
        45..=89 => "a minute ago".into(),
66
        90..=2_699 => unit((secs + 59) / 60, "minute"),
67
        2_700..=5_399 => "an hour ago".into(),
68
        5_400..=79_199 => unit((secs + 3_599) / 3_600, "hour"),
69
        79_200..=129_599 => "yesterday".into(),
70
        _ => unit((secs + 86_399) / 86_400, "day"),
71
    }
72
}