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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#![cfg(feature = "color")]

use std::fmt;

use super::strings::indent_vec;
use super::{Format, OutputStyle};

// Disable colors and text styles if stderr is not a tty.
fn check_disable_color() {
    if atty::isnt(atty::Stream::Stderr) {
        colored::control::set_override(false)
    }
}

#[derive(Debug, Default)]
struct OutputSegment {
    buf: String,
    style: OutputStyle,
}

/// Configuration for formatting with [`Format`].
///
/// This value is passed to [`Format::fmt`] and is used to set various options to configure how the
/// value will be formatted.
///
/// [`Format::fmt`]: crate::core::Format::fmt
#[derive(Debug)]
pub struct Formatter {
    prev: Vec<OutputSegment>,
    current: OutputSegment,
}

impl Formatter {
    fn new() -> Self {
        Self {
            prev: Vec::new(),
            current: Default::default(),
        }
    }

    /// Write a string to the output.
    pub fn write_str(&mut self, s: impl AsRef<str>) {
        self.current.buf.push_str(s.as_ref());
    }

    /// Write a `char` to the output.
    pub fn write_char(&mut self, c: char) {
        self.current.buf.push(c);
    }

    /// Pass some pre-formatted output through to the output.
    ///
    /// This method is often used when writing formatters for matchers which compose other
    /// matchers, such as [`not`] or [`each`]. It's used by formatters such as [`FailureFormat`]
    /// and [`SomeFailuresFormat`].
    ///
    /// [`not`]: crate::not
    /// [`each`]: crate::each
    /// [`FailureFormat`]: crate::format::FailureFormat
    /// [`SomeFailuresFormat`]: crate::format::SomeFailuresFormat
    pub fn write_fmt(&mut self, output: impl Into<FormattedOutput>) {
        let formatted = output.into();
        let new_current = OutputSegment {
            buf: String::new(),
            style: self.current.style.clone(),
        };
        self.prev
            .push(std::mem::replace(&mut self.current, new_current));
        self.prev.extend(formatted.segments);
    }

    /// Get the current [`OutputStyle`].
    pub fn style(&self) -> &OutputStyle {
        &self.current.style
    }

    /// Set the current [`OutputStyle`].
    ///
    /// This is used to configure colors and text styles in the output. Output formatting is
    /// stripped out when stderr is not a tty.
    pub fn set_style(&mut self, style: OutputStyle) {
        self.prev.push(std::mem::replace(
            &mut self.current,
            OutputSegment {
                buf: String::new(),
                style,
            },
        ));
    }

    /// Reset the current colors and text styles to their defaults.
    pub fn reset_style(&mut self) {
        self.set_style(Default::default());
    }
}

/// A value that has been formatted with [`Format`].
///
/// Formatting a value with [`Format`] returns this opaque type rather than a string, since we need
/// to encapsulate the colors and text styles information in a cross-platform way. While ANSI escape
/// codes can be included in a string, other platforms (such as Windows) have their own mechanisms
/// for including colors and text styles in stdout/stderr.
#[derive(Debug)]
pub struct FormattedOutput {
    segments: Vec<OutputSegment>,
}

impl FormattedOutput {
    /// Create a new [`FormattedOutput`] by formatting `value` with `format`.
    pub fn new<Value, Fmt>(value: Value, format: Fmt) -> crate::Result<Self>
    where
        Fmt: Format<Value = Value>,
    {
        let mut formatter = Formatter::new();
        format.fmt(&mut formatter, value)?;
        let mut segments = formatter.prev;
        segments.push(formatter.current);
        Ok(Self { segments })
    }

    fn indented_inner(self, spaces: u32, hanging: bool) -> Self {
        if spaces == 0 {
            return self;
        }

        let mut styles = Vec::with_capacity(self.segments.len());
        let mut buffers = Vec::with_capacity(self.segments.len());

        for segment in self.segments {
            styles.push(segment.style);
            buffers.push(segment.buf);
        }

        Self {
            segments: indent_vec(buffers, spaces, hanging)
                .into_iter()
                .zip(styles)
                .map(|(buf, style)| OutputSegment { buf, style })
                .collect(),
        }
    }

    /// Return a new [`FormattedOutput`] which has been indented by the given number of spaces.
    ///
    /// Also see [`FormattedFailure::into_indented`].
    ///
    /// [`FormattedFailure::into_indented`]: crate::core::FormattedFailure::into_indented
    pub fn indented(self, spaces: u32) -> Self {
        self.indented_inner(spaces, false)
    }

    /// Panic with this output as the error message.
    ///
    /// This does not print colors or text styles when the [`NO_COLOR`](https://no-color.org/)
    /// environment variable is set or when stderr is not a tty.
    pub fn fail(&self) -> ! {
        check_disable_color();
        panic!("\n{}\n", self);
    }
}

impl fmt::Display for FormattedOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for segment in &self.segments {
            f.write_fmt(format_args!("{}", segment.style.apply(&segment.buf)))?;
        }

        Ok(())
    }
}