//! 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("–"), "cancelled" => 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"), } } /// A wall time as its UTC date and minute, `2026-11-16 09:30Z`. pub fn date(ms: i64) -> String { let secs = ms.div_euclid(1000); let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm). let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2); format!("{y:04}-{m:02}-{d:02} {:02}:{:02}Z", rem / 3_600, rem % 3_600 / 60) } #[cfg(test)] mod date_tests { #[test] fn dates_are_utc_civil_dates() { assert_eq!(super::date(0), "1970-01-01 00:00Z"); assert_eq!(super::date(1_792_229_400_000), "2026-10-17 09:30Z"); assert_eq!(super::date(951_782_400_000), "2000-02-29 00:00Z"); } }