refactor(color): Track style, rather than details

This makes it easier for us to compose.  Before, we had to infer things
like "bold" based on the color.  Now we just say "error" and get all of
the formatting specific to that.
This commit is contained in:
Ed Page 2021-11-24 10:49:57 -06:00
parent afa7346f74
commit 463d75474e
2 changed files with 45 additions and 33 deletions

View file

@ -1,28 +1,15 @@
use crate::util::color::{Color, ColorChoice};
use crate::util::color::ColorChoice;
use std::{
fmt::{self, Display, Formatter},
io::{self, Write},
};
#[cfg(feature = "color")]
fn is_a_tty(stderr: bool) -> bool {
debug!("is_a_tty: stderr={:?}", stderr);
let stream = if stderr {
atty::Stream::Stderr
} else {
atty::Stream::Stdout
};
atty::is(stream)
}
#[derive(Clone, Debug)]
pub(crate) struct Colorizer {
use_stderr: bool,
color_when: ColorChoice,
pieces: Vec<(String, Option<Color>)>,
pieces: Vec<(String, Style)>,
}
impl Colorizer {
@ -37,22 +24,22 @@ impl Colorizer {
#[inline]
pub(crate) fn good(&mut self, msg: impl Into<String>) {
self.pieces.push((msg.into(), Some(Color::Green)));
self.pieces.push((msg.into(), Style::Good));
}
#[inline]
pub(crate) fn warning(&mut self, msg: impl Into<String>) {
self.pieces.push((msg.into(), Some(Color::Yellow)));
self.pieces.push((msg.into(), Style::Warning));
}
#[inline]
pub(crate) fn error(&mut self, msg: impl Into<String>) {
self.pieces.push((msg.into(), Some(Color::Red)));
self.pieces.push((msg.into(), Style::Error));
}
#[inline]
pub(crate) fn none(&mut self, msg: impl Into<String>) {
self.pieces.push((msg.into(), None));
self.pieces.push((msg.into(), Style::Default));
}
}
@ -78,10 +65,19 @@ impl Colorizer {
for piece in &self.pieces {
let mut color = ColorSpec::new();
color.set_fg(piece.1);
if piece.1 == Some(Color::Red) {
match piece.1 {
Style::Good => {
color.set_fg(Some(termcolor::Color::Green));
}
Style::Warning => {
color.set_fg(Some(termcolor::Color::Yellow));
}
Style::Error => {
color.set_fg(Some(termcolor::Color::Red));
color.set_bold(true);
}
Style::Default => {}
}
buffer.set_color(&color)?;
buffer.write_all(piece.0.as_bytes())?;
@ -117,3 +113,30 @@ impl Display for Colorizer {
Ok(())
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Style {
Good,
Warning,
Error,
Default,
}
impl Default for Style {
fn default() -> Self {
Self::Default
}
}
#[cfg(feature = "color")]
fn is_a_tty(stderr: bool) -> bool {
debug!("is_a_tty: stderr={:?}", stderr);
let stream = if stderr {
atty::Stream::Stderr
} else {
atty::Stream::Stdout
};
atty::is(stream)
}

View file

@ -60,14 +60,3 @@ impl Default for ColorChoice {
Self::Auto
}
}
#[cfg(feature = "color")]
pub(crate) use termcolor::Color;
#[cfg(not(feature = "color"))]
#[derive(Copy, Clone, Debug)]
pub(crate) enum Color {
Green,
Yellow,
Red,
}