1use std::borrow::Cow;
5use std::fmt::Display;
6use std::io::Write;
7
8use crate::Env;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum ColorChoice {
14 Auto,
16 Always,
18 Never,
20}
21
22const RESET: &str = "\x1b[0m";
23const BOLD_RED: &str = "\x1b[1;31m";
24const BOLD_YELLOW: &str = "\x1b[1;33m";
25const BOLD_CYAN: &str = "\x1b[1;36m";
26const BOLD_GREEN: &str = "\x1b[1;32m";
27
28pub fn colors(
34 given: Option<ColorChoice>,
35 configured: Option<ColorChoice>,
36 no_color: bool,
37 terminal: bool,
38) -> bool {
39 match given.or(configured) {
40 Some(ColorChoice::Always) => true,
41 Some(ColorChoice::Never) => false,
42 Some(ColorChoice::Auto) => terminal,
43 None => terminal && !no_color,
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52pub enum Verbosity {
53 Quiet,
55 #[default]
57 Normal,
58 Verbose,
60}
61
62pub struct Shell {
65 out: Box<dyn Write>,
66 given: Option<ColorChoice>,
68 no_color: bool,
70 terminal: bool,
72 color: bool,
73 verbosity: Verbosity,
74}
75
76impl Shell {
77 pub fn new(
87 out: Box<dyn Write>,
88 choice: Option<ColorChoice>,
89 env: &Env,
90 out_is_terminal: bool,
91 ) -> Shell {
92 let mut shell = Shell {
93 out,
94 given: choice,
95 no_color: env.get("NO_COLOR").is_some(),
96 terminal: out_is_terminal,
97 color: false,
98 verbosity: Verbosity::Normal,
99 };
100 shell.configure(None, false);
101 shell
102 }
103
104 pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
108 self.color = colors(self.given, configured, self.no_color, self.terminal);
109 if verbose && self.verbosity == Verbosity::Normal {
110 self.verbosity = Verbosity::Verbose;
111 }
112 }
113
114 pub fn set_verbosity(&mut self, verbosity: Verbosity) {
119 self.verbosity = verbosity;
120 }
121
122 pub fn verbose(&self) -> bool {
124 self.verbosity == Verbosity::Verbose
125 }
126
127 pub fn uses_color(&self) -> bool {
129 self.color
130 }
131
132 pub fn error(&mut self, message: impl Display) {
134 self.line(BOLD_RED, "error", message);
135 }
136
137 pub fn warning(&mut self, message: impl Display) {
139 self.line(BOLD_YELLOW, "warning", message);
140 }
141
142 pub fn help(&mut self, message: impl Display) {
144 self.line(BOLD_CYAN, "help", message);
145 }
146
147 pub fn status(&mut self, verb: &str, message: impl Display) {
151 if self.verbosity == Verbosity::Quiet {
152 return;
153 }
154 let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
155 let message = message.to_string();
156 let message = escaped_text(&message);
157 self.write(format_args!("{verb} {message}"));
158 }
159
160 pub fn raw(&mut self, bytes: &[u8]) {
166 let _ = self.out.write_all(bytes);
168 let _ = self.out.flush();
169 }
170
171 pub fn tool_output(&mut self, bytes: &[u8], asked: bool) {
178 let shown = escaped(bytes, asked && self.color);
179 self.raw(&shown);
180 }
181
182 fn line(&mut self, style: &str, label: &str, message: impl Display) {
183 let label = self.paint(style, label);
184 let message = message.to_string();
187 let message = escaped_text(&message);
188 self.write(format_args!("{label}: {message}"));
189 }
190
191 fn write(&mut self, line: std::fmt::Arguments<'_>) {
192 let _ = writeln!(self.out, "{line}");
194 }
195
196 fn paint(&self, style: &str, text: &str) -> String {
197 if self.color {
198 format!("{style}{text}{RESET}")
199 } else {
200 text.to_owned()
201 }
202 }
203}
204
205fn escaped(bytes: &[u8], color: bool) -> Vec<u8> {
212 let mut out = Vec::with_capacity(bytes.len());
213 let mut i = 0;
214 while i < bytes.len() {
215 let byte = bytes[i];
216 let kept = match byte {
217 b'\n' | b'\t' => 1,
218 b'\r' if bytes.get(i + 1) == Some(&b'\n') => 1,
219 0x1b if color => color_sequence(&bytes[i..]),
220 0x00..=0x1f | 0x7f => 0,
221 _ => 1,
222 };
223 if kept == 0 {
226 out.extend(format!("\\x{byte:02x}").bytes());
227 i += 1;
228 } else {
229 out.extend(&bytes[i..i + kept]);
230 i += kept;
231 }
232 }
233 out
234}
235
236pub fn without_color(bytes: &[u8]) -> Vec<u8> {
241 let mut out = Vec::with_capacity(bytes.len());
242 let mut i = 0;
243 while i < bytes.len() {
244 let color = if bytes[i] == 0x1b {
245 color_sequence(&bytes[i..])
246 } else {
247 0
248 };
249 if color == 0 {
250 out.push(bytes[i]);
251 i += 1;
252 } else {
253 i += color;
254 }
255 }
256 out
257}
258
259fn color_sequence(bytes: &[u8]) -> usize {
267 if bytes.get(1) != Some(&b'[') {
268 return 0;
269 }
270 let length = bytes[2..]
271 .iter()
272 .take_while(|b| b.is_ascii_digit() || **b == b';' || **b == b':')
273 .count();
274 let parameters = &bytes[2..2 + length];
275 let shown = match bytes.get(2 + length) {
276 Some(b'm') => styles_shown_text(parameters),
277 Some(b'K') => matches!(parameters, b"" | b"0"),
278 _ => false,
279 };
280 if shown { 2 + length + 1 } else { 0 }
281}
282
283fn styles_shown_text(parameters: &[u8]) -> bool {
285 let mut codes = parameters.split(|b| *b == b';' || *b == b':').map(|code| {
286 if code.is_empty() {
287 Some(0)
288 } else {
289 std::str::from_utf8(code).ok()?.parse::<u32>().ok()
290 }
291 });
292 while let Some(code) = codes.next() {
293 match code {
294 Some(0 | 1 | 3 | 4 | 22 | 23 | 24 | 39 | 30..=37 | 90..=97) => {}
295 Some(38) => {
298 let numbers = match codes.next() {
299 Some(Some(5)) => 1,
300 Some(Some(2)) => 3,
301 _ => return false,
302 };
303 for _ in 0..numbers {
304 if !matches!(codes.next(), Some(Some(0..=255))) {
305 return false;
306 }
307 }
308 }
309 _ => return false,
310 }
311 }
312 true
313}
314
315fn escaped_text(text: &str) -> Cow<'_, str> {
320 let plain = |c: char| !c.is_control() || c == '\n' || c == '\t';
321 if text.chars().all(plain) {
322 return Cow::Borrowed(text);
323 }
324 let mut out = String::with_capacity(text.len());
325 let mut chars = text.chars().peekable();
326 while let Some(c) = chars.next() {
327 match c {
328 c if plain(c) => out.push(c),
329 '\r' if chars.peek() == Some(&'\n') => out.push(c),
330 c if (c as u32) < 0x80 => out.push_str(&format!("\\x{:02x}", c as u32)),
331 c => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
332 }
333 }
334 Cow::Owned(out)
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 use crate::env::NameCase;
341 use std::sync::{Arc, Mutex};
342
343 #[derive(Clone, Default)]
345 struct Captured(Arc<Mutex<Vec<u8>>>);
346
347 impl Write for Captured {
348 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
349 self.0.lock().unwrap().write(buf)
350 }
351 fn flush(&mut self) -> std::io::Result<()> {
352 Ok(())
353 }
354 }
355
356 impl Captured {
357 fn text(&self) -> String {
358 String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
359 }
360 }
361
362 fn shell(
363 choice: Option<ColorChoice>,
364 env: &[(&str, &str)],
365 terminal: bool,
366 ) -> (Shell, Captured) {
367 let out = Captured::default();
368 let env = Env::from_pairs(
369 env.iter().map(|(n, v)| (n.into(), v.into())),
370 NameCase::Sensitive,
371 );
372 (
373 Shell::new(Box::new(out.clone()), choice, &env, terminal),
374 out,
375 )
376 }
377
378 #[test]
386 fn configured_verbose_ranks_below_the_command_line() {
387 let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
389 assert!(!fresh.verbose());
390 for (given, configured, verbose, quiet) in [
391 (Verbosity::Normal, true, true, false),
392 (Verbosity::Normal, false, false, false),
393 (Verbosity::Quiet, true, false, true),
394 (Verbosity::Verbose, false, true, false),
395 ] {
396 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
397 sh.set_verbosity(given);
398 sh.configure(None, configured);
399 assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
400 sh.status("Compiling", "app");
401 assert_eq!(
402 out.text().is_empty(),
403 quiet,
404 "{given:?}, configured {configured}"
405 );
406 }
407 }
408
409 #[test]
415 fn quiet_leaves_out_status_lines_only() {
416 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
417 sh.set_verbosity(Verbosity::Quiet);
418 sh.status("Compiling", "mygame v0.1.0");
419 sh.error("no compiler found");
420 sh.help("install Build Tools");
421 sh.warning("unused key");
422 sh.raw(
423 b"main.cpp(1): note
424",
425 );
426 assert_eq!(
427 out.text(),
428 "error: no compiler found
429help: install Build Tools
430warning: unused key
431main.cpp(1): note
432"
433 );
434 }
435
436 #[test]
439 fn lines_without_color() {
440 let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
441 sh.error("no compiler found");
442 sh.help("install Build Tools");
443 sh.warning("unused key");
444 sh.status("Compiling", "mygame v0.1.0");
445 assert_eq!(
446 out.text(),
447 "error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n Compiling mygame v0.1.0\n"
448 );
449 }
450
451 #[test]
456 fn raw_output_is_written_as_produced() {
457 let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
458 let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
459 sh.raw(&cp932);
460 sh.raw(b"x");
461 assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
462 }
463 #[test]
471 fn a_tools_control_characters_are_shown_escaped() {
472 let cp932 = [0x83, 0x5c, 0x88, 0x9f];
473 let mut bytes = b"a\tb\r\nc\x1b]0;x\x07d\re\x00\x7f\x0bf".to_vec();
474 bytes.extend(cp932);
475 bytes.push(b'\r');
476 let mut expected = b"a\tb\r\nc\\x1b]0;x\\x07d\\x0de\\x00\\x7f\\x0bf".to_vec();
477 expected.extend(cp932);
478 expected.extend(b"\\x0d");
479 assert_eq!(escaped(&bytes, false), expected);
480 assert_eq!(escaped(&bytes, true), expected);
481 }
482
483 #[test]
493 fn only_color_that_shows_text_passes() {
494 for kept in [
495 &b"\x1b[1;31merror\x1b[0m: x"[..],
496 b"\x1b[01;35m\x1b[Kwarning: \x1b[m\x1b[K",
497 b"\x1b[0;1;36mnote\x1b[0m",
498 b"\x1b[38;5;1mx\x1b[38:2:1:2:3mx\x1b[39m",
499 ] {
500 assert_eq!(escaped(kept, true), kept);
501 }
502 assert_eq!(
503 escaped(b"\x1b[1;31merror\x1b[0m: x", false),
504 b"\\x1b[1;31merror\\x1b[0m: x".to_vec()
505 );
506 for (hiding, shown) in [
507 (&b"\x1b[8mx"[..], &b"\\x1b[8mx"[..]),
508 (b"\x1b[30;40mx", b"\\x1b[30;40mx"),
509 (b"\x1b[7mx", b"\\x1b[7mx"),
510 (b"\x1b[5mx", b"\\x1b[5mx"),
511 (b"\x1b[38;5mx", b"\\x1b[38;5mx"),
512 (b"\x1b[2J\x1b[?25l", b"\\x1b[2J\\x1b[?25l"),
513 (b"\x1b[?1m", b"\\x1b[?1m"),
514 (b"\x1b[2K", b"\\x1b[2K"),
515 (b"\x1b[", b"\\x1b["),
516 ] {
517 assert_eq!(escaped(hiding, true), shown);
518 }
519 }
520
521 #[test]
528 fn taking_color_out_keeps_what_is_not_color() {
529 assert_eq!(
530 without_color(b"\x1b[1ma.cpp:1:1: \x1b[0;1;35mwarning: \x1b[0mx\x1b[K\n"),
531 b"a.cpp:1:1: warning: x\n"
532 );
533 assert_eq!(
534 without_color(b"a \x1b[2J b \x1b[8mhidden\x1b[0m c"),
535 b"a \x1b[2J b \x1b[8mhidden c"
536 );
537 assert_eq!(without_color(b"lone \x1b here"), b"lone \x1b here");
538 }
539
540 #[test]
548 fn a_value_in_a_message_is_shown_escaped() {
549 let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
550 sh.error("unknown `\x1b]0;x\x07`\r\n\tbelow\u{9b}\x7f\rend");
551 sh.status("Compiling", "a\x1b[2Jb");
552 assert_eq!(
553 out.text(),
554 "\x1b[1;31merror\x1b[0m: unknown `\\x1b]0;x\\x07`\r\n\tbelow\\u{9b}\\x7f\\x0dend\n\
555 \x1b[1;32m Compiling\x1b[0m a\\x1b[2Jb\n"
556 );
557 }
558
559 #[test]
565 fn a_tools_output_is_written_escaped() {
566 let output = b"\x1b[1mwarning\x1b[0m\x1b]0;x\x07\n";
567 let written = |choice, asked| {
568 let (mut sh, out) = shell(Some(choice), &[], false);
569 sh.tool_output(output, asked);
570 out.text()
571 };
572 assert_eq!(
573 written(ColorChoice::Always, true),
574 "\x1b[1mwarning\x1b[0m\\x1b]0;x\\x07\n"
575 );
576 let escaped = "\\x1b[1mwarning\\x1b[0m\\x1b]0;x\\x07\n";
577 assert_eq!(written(ColorChoice::Always, false), escaped);
578 assert_eq!(written(ColorChoice::Never, true), escaped);
579 }
580
581 #[test]
584 fn lines_with_color_paint_only_the_label() {
585 let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
586 sh.error("e");
587 sh.help("h");
588 sh.warning("w");
589 sh.status("Compiling", "m");
590 assert_eq!(
591 out.text(),
592 "\x1b[1;31merror\x1b[0m: e\n\
593 \x1b[1;36mhelp\x1b[0m: h\n\
594 \x1b[1;33mwarning\x1b[0m: w\n\
595 \x1b[1;32m Compiling\x1b[0m m\n"
596 );
597 }
598
599 #[test]
603 fn color_follows_the_choice_the_terminal_and_no_color() {
604 let on =
605 |choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
606 let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
607 assert!(on(None, &[], true));
610 assert!(!on(None, &[], false));
611 assert!(!on(None, no_color, true));
612 assert!(on(Some(ColorChoice::Auto), no_color, true));
614 assert!(!on(Some(ColorChoice::Auto), &[], false));
615 assert!(on(Some(ColorChoice::Always), no_color, false));
616 assert!(!on(Some(ColorChoice::Never), &[], true));
617 }
618
619 #[test]
625 fn colors_follows_the_order() {
626 use ColorChoice::{Always, Auto, Never};
627 assert!(colors(Some(Always), Some(Never), true, false));
629 assert!(!colors(Some(Never), Some(Always), false, true));
630 assert!(colors(None, Some(Always), true, false));
631 assert!(!colors(None, Some(Never), false, true));
632 assert!(colors(Some(Auto), None, true, true));
634 assert!(!colors(Some(Auto), Some(Always), false, false));
635 assert!(colors(None, Some(Auto), true, true));
636 assert!(!colors(None, None, true, true));
638 assert!(colors(None, None, false, true));
639 assert!(!colors(None, None, false, false));
640 }
641
642 #[test]
648 fn the_configured_choice_ranks_between_the_flag_and_no_color() {
649 let on = |given, configured, env: &[(&str, &str)], terminal| {
650 let mut shell = shell(given, env, terminal).0;
651 shell.configure(configured, false);
652 shell.uses_color()
653 };
654 let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
655 let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
656 assert!(on(None, always, no_color, false));
657 assert!(!on(None, never, &[], true));
658 assert!(on(None, Some(ColorChoice::Auto), no_color, true));
659 assert!(!on(never, always, &[], true));
660 assert!(on(always, never, &[], false));
661 assert!(!on(None, None, no_color, true));
662 assert!(on(None, None, &[], true));
663 }
664}