1 use std::io::Write; 2 use termcolor::{Color, ColorSpec, WriteColor}; 3 4 #[derive(Clone, Debug, Default)] 5 pub(crate) struct Palette { 6 description: ColorSpec, 7 var: ColorSpec, 8 expected: ColorSpec, 9 } 10 11 impl Palette { new(alternate: bool) -> Self12 pub(crate) fn new(alternate: bool) -> Self { 13 if alternate && cfg!(feature = "color") { 14 Self { 15 description: ColorSpec::new() 16 .set_fg(Some(Color::Blue)) 17 .set_bold(true) 18 .clone(), 19 var: ColorSpec::new() 20 .set_fg(Some(Color::Red)) 21 .set_bold(true) 22 .clone(), 23 expected: ColorSpec::new() 24 .set_fg(Some(Color::Green)) 25 .set_bold(true) 26 .clone(), 27 } 28 } else { 29 Self::plain() 30 } 31 } 32 plain() -> Self33 pub(crate) fn plain() -> Self { 34 Self { 35 description: Default::default(), 36 var: Default::default(), 37 expected: Default::default(), 38 } 39 } 40 description<D: std::fmt::Display>(&self, display: D) -> Styled<D>41 pub(crate) fn description<D: std::fmt::Display>(&self, display: D) -> Styled<D> { 42 Styled::new(display, self.description.clone()) 43 } 44 var<D: std::fmt::Display>(&self, display: D) -> Styled<D>45 pub(crate) fn var<D: std::fmt::Display>(&self, display: D) -> Styled<D> { 46 Styled::new(display, self.var.clone()) 47 } 48 expected<D: std::fmt::Display>(&self, display: D) -> Styled<D>49 pub(crate) fn expected<D: std::fmt::Display>(&self, display: D) -> Styled<D> { 50 Styled::new(display, self.expected.clone()) 51 } 52 } 53 54 #[derive(Debug)] 55 pub(crate) struct Styled<D> { 56 display: D, 57 style: ColorSpec, 58 } 59 60 impl<D: std::fmt::Display> Styled<D> { new(display: D, style: ColorSpec) -> Self61 pub(crate) fn new(display: D, style: ColorSpec) -> Self { 62 Self { display, style } 63 } 64 } 65 66 impl<D: std::fmt::Display> std::fmt::Display for Styled<D> { 67 #[inline] fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 69 if f.alternate() { 70 let mut buf = termcolor::Buffer::ansi(); 71 buf.set_color(&self.style).unwrap(); 72 write!(&mut buf, "{}", &self.display).unwrap(); 73 buf.reset().unwrap(); 74 write!(f, "{}", String::from_utf8(buf.into_inner()).unwrap()) 75 } else { 76 self.display.fmt(f) 77 } 78 } 79 } 80