nextest_runner/reporter/
helpers.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use bstr::ByteSlice;
5use owo_colors::Style;
6
7/// Given a slice, find the index of the point at which highlighting should end.
8///
9/// Returns a value in the range [0, slice.len()].
10pub fn highlight_end(slice: &[u8]) -> usize {
11    // We want to highlight the first two lines of the output.
12    let mut iter = slice.find_iter(b"\n");
13    match iter.next() {
14        Some(_) => {
15            match iter.next() {
16                Some(second) => second,
17                // No second newline found, so highlight the entire slice.
18                None => slice.len(),
19            }
20        }
21        // No newline found, so highlight the entire slice.
22        None => slice.len(),
23    }
24}
25
26#[derive(Debug, Default)]
27pub(super) struct Styles {
28    pub(super) is_colorized: bool,
29    pub(super) count: Style,
30    pub(super) pass: Style,
31    pub(super) retry: Style,
32    pub(super) fail: Style,
33    pub(super) skip: Style,
34    pub(super) script_id: Style,
35    pub(super) list_styles: crate::list::Styles,
36}
37
38impl Styles {
39    pub(super) fn colorize(&mut self) {
40        self.is_colorized = true;
41        self.count = Style::new().bold();
42        self.pass = Style::new().green().bold();
43        self.retry = Style::new().magenta().bold();
44        self.fail = Style::new().red().bold();
45        self.skip = Style::new().yellow().bold();
46        self.script_id = Style::new().blue().bold();
47        self.list_styles.colorize();
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_highlight_end() {
57        let tests: &[(&str, usize)] = &[
58            ("", 0),
59            ("\n", 1),
60            ("foo", 3),
61            ("foo\n", 4),
62            ("foo\nbar", 7),
63            ("foo\nbar\n", 7),
64            ("foo\nbar\nbaz", 7),
65            ("foo\nbar\nbaz\n", 7),
66            ("\nfoo\nbar\nbaz", 4),
67        ];
68
69        for (input, output) in tests {
70            assert_eq!(
71                highlight_end(input.as_bytes()),
72                *output,
73                "for input {input:?}"
74            );
75        }
76    }
77}