//! Output styling in the manner of `oxy`: colour and glyphs on a terminal, //! plain text with `--plain`, `NO_COLOR` or when piped. use std::io::IsTerminal; use std::sync::OnceLock; static PLAIN: OnceLock = OnceLock::new(); pub fn init(plain_flag: bool) { let plain = plain_flag || std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty()) || !std::io::stdout().is_terminal(); let _ = PLAIN.set(plain); } fn plain() -> bool { *PLAIN.get().unwrap_or(&true) } fn paint(code: &str, s: &str) -> String { if plain() { s.to_string() } else { format!("\x1b[{code}m{s}\x1b[0m") } } pub fn ok(s: &str) -> String { paint("32", s) } pub fn bad(s: &str) -> String { paint("31", s) } pub fn warn(s: &str) -> String { paint("35", s) } pub fn dim(s: &str) -> String { paint("2", s) } pub fn strong(s: &str) -> String { paint("1", s) } pub fn kv(key: &str, value: &str) -> String { format!("{} {value}", dim(&format!("{key:>16}"))) } /// A run's or job's or check's status, as a glyph. pub fn status(s: &str) -> String { match s { "passed" | "success" => ok("✔"), "failed" | "failure" | "error" => bad("✘"), "running" | "pending" => warn("●"), "queued" => dim("○"), "skipped" | "neutral" => dim("–"), _ => dim("?"), } } /// "3 minutes ago", as oxy says it. pub fn ago(ms: i64) -> String { let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0); let secs = (now - ms).max(0) / 1000; let unit = |n: i64, w: &str| format!("{n} {w}{} ago", if n == 1 { "" } else { "s" }); match secs { 0..=44 => "just now".into(), 45..=89 => "a minute ago".into(), 90..=2_699 => unit((secs + 59) / 60, "minute"), 2_700..=5_399 => "an hour ago".into(), 5_400..=79_199 => unit((secs + 3_599) / 3_600, "hour"), 79_200..=129_599 => "yesterday".into(), _ => unit((secs + 86_399) / 86_400, "day"), } }