use std::borrow::Cow;
use std::fmt::Display;
use std::io::Write;
use crate::Env;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorChoice {
Auto,
Always,
Never,
}
const RESET: &str = "\x1b[0m";
const BOLD_RED: &str = "\x1b[1;31m";
const BOLD_YELLOW: &str = "\x1b[1;33m";
const BOLD_CYAN: &str = "\x1b[1;36m";
const BOLD_GREEN: &str = "\x1b[1;32m";
pub fn colors(
given: Option<ColorChoice>,
configured: Option<ColorChoice>,
no_color: bool,
terminal: bool,
) -> bool {
match given.or(configured) {
Some(ColorChoice::Always) => true,
Some(ColorChoice::Never) => false,
Some(ColorChoice::Auto) => terminal,
None => terminal && !no_color,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Verbosity {
Quiet,
#[default]
Normal,
Verbose,
}
pub struct Shell {
out: Box<dyn Write>,
given: Option<ColorChoice>,
no_color: bool,
terminal: bool,
color: bool,
verbosity: Verbosity,
}
impl Shell {
pub fn new(
out: Box<dyn Write>,
choice: Option<ColorChoice>,
env: &Env,
out_is_terminal: bool,
) -> Shell {
let mut shell = Shell {
out,
given: choice,
no_color: env.get("NO_COLOR").is_some(),
terminal: out_is_terminal,
color: false,
verbosity: Verbosity::Normal,
};
shell.configure(None, false);
shell
}
pub fn configure(&mut self, configured: Option<ColorChoice>, verbose: bool) {
self.color = colors(self.given, configured, self.no_color, self.terminal);
if verbose && self.verbosity == Verbosity::Normal {
self.verbosity = Verbosity::Verbose;
}
}
pub fn set_verbosity(&mut self, verbosity: Verbosity) {
self.verbosity = verbosity;
}
pub fn verbose(&self) -> bool {
self.verbosity == Verbosity::Verbose
}
pub fn uses_color(&self) -> bool {
self.color
}
pub fn error(&mut self, message: impl Display) {
self.line(BOLD_RED, "error", message);
}
pub fn warning(&mut self, message: impl Display) {
self.line(BOLD_YELLOW, "warning", message);
}
pub fn help(&mut self, message: impl Display) {
self.line(BOLD_CYAN, "help", message);
}
pub fn status(&mut self, verb: &str, message: impl Display) {
if self.verbosity == Verbosity::Quiet {
return;
}
let verb = self.paint(BOLD_GREEN, &format!("{verb:>12}"));
let message = message.to_string();
let message = escaped_text(&message);
self.write(format_args!("{verb} {message}"));
}
pub fn raw(&mut self, bytes: &[u8]) {
let _ = self.out.write_all(bytes);
let _ = self.out.flush();
}
pub fn tool_output(&mut self, bytes: &[u8], asked: bool) {
let shown = escaped(bytes, asked && self.color);
self.raw(&shown);
}
fn line(&mut self, style: &str, label: &str, message: impl Display) {
let label = self.paint(style, label);
let message = message.to_string();
let message = escaped_text(&message);
self.write(format_args!("{label}: {message}"));
}
fn write(&mut self, line: std::fmt::Arguments<'_>) {
let _ = writeln!(self.out, "{line}");
}
fn paint(&self, style: &str, text: &str) -> String {
if self.color {
format!("{style}{text}{RESET}")
} else {
text.to_owned()
}
}
}
fn escaped(bytes: &[u8], color: bool) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let byte = bytes[i];
let kept = match byte {
b'\n' | b'\t' => 1,
b'\r' if bytes.get(i + 1) == Some(&b'\n') => 1,
0x1b if color => color_sequence(&bytes[i..]),
0x00..=0x1f | 0x7f => 0,
_ => 1,
};
if kept == 0 {
out.extend(format!("\\x{byte:02x}").bytes());
i += 1;
} else {
out.extend(&bytes[i..i + kept]);
i += kept;
}
}
out
}
pub fn without_color(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
let color = if bytes[i] == 0x1b {
color_sequence(&bytes[i..])
} else {
0
};
if color == 0 {
out.push(bytes[i]);
i += 1;
} else {
i += color;
}
}
out
}
fn color_sequence(bytes: &[u8]) -> usize {
if bytes.get(1) != Some(&b'[') {
return 0;
}
let length = bytes[2..]
.iter()
.take_while(|b| b.is_ascii_digit() || **b == b';' || **b == b':')
.count();
let parameters = &bytes[2..2 + length];
let shown = match bytes.get(2 + length) {
Some(b'm') => styles_shown_text(parameters),
Some(b'K') => matches!(parameters, b"" | b"0"),
_ => false,
};
if shown { 2 + length + 1 } else { 0 }
}
fn styles_shown_text(parameters: &[u8]) -> bool {
let mut codes = parameters.split(|b| *b == b';' || *b == b':').map(|code| {
if code.is_empty() {
Some(0)
} else {
std::str::from_utf8(code).ok()?.parse::<u32>().ok()
}
});
while let Some(code) = codes.next() {
match code {
Some(0 | 1 | 3 | 4 | 22 | 23 | 24 | 39 | 30..=37 | 90..=97) => {}
Some(38) => {
let numbers = match codes.next() {
Some(Some(5)) => 1,
Some(Some(2)) => 3,
_ => return false,
};
for _ in 0..numbers {
if !matches!(codes.next(), Some(Some(0..=255))) {
return false;
}
}
}
_ => return false,
}
}
true
}
fn escaped_text(text: &str) -> Cow<'_, str> {
let plain = |c: char| !c.is_control() || c == '\n' || c == '\t';
if text.chars().all(plain) {
return Cow::Borrowed(text);
}
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
c if plain(c) => out.push(c),
'\r' if chars.peek() == Some(&'\n') => out.push(c),
c if (c as u32) < 0x80 => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
}
}
Cow::Owned(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::env::NameCase;
use std::sync::{Arc, Mutex};
#[derive(Clone, Default)]
struct Captured(Arc<Mutex<Vec<u8>>>);
impl Write for Captured {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Captured {
fn text(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
fn shell(
choice: Option<ColorChoice>,
env: &[(&str, &str)],
terminal: bool,
) -> (Shell, Captured) {
let out = Captured::default();
let env = Env::from_pairs(
env.iter().map(|(n, v)| (n.into(), v.into())),
NameCase::Sensitive,
);
(
Shell::new(Box::new(out.clone()), choice, &env, terminal),
out,
)
}
#[test]
fn configured_verbose_ranks_below_the_command_line() {
let (fresh, _) = shell(Some(ColorChoice::Never), &[], false);
assert!(!fresh.verbose());
for (given, configured, verbose, quiet) in [
(Verbosity::Normal, true, true, false),
(Verbosity::Normal, false, false, false),
(Verbosity::Quiet, true, false, true),
(Verbosity::Verbose, false, true, false),
] {
let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
sh.set_verbosity(given);
sh.configure(None, configured);
assert_eq!(sh.verbose(), verbose, "{given:?}, configured {configured}");
sh.status("Compiling", "app");
assert_eq!(
out.text().is_empty(),
quiet,
"{given:?}, configured {configured}"
);
}
}
#[test]
fn quiet_leaves_out_status_lines_only() {
let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
sh.set_verbosity(Verbosity::Quiet);
sh.status("Compiling", "mygame v0.1.0");
sh.error("no compiler found");
sh.help("install Build Tools");
sh.warning("unused key");
sh.raw(
b"main.cpp(1): note
",
);
assert_eq!(
out.text(),
"error: no compiler found
help: install Build Tools
warning: unused key
main.cpp(1): note
"
);
}
#[test]
fn lines_without_color() {
let (mut sh, out) = shell(Some(ColorChoice::Never), &[], false);
sh.error("no compiler found");
sh.help("install Build Tools");
sh.warning("unused key");
sh.status("Compiling", "mygame v0.1.0");
assert_eq!(
out.text(),
"error: no compiler found\nhelp: install Build Tools\nwarning: unused key\n Compiling mygame v0.1.0\n"
);
}
#[test]
fn raw_output_is_written_as_produced() {
let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
let cp932 = [0x83, 0x81, 0x83, 0x82, 0x0d, 0x0a];
sh.raw(&cp932);
sh.raw(b"x");
assert_eq!(*out.0.lock().unwrap(), [&cp932[..], b"x"].concat());
}
#[test]
fn a_tools_control_characters_are_shown_escaped() {
let cp932 = [0x83, 0x5c, 0x88, 0x9f];
let mut bytes = b"a\tb\r\nc\x1b]0;x\x07d\re\x00\x7f\x0bf".to_vec();
bytes.extend(cp932);
bytes.push(b'\r');
let mut expected = b"a\tb\r\nc\\x1b]0;x\\x07d\\x0de\\x00\\x7f\\x0bf".to_vec();
expected.extend(cp932);
expected.extend(b"\\x0d");
assert_eq!(escaped(&bytes, false), expected);
assert_eq!(escaped(&bytes, true), expected);
}
#[test]
fn only_color_that_shows_text_passes() {
for kept in [
&b"\x1b[1;31merror\x1b[0m: x"[..],
b"\x1b[01;35m\x1b[Kwarning: \x1b[m\x1b[K",
b"\x1b[0;1;36mnote\x1b[0m",
b"\x1b[38;5;1mx\x1b[38:2:1:2:3mx\x1b[39m",
] {
assert_eq!(escaped(kept, true), kept);
}
assert_eq!(
escaped(b"\x1b[1;31merror\x1b[0m: x", false),
b"\\x1b[1;31merror\\x1b[0m: x".to_vec()
);
for (hiding, shown) in [
(&b"\x1b[8mx"[..], &b"\\x1b[8mx"[..]),
(b"\x1b[30;40mx", b"\\x1b[30;40mx"),
(b"\x1b[7mx", b"\\x1b[7mx"),
(b"\x1b[5mx", b"\\x1b[5mx"),
(b"\x1b[38;5mx", b"\\x1b[38;5mx"),
(b"\x1b[2J\x1b[?25l", b"\\x1b[2J\\x1b[?25l"),
(b"\x1b[?1m", b"\\x1b[?1m"),
(b"\x1b[2K", b"\\x1b[2K"),
(b"\x1b[", b"\\x1b["),
] {
assert_eq!(escaped(hiding, true), shown);
}
}
#[test]
fn taking_color_out_keeps_what_is_not_color() {
assert_eq!(
without_color(b"\x1b[1ma.cpp:1:1: \x1b[0;1;35mwarning: \x1b[0mx\x1b[K\n"),
b"a.cpp:1:1: warning: x\n"
);
assert_eq!(
without_color(b"a \x1b[2J b \x1b[8mhidden\x1b[0m c"),
b"a \x1b[2J b \x1b[8mhidden c"
);
assert_eq!(without_color(b"lone \x1b here"), b"lone \x1b here");
}
#[test]
fn a_value_in_a_message_is_shown_escaped() {
let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
sh.error("unknown `\x1b]0;x\x07`\r\n\tbelow\u{9b}\x7f\rend");
sh.status("Compiling", "a\x1b[2Jb");
assert_eq!(
out.text(),
"\x1b[1;31merror\x1b[0m: unknown `\\x1b]0;x\\x07`\r\n\tbelow\\u{9b}\\x7f\\x0dend\n\
\x1b[1;32m Compiling\x1b[0m a\\x1b[2Jb\n"
);
}
#[test]
fn a_tools_output_is_written_escaped() {
let output = b"\x1b[1mwarning\x1b[0m\x1b]0;x\x07\n";
let written = |choice, asked| {
let (mut sh, out) = shell(Some(choice), &[], false);
sh.tool_output(output, asked);
out.text()
};
assert_eq!(
written(ColorChoice::Always, true),
"\x1b[1mwarning\x1b[0m\\x1b]0;x\\x07\n"
);
let escaped = "\\x1b[1mwarning\\x1b[0m\\x1b]0;x\\x07\n";
assert_eq!(written(ColorChoice::Always, false), escaped);
assert_eq!(written(ColorChoice::Never, true), escaped);
}
#[test]
fn lines_with_color_paint_only_the_label() {
let (mut sh, out) = shell(Some(ColorChoice::Always), &[], false);
sh.error("e");
sh.help("h");
sh.warning("w");
sh.status("Compiling", "m");
assert_eq!(
out.text(),
"\x1b[1;31merror\x1b[0m: e\n\
\x1b[1;36mhelp\x1b[0m: h\n\
\x1b[1;33mwarning\x1b[0m: w\n\
\x1b[1;32m Compiling\x1b[0m m\n"
);
}
#[test]
fn color_follows_the_choice_the_terminal_and_no_color() {
let on =
|choice, env: &[(&str, &str)], terminal| shell(choice, env, terminal).0.uses_color();
let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
assert!(on(None, &[], true));
assert!(!on(None, &[], false));
assert!(!on(None, no_color, true));
assert!(on(Some(ColorChoice::Auto), no_color, true));
assert!(!on(Some(ColorChoice::Auto), &[], false));
assert!(on(Some(ColorChoice::Always), no_color, false));
assert!(!on(Some(ColorChoice::Never), &[], true));
}
#[test]
fn colors_follows_the_order() {
use ColorChoice::{Always, Auto, Never};
assert!(colors(Some(Always), Some(Never), true, false));
assert!(!colors(Some(Never), Some(Always), false, true));
assert!(colors(None, Some(Always), true, false));
assert!(!colors(None, Some(Never), false, true));
assert!(colors(Some(Auto), None, true, true));
assert!(!colors(Some(Auto), Some(Always), false, false));
assert!(colors(None, Some(Auto), true, true));
assert!(!colors(None, None, true, true));
assert!(colors(None, None, false, true));
assert!(!colors(None, None, false, false));
}
#[test]
fn the_configured_choice_ranks_between_the_flag_and_no_color() {
let on = |given, configured, env: &[(&str, &str)], terminal| {
let mut shell = shell(given, env, terminal).0;
shell.configure(configured, false);
shell.uses_color()
};
let no_color: &[(&str, &str)] = &[("NO_COLOR", "")];
let (always, never) = (Some(ColorChoice::Always), Some(ColorChoice::Never));
assert!(on(None, always, no_color, false));
assert!(!on(None, never, &[], true));
assert!(on(None, Some(ColorChoice::Auto), no_color, true));
assert!(!on(never, always, &[], true));
assert!(on(always, never, &[], false));
assert!(!on(None, None, no_color, true));
assert!(on(None, None, &[], true));
}
}