|
| 1 | +use std::env; |
| 2 | +use std::io::Write; |
| 3 | + |
| 4 | +use libs::atty; |
| 5 | +use libs::once_cell::sync::Lazy; |
| 6 | +use libs::termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; |
| 7 | + |
| 8 | +/// Termcolor color choice. |
| 9 | +/// We do not rely on ColorChoice::Auto behavior |
| 10 | +/// as the check is already performed by has_color. |
| 11 | +static COLOR_CHOICE: Lazy<ColorChoice> = |
| 12 | + Lazy::new(|| if has_color() { ColorChoice::Always } else { ColorChoice::Never }); |
| 13 | + |
| 14 | +pub fn info(message: &str) { |
| 15 | + colorize(message, ColorSpec::new().set_bold(true), StandardStream::stdout(*COLOR_CHOICE)); |
| 16 | +} |
| 17 | + |
| 18 | +pub fn warn(message: &str) { |
| 19 | + colorize( |
| 20 | + &format!("{}{}", "Warning: ", message), |
| 21 | + ColorSpec::new().set_bold(true).set_fg(Some(Color::Yellow)), |
| 22 | + StandardStream::stdout(*COLOR_CHOICE), |
| 23 | + ); |
| 24 | +} |
| 25 | + |
| 26 | +pub fn success(message: &str) { |
| 27 | + colorize( |
| 28 | + message, |
| 29 | + ColorSpec::new().set_bold(true).set_fg(Some(Color::Green)), |
| 30 | + StandardStream::stdout(*COLOR_CHOICE), |
| 31 | + ); |
| 32 | +} |
| 33 | + |
| 34 | +pub fn error(message: &str) { |
| 35 | + colorize( |
| 36 | + &format!("{}{}", "Error: ", message), |
| 37 | + ColorSpec::new().set_bold(true).set_fg(Some(Color::Red)), |
| 38 | + StandardStream::stderr(*COLOR_CHOICE), |
| 39 | + ); |
| 40 | +} |
| 41 | + |
| 42 | +/// Print a colorized message to stdout |
| 43 | +fn colorize(message: &str, color: &ColorSpec, mut stream: StandardStream) { |
| 44 | + stream.set_color(color).unwrap(); |
| 45 | + write!(stream, "{}", message).unwrap(); |
| 46 | + stream.set_color(&ColorSpec::new()).unwrap(); |
| 47 | + writeln!(stream).unwrap(); |
| 48 | +} |
| 49 | + |
| 50 | +/// Check whether to output colors |
| 51 | +fn has_color() -> bool { |
| 52 | + let use_colors = env::var("CLICOLOR").unwrap_or_else(|_| "1".to_string()) != "0" |
| 53 | + && env::var("NO_COLOR").is_err(); |
| 54 | + let force_colors = env::var("CLICOLOR_FORCE").unwrap_or_else(|_| "0".to_string()) != "0"; |
| 55 | + |
| 56 | + force_colors || use_colors && atty::is(atty::Stream::Stdout) |
| 57 | +} |
0 commit comments