Skip to main content

snapbox/report/
color.rs

1#[derive(Copy, Clone, Debug, Default)]
2pub struct Palette {
3    pub(crate) info: Style,
4    pub(crate) warn: Style,
5    pub(crate) error: Style,
6    pub(crate) hint: Style,
7    pub(crate) expected: Style,
8    pub(crate) actual: Style,
9}
10
11impl Palette {
12    pub fn color() -> Self {
13        if cfg!(feature = "color") {
14            Self {
15                info: anstyle::AnsiColor::Green.on_default(),
16                warn: anstyle::AnsiColor::Yellow.on_default(),
17                error: anstyle::AnsiColor::Red.on_default(),
18                hint: anstyle::Effects::DIMMED.into(),
19                expected: anstyle::AnsiColor::Red.on_default() | anstyle::Effects::UNDERLINE,
20                actual: anstyle::AnsiColor::Green.on_default() | anstyle::Effects::UNDERLINE,
21            }
22        } else {
23            Self::plain()
24        }
25    }
26
27    pub fn plain() -> Self {
28        Self::default()
29    }
30
31    pub fn info<D: std::fmt::Display>(self, item: D) -> Styled<D> {
32        Styled::new(item, self.info)
33    }
34
35    pub fn warn<D: std::fmt::Display>(self, item: D) -> Styled<D> {
36        Styled::new(item, self.warn)
37    }
38
39    pub fn error<D: std::fmt::Display>(self, item: D) -> Styled<D> {
40        Styled::new(item, self.error)
41    }
42
43    pub fn hint<D: std::fmt::Display>(self, item: D) -> Styled<D> {
44        Styled::new(item, self.hint)
45    }
46
47    pub fn expected<D: std::fmt::Display>(self, item: D) -> Styled<D> {
48        Styled::new(item, self.expected)
49    }
50
51    pub fn actual<D: std::fmt::Display>(self, item: D) -> Styled<D> {
52        Styled::new(item, self.actual)
53    }
54}
55
56pub(crate) use anstyle::Style;
57
58#[derive(Debug)]
59pub struct Styled<D> {
60    display: D,
61    style: Style,
62}
63
64impl<D: std::fmt::Display> Styled<D> {
65    pub(crate) fn new(display: D, style: Style) -> Self {
66        Self { display, style }
67    }
68}
69
70impl<D: std::fmt::Display> std::fmt::Display for Styled<D> {
71    #[inline]
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{}", self.style.render())?;
74        self.display.fmt(f)?;
75        write!(f, "{}", self.style.render_reset())?;
76        Ok(())
77    }
78}