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}"));
self.write(format_args!("{verb} {message}"));
}
pub fn raw(&mut self, bytes: &[u8]) {
let _ = self.out.write_all(bytes);
let _ = self.out.flush();
}
fn line(&mut self, style: &str, label: &str, message: impl Display) {
let label = self.paint(style, label);
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()
}
}
}
#[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 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));
}
}