1use std::io::IsTerminal;
19use std::sync::atomic::{AtomicU8, Ordering};
20
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
23pub enum ColourChoice {
24 #[default]
27 Auto,
28 Always,
30 Never,
32}
33
34impl ColourChoice {
35 pub fn clap(self) -> clap::ColorChoice {
37 match self {
38 ColourChoice::Auto => clap::ColorChoice::Auto,
39 ColourChoice::Always => clap::ColorChoice::Always,
40 ColourChoice::Never => clap::ColorChoice::Never,
41 }
42 }
43
44 pub fn from_args<I, S>(args: I) -> Option<ColourChoice>
50 where
51 I: IntoIterator<Item = S>,
52 S: AsRef<std::ffi::OsStr>,
53 {
54 use clap::ValueEnum;
55 let mut found = None;
56 let mut args = args.into_iter().skip(1);
57 while let Some(arg) = args.next() {
58 let Some(arg) = arg.as_ref().to_str() else {
59 continue;
60 };
61 if arg == "--" {
62 break;
63 }
64 let value = match arg.split_once('=') {
65 Some(("--color" | "--colour", value)) => value.to_string(),
66 None if arg == "--color" || arg == "--colour" => {
67 match args
68 .next()
69 .and_then(|v| v.as_ref().to_str().map(str::to_string))
70 {
71 Some(value) => value,
72 None => break,
73 }
74 }
75 _ => continue,
76 };
77 if let Ok(choice) = ColourChoice::from_str(&value, true) {
79 found = Some(choice);
80 }
81 }
82 found
83 }
84}
85
86static CHOICE: AtomicU8 = AtomicU8::new(0);
87
88pub fn set_choice(choice: ColourChoice) {
91 CHOICE.store(choice as u8, Ordering::Relaxed);
92}
93
94pub fn choice() -> ColourChoice {
96 match CHOICE.load(Ordering::Relaxed) {
97 1 => ColourChoice::Always,
98 2 => ColourChoice::Never,
99 _ => ColourChoice::Auto,
100 }
101}
102
103pub fn stdout() -> bool {
105 resolve(choice(), || std::io::stdout().is_terminal())
106}
107
108pub fn stderr() -> bool {
110 resolve(choice(), || std::io::stderr().is_terminal())
111}
112
113fn resolve(choice: ColourChoice, is_terminal: impl FnOnce() -> bool) -> bool {
114 match choice {
115 ColourChoice::Always => true,
116 ColourChoice::Never => false,
117 ColourChoice::Auto => allowed(is_terminal(), |name| std::env::var_os(name)),
118 }
119}
120
121pub fn apply_to_child(cmd: &mut std::process::Command, piped: bool) {
127 match choice() {
128 ColourChoice::Never => {
129 cmd.env_remove("FORCE_COLOR").env("NO_COLOR", "1");
130 }
131 ColourChoice::Always => {
132 cmd.env_remove("NO_COLOR").env("FORCE_COLOR", "1");
133 }
134 ColourChoice::Auto => {
135 if piped && stderr() {
136 cmd.env("FORCE_COLOR", "1");
137 }
138 }
139 }
140}
141
142pub(crate) fn allowed(is_terminal: bool, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
154 let set = |name| var(name).is_some_and(|v| !v.is_empty());
155 let forced = |name| var(name).is_some_and(|v| !v.is_empty() && v != "0");
156 if set("NO_COLOR") {
157 false
158 } else {
159 is_terminal || forced("FORCE_COLOR") || forced("CLICOLOR_FORCE")
160 }
161}
162
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub enum Style {
166 Blue,
168 Green,
170 Amber,
172 Red,
174 Bold,
176 Dim,
178}
179
180impl Style {
181 fn codes(self) -> (&'static str, &'static str) {
182 match self {
183 Style::Blue => ("\x1b[34m", "\x1b[39m"),
184 Style::Green => ("\x1b[32m", "\x1b[39m"),
185 Style::Amber => ("\x1b[33m", "\x1b[39m"),
186 Style::Red => ("\x1b[31m", "\x1b[39m"),
187 Style::Bold => ("\x1b[1m", "\x1b[22m"),
188 Style::Dim => ("\x1b[2m", "\x1b[22m"),
189 }
190 }
191}
192
193pub fn paint(on: bool, style: Style, text: &str) -> String {
195 if on {
196 let (open, close) = style.codes();
197 format!("{open}{text}{close}")
198 } else {
199 text.to_string()
200 }
201}
202
203#[derive(Debug, Default)]
211pub struct TestLines {
212 after_blank: bool,
214}
215
216impl TestLines {
217 pub fn paint(&mut self, line: &str) -> String {
219 let (body, end) = split_end(line);
220 let after_blank = std::mem::replace(&mut self.after_blank, body.is_empty());
221 let styled = if let Some(name) = body.strip_prefix(" \u{2713} ") {
222 format!(" {} {name}", paint(true, Style::Green, "\u{2713}"))
223 } else if body.starts_with(" \u{2717} ") {
224 paint(true, Style::Red, body)
225 } else if body.starts_with(" ! ") {
226 paint(true, Style::Amber, body)
227 } else if let Some(tally) = tally(body) {
228 tally
229 } else if after_blank && !body.starts_with(' ') && body.ends_with(':') {
230 paint(true, Style::Bold, body)
231 } else {
232 return line.to_string();
233 };
234 format!("{styled}{end}")
235 }
236}
237
238fn tally(body: &str) -> Option<String> {
240 let (passed, rest) = body.split_once(" passed, ")?;
241 let failed = rest.strip_suffix(" failed.")?;
242 let p: u64 = passed.parse().ok()?;
243 let f: u64 = failed.parse().ok()?;
244 let passed = format!("{p} passed");
245 let failed = format!("{f} failed");
246 Some(format!(
247 "{}, {}.",
248 if p > 0 && f == 0 {
249 paint(true, Style::Green, &passed)
250 } else {
251 passed
252 },
253 if f > 0 {
254 paint(true, Style::Red, &failed)
255 } else {
256 paint(true, Style::Dim, &failed)
257 },
258 ))
259}
260
261fn split_end(line: &str) -> (&str, &str) {
262 if let Some(body) = line.strip_suffix("\r\n") {
263 (body, "\r\n")
264 } else if let Some(body) = line.strip_suffix('\n') {
265 (body, "\n")
266 } else {
267 (line, "")
268 }
269}
270
271pub fn message(text: &str) -> String {
277 text.split_inclusive('\n').map(message_line).collect()
278}
279
280const LABELS: [(&str, Style); 3] = [
281 ("error:", Style::Red),
282 ("warning:", Style::Amber),
283 ("note:", Style::Blue),
284];
285
286fn message_line(line: &str) -> String {
287 let mut at = line.len() - line.trim_start().len();
290 if line[at..].starts_with("= ") {
291 at += 2;
292 }
293 let mut starts = vec![at];
294 while let Some(colon) = line[at..].find(": ") {
295 if !is_speaker(&line[at..at + colon]) {
296 break;
297 }
298 at += colon + 2;
299 starts.push(at);
300 }
301 for start in starts {
302 for (label, style) in LABELS {
303 if let Some(end) = label_end(&line[start..], label) {
304 let (label, end) = (&line[start..start + end], start + end);
305 return format!(
306 "{}{}{}",
307 &line[..start],
308 paint(true, style, label),
309 &line[end..]
310 );
311 }
312 }
313 }
314 line.to_string()
315}
316
317fn label_end(text: &str, label: &str) -> Option<usize> {
320 if text.starts_with(label) {
321 return Some(label.len());
322 }
323 let word = label.trim_end_matches(':');
324 let code = text.strip_prefix(word)?.strip_prefix('[')?;
325 let close = code.find("]:")?;
326 let plain = |c: char| c.is_ascii_alphanumeric() || "._-".contains(c);
327 (close > 0 && code[..close].chars().all(plain)).then_some(word.len() + 1 + close + 2)
328}
329
330fn is_speaker(text: &str) -> bool {
334 !text.is_empty()
335 && text.len() <= 40
336 && !LABELS.iter().any(|(l, _)| l.trim_end_matches(':') == text)
337 && text
338 .chars()
339 .all(|c| c.is_ascii_alphanumeric() || " -_./".contains(c))
340}
341
342pub fn stderr_message(text: &str) -> String {
345 if stderr() {
346 message(text)
347 } else {
348 text.to_string()
349 }
350}
351
352pub fn eprint_message(text: &str) {
355 eprintln!("{}", stderr_message(text));
356}
357
358pub fn eprint(text: &str) {
360 eprint!("{}", stderr_message(text));
361}
362
363pub fn eprintln(text: &str) {
365 eprint_message(text);
366}
367
368#[macro_export]
371macro_rules! emsg {
372 ($($arg:tt)*) => {
373 $crate::colour::eprint_message(&format!($($arg)*))
374 };
375}
376
377pub fn coverage_style(percent: u32) -> Style {
380 match percent {
381 80.. => Style::Green,
382 50.. => Style::Amber,
383 _ => Style::Red,
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
396 fn auto_needs_a_terminal_or_a_force_and_no_no_color() {
397 use std::ffi::OsString;
398 let allowed = |is_terminal, vars: &[(&str, &str)]| {
399 allowed(is_terminal, |name| {
400 vars.iter()
401 .find(|(n, _)| *n == name)
402 .map(|(_, v)| OsString::from(v))
403 })
404 };
405 assert!(allowed(true, &[]));
406 assert!(allowed(true, &[("NO_COLOR", "")]));
407 assert!(!allowed(true, &[("NO_COLOR", "1")]));
408 assert!(!allowed(false, &[]));
409 assert!(!allowed(false, &[("NO_COLOR", "")]));
410
411 for force in ["FORCE_COLOR", "CLICOLOR_FORCE"] {
412 assert!(allowed(false, &[(force, "1")]), "{force}=1");
413 assert!(allowed(false, &[(force, "true")]), "{force}=true");
414 assert!(!allowed(false, &[(force, "")]), "{force}= is unset");
415 assert!(!allowed(false, &[(force, "0")]), "{force}=0 doesn't force");
416 assert!(allowed(true, &[(force, "0")]), "{force}=0 doesn't forbid");
417 assert!(allowed(false, &[(force, "1"), ("NO_COLOR", "")]));
418 assert!(!allowed(false, &[(force, "1"), ("NO_COLOR", "1")]));
419 assert!(!allowed(true, &[(force, "1"), ("NO_COLOR", "1")]));
420 }
421 }
422
423 #[test]
424 fn always_and_never_ignore_the_terminal() {
425 assert!(resolve(ColourChoice::Always, || false));
426 assert!(!resolve(ColourChoice::Never, || true));
427 }
428
429 #[test]
430 fn the_flag_is_found_in_either_spelling_and_the_last_wins() {
431 let find = |args: &[&str]| ColourChoice::from_args(args);
432 assert_eq!(find(&["bynk", "test"]), None);
433 assert_eq!(
434 find(&["bynk", "--color", "never", "test"]),
435 Some(ColourChoice::Never)
436 );
437 assert_eq!(
438 find(&["bynk", "test", "--colour=always"]),
439 Some(ColourChoice::Always)
440 );
441 assert_eq!(
442 find(&["bynk", "--color=never", "test", "--colour", "auto"]),
443 Some(ColourChoice::Auto)
444 );
445 assert_eq!(find(&["bynk", "dev", "--", "--color=never"]), None);
447 assert_eq!(find(&["bynk", "--color=sometimes"]), None);
448 assert_eq!(find(&["bynk", "--color"]), None);
449 }
450
451 fn test_line(line: &str) -> String {
453 TestLines { after_blank: true }.paint(line)
454 }
455
456 #[test]
457 fn a_heading_follows_a_blank_line() {
458 let mut lines = TestLines::default();
459 let out: Vec<String> = [
460 "Running tests...\n",
461 "\n",
462 "orders:\n",
463 "Response:\n",
464 " \u{2713} adds\n",
465 "\n",
466 "billing:\n",
467 ]
468 .iter()
469 .map(|l| lines.paint(l))
470 .collect();
471 assert_eq!(out[2], "\x1b[1morders:\x1b[22m\n");
472 assert_eq!(out[3], "Response:\n", "a test's own output is left alone");
473 assert_eq!(out[6], "\x1b[1mbilling:\x1b[22m\n");
474 }
475
476 #[test]
477 fn test_lines_are_coloured_by_outcome() {
478 assert_eq!(
479 test_line(" \u{2713} adds\n"),
480 " \x1b[32m\u{2713}\x1b[39m adds\n"
481 );
482 assert_eq!(
483 test_line(" \u{2717} subtracts\n"),
484 "\x1b[31m \u{2717} subtracts\x1b[39m\n"
485 );
486 assert_eq!(test_line("orders:\n"), "\x1b[1morders:\x1b[22m\n");
487 assert_eq!(
488 test_line("3 passed, 0 failed.\n"),
489 "\x1b[32m3 passed\x1b[39m, \x1b[2m0 failed\x1b[22m.\n"
490 );
491 assert_eq!(
492 test_line("3 passed, 1 failed."),
493 "3 passed, \x1b[31m1 failed\x1b[39m."
494 );
495 for line in [
497 "Running tests...\n",
498 "\n",
499 " expected 1, got 2\n",
500 "a passed, b failed.\n",
501 ] {
502 assert_eq!(test_line(line), line);
503 }
504 }
505
506 #[test]
507 fn a_message_label_is_coloured_where_it_stands() {
508 let red = |l: &str| format!("\x1b[31m{l}\x1b[39m");
509 let amber = |l: &str| format!("\x1b[33m{l}\x1b[39m");
510 let blue = |l: &str| format!("\x1b[34m{l}\x1b[39m");
511 assert_eq!(
512 message("bynk: warning: kept it"),
513 format!("bynk: {} kept it", amber("warning:"))
514 );
515 assert_eq!(
516 message("bynk test: error: no tests found in x"),
517 format!("bynk test: {} no tests found in x", red("error:"))
518 );
519 assert_eq!(
520 message("bynk dev: note: `a.sql` changed"),
521 format!("bynk dev: {} `a.sql` changed", blue("note:"))
522 );
523 assert_eq!(
524 message("first\n = note: the token came from X\n note: y\nwarning: z"),
525 format!(
526 "first\n = {} the token came from X\n {} y\n{} z",
527 blue("note:"),
528 blue("note:"),
529 amber("warning:")
530 )
531 );
532 assert_eq!(
534 message("bynk: warning: x said error: y"),
535 format!("bynk: {} x said error: y", amber("warning:"))
536 );
537 assert_eq!(
539 message("bynk: packages/ok: error: no member"),
540 format!("bynk: packages/ok: {} no member", red("error:"))
541 );
542 assert_eq!(
544 message("bynk: error[bynk.fetch.status]: 404 from x"),
545 format!("bynk: {} 404 from x", red("error[bynk.fetch.status]:"))
546 );
547 for plain in [
548 "bynk: error[]: empty code",
549 "bynk: error[a b]: a space",
550 "bynk: signed out of `acme`",
551 "bynk: could not read `a: b`: error: no",
552 "",
553 ] {
554 assert_eq!(message(plain), plain);
555 }
556 }
557
558 #[test]
559 fn coverage_is_red_amber_green() {
560 assert_eq!(coverage_style(100), Style::Green);
561 assert_eq!(coverage_style(80), Style::Green);
562 assert_eq!(coverage_style(79), Style::Amber);
563 assert_eq!(coverage_style(50), Style::Amber);
564 assert_eq!(coverage_style(49), Style::Red);
565 assert_eq!(coverage_style(0), Style::Red);
566 }
567
568 #[test]
569 fn paint_off_is_plain() {
570 assert_eq!(paint(false, Style::Red, "x"), "x");
571 assert_eq!(paint(true, Style::Red, "x"), "\x1b[31mx\x1b[39m");
572 }
573}