hakari/verify/
display.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::verify::VerifyErrors;
use indenter::indented;
use owo_colors::{OwoColorize, Style};
use std::fmt::{self, Write};

/// A display formatter for [`VerifyErrors`].
///
/// Requires the `cli-support` feature.
#[derive(Clone, Debug)]
pub struct VerifyErrorsDisplay<'g, 'verify> {
    verify: &'verify VerifyErrors<'g>,
    styles: Styles,
    color: bool,
}

impl<'g, 'verify> VerifyErrorsDisplay<'g, 'verify> {
    pub(super) fn new(verify: &'verify VerifyErrors<'g>) -> Self {
        Self {
            verify,
            styles: Styles::default(),
            color: false,
        }
    }

    /// Adds ANSI color codes to the output.
    pub fn colorize(&mut self) -> &mut Self {
        self.styles.colorize();
        self.color = true;
        self
    }
}

impl<'g, 'verify> fmt::Display for VerifyErrorsDisplay<'g, 'verify> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for explain in self.verify.errors() {
            writeln!(
                f,
                "for dependency {}:\n",
                explain
                    .dependency()
                    .id()
                    .style(self.styles.dependency_id_style)
            )?;
            let mut display = explain.display();
            if self.color {
                display.colorize();
            }
            write!(indented(f).with_str("  "), "{}", display)?;
        }

        Ok(())
    }
}

#[derive(Clone, Debug, Default)]
struct Styles {
    dependency_id_style: Style,
}

impl Styles {
    fn colorize(&mut self) {
        self.dependency_id_style = Style::new().bright_magenta();
    }
}