diff --git a/src/util.rs b/src/util.rs index 8902b34..5b73255 100644 --- a/src/util.rs +++ b/src/util.rs @@ -3,6 +3,7 @@ use chrono::NaiveDateTime; use std::fs; use std::io::IsTerminal; use std::path::Path; +use std::sync::OnceLock; /// How timestamps are written into tickets and comments, and therefore how they /// are read back. Shared so the writer and the reader cannot drift apart. @@ -15,8 +16,40 @@ pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S"; /// Fixed width, so the lexicographic sort in `read_comments` stays chronological. pub const COMMENT_FILE_FORMAT: &str = "%Y%m%d_%H%M%S_%6f"; +/// Whether colour is wanted, from the three inputs that decide it. +/// +/// Split out from the caching wrapper so it can be tested without a pty and +/// without touching the process environment. +/// +/// `NO_COLOR` follows the no-color.org convention: set and non-empty disables, +/// whatever the value. An empty value is treated as unset, which is what lets a +/// wrapper script clear an inherited one. +fn colors_wanted(is_terminal: bool, no_color: Option<&str>, term: Option<&str>) -> bool { + if no_color.is_some_and(|value| !value.is_empty()) { + return false; + } + + if matches!(term, Some("dumb") | Some("")) { + return false; + } + + is_terminal +} + pub fn should_use_colors() -> bool { - std::io::stdout().is_terminal() + // Decided once: it cannot change mid-run, and color_text asks on every call. + static ENABLED: OnceLock = OnceLock::new(); + + *ENABLED.get_or_init(|| { + let no_color = std::env::var("NO_COLOR").ok(); + let term = std::env::var("TERM").ok(); + + colors_wanted( + std::io::stdout().is_terminal(), + no_color.as_deref(), + term.as_deref(), + ) + }) } pub fn get_color(color: &str) -> &'static str { @@ -495,6 +528,35 @@ pub fn collect_ticket_items(status_path: impl AsRef) -> Result