From b6d0b55d4be336fd7aefdff85e0e97615d6dbeaf Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Thu, 20 Aug 2026 15:04:41 +0200 Subject: [PATCH] (9991698) Respect NO_COLOR and non-capable terminals should_use_colors only asked whether stdout was a terminal, so there was no way to turn colour off in one, and it was re-evaluated on every color_text call. Honour NO_COLOR by the no-color.org rule, set and non-empty disables whatever the value, with an empty value treated as unset so an inherited one can be cleared. Treat TERM=dumb and an empty TERM as no colour. Decide once in a OnceLock, since none of the three inputs change mid-run. The decision itself is a pure function of its three inputs, so it is tested without a pty. Verified under a real one as well: colour on by default, absent with NO_COLOR=1, absent with TERM=dumb, present again with NO_COLOR set to empty. Co-Authored-By: Claude Opus 5 (1M context) --- src/util.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) 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