cargo_nextest/
output.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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright (c) The nextest Contributors
// Copyright (c) The cargo-guppy Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use clap::{Args, ValueEnum};
use miette::{GraphicalTheme, MietteHandlerOpts, ThemeStyles};
use nextest_runner::{reporter::ReporterStderr, write_str::WriteStr};
use owo_colors::{style, OwoColorize, Style};
use std::{
    fmt,
    io::{self, BufWriter, Stderr, Stdout, Write},
    marker::PhantomData,
};
use tracing::{
    field::{Field, Visit},
    level_filters::LevelFilter,
    Event, Level, Subscriber,
};
use tracing_subscriber::{
    filter::Targets,
    fmt::{format, FmtContext, FormatEvent, FormatFields},
    layer::SubscriberExt,
    registry::LookupSpan,
    util::SubscriberInitExt,
    Layer,
};

pub(crate) mod clap_styles {
    use clap::builder::{
        styling::{AnsiColor, Effects, Style},
        Styles,
    };

    const HEADER: Style = AnsiColor::Green.on_default().effects(Effects::BOLD);
    const USAGE: Style = AnsiColor::Green.on_default().effects(Effects::BOLD);
    const LITERAL: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
    const PLACEHOLDER: Style = AnsiColor::Cyan.on_default();
    const ERROR: Style = AnsiColor::Red.on_default().effects(Effects::BOLD);
    const VALID: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
    const INVALID: Style = AnsiColor::Yellow.on_default().effects(Effects::BOLD);

    pub(crate) const fn style() -> Styles {
        // Copied from
        // https://github.com/rust-lang/cargo/blob/98f6bf3700e2918678acd87b7e1a1450df579853/src/bin/cargo/cli.rs#L552-L561
        // to match Cargo's style.
        Styles::styled()
            .header(HEADER)
            .usage(USAGE)
            .literal(LITERAL)
            .placeholder(PLACEHOLDER)
            .error(ERROR)
            .valid(VALID)
            .invalid(INVALID)
    }
}

#[derive(Copy, Clone, Debug, Args)]
#[must_use]
pub(crate) struct OutputOpts {
    /// Verbose output
    #[arg(long, short, global = true, env = "NEXTEST_VERBOSE")]
    pub(crate) verbose: bool,
    // TODO: quiet?
    /// Produce color output: auto, always, never
    #[arg(
        long,
        value_enum,
        default_value_t,
        hide_possible_values = true,
        global = true,
        value_name = "WHEN",
        env = "CARGO_TERM_COLOR"
    )]
    pub(crate) color: Color,
}

impl OutputOpts {
    pub(crate) fn init(self) -> OutputContext {
        let OutputOpts { verbose, color } = self;

        color.init();

        OutputContext { verbose, color }
    }
}

#[derive(Copy, Clone, Debug)]
#[must_use]
pub struct OutputContext {
    pub(crate) verbose: bool,
    pub(crate) color: Color,
}

impl OutputContext {
    // color_never_init is only used for double-spawning, which only exists on Unix platforms.
    #[cfg(unix)]
    pub(crate) fn color_never_init() -> Self {
        Color::Never.init();
        Self {
            verbose: false,
            color: Color::Never,
        }
    }

    /// Returns general stderr styles for the current output context.
    pub fn stderr_styles(&self) -> StderrStyles {
        let mut styles = StderrStyles::default();

        if self.color.should_colorize(supports_color::Stream::Stderr) {
            styles.colorize();
        }

        styles
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
#[must_use]
#[derive(Default)]
pub enum Color {
    #[default]
    Auto,
    Always,
    Never,
}

static INIT_LOGGER: std::sync::Once = std::sync::Once::new();

struct SimpleFormatter {
    styles: LogStyles,
}

impl<S, N> FormatEvent<S, N> for SimpleFormatter
where
    S: Subscriber + for<'a> LookupSpan<'a>,
    N: for<'a> FormatFields<'a> + 'static,
{
    fn format_event(
        &self,
        _ctx: &FmtContext<'_, S, N>,
        mut writer: format::Writer<'_>,
        event: &Event<'_>,
    ) -> fmt::Result {
        let metadata = event.metadata();

        if metadata.target() != "cargo_nextest::no_heading" {
            match *metadata.level() {
                Level::ERROR => {
                    write!(writer, "{}: ", "error".style(self.styles.error))?;
                }
                Level::WARN => {
                    write!(writer, "{}: ", "warning".style(self.styles.warning))?;
                }
                Level::INFO => {
                    write!(writer, "{}: ", "info".style(self.styles.info))?;
                }
                Level::DEBUG => {
                    write!(writer, "{}: ", "debug".style(self.styles.debug))?;
                }
                Level::TRACE => {
                    write!(writer, "{}: ", "trace".style(self.styles.trace))?;
                }
            }
        }

        let mut visitor = MessageVisitor {
            writer: &mut writer,
            // Show other fields for debug or trace output.
            show_other: *metadata.level() >= Level::DEBUG,
            error: None,
        };

        event.record(&mut visitor);

        if let Some(error) = visitor.error {
            return Err(error);
        }

        writeln!(writer)
    }
}

static MESSAGE_FIELD: &str = "message";

struct MessageVisitor<'writer, 'a> {
    writer: &'a mut format::Writer<'writer>,
    show_other: bool,
    error: Option<fmt::Error>,
}

impl Visit for MessageVisitor<'_, '_> {
    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        if field.name() == MESSAGE_FIELD {
            if let Err(error) = write!(self.writer, "{:?}", value) {
                self.error = Some(error);
            }
        } else if self.show_other {
            if let Err(error) = write!(self.writer, "; {} = {:?}", field.name(), value) {
                self.error = Some(error);
            }
        }
    }
}

impl Color {
    pub(crate) fn init(self) {
        // Pass the styles in as a stylesheet to ensure we use the latest supports-color here.
        let mut log_styles = LogStyles::default();
        if self.should_colorize(supports_color::Stream::Stderr) {
            log_styles.colorize();
        }

        INIT_LOGGER.call_once(|| {
            let level_str = std::env::var_os("NEXTEST_LOG").unwrap_or_default();
            let level_str = level_str
                .into_string()
                .unwrap_or_else(|_| panic!("NEXTEST_LOG is not UTF-8"));

            // If the level string is empty, use the standard level filter instead.
            let targets = if level_str.is_empty() {
                Targets::new().with_default(LevelFilter::INFO)
            } else {
                level_str.parse().expect("unable to parse NEXTEST_LOG")
            };

            let layer = tracing_subscriber::fmt::layer()
                .event_format(SimpleFormatter { styles: log_styles })
                .with_writer(std::io::stderr)
                .with_filter(targets);

            cfg_if::cfg_if! {
                if #[cfg(feature = "experimental-tokio-console")] {
                    let console_layer = nextest_runner::console::spawn();
                    tracing_subscriber::registry()
                        .with(layer)
                        .with(console_layer)
                        .init();
                } else {
                    tracing_subscriber::registry()
                        .with(layer)
                        .init();
                }
            }

            miette::set_hook(Box::new(move |_| {
                let theme_styles = if self.should_colorize(supports_color::Stream::Stderr) {
                    ThemeStyles {
                        error: style().red().bold(),
                        warning: style().yellow().bold(),
                        advice: style().bright_cyan().bold(),
                        help: style().cyan(),
                        link: style().cyan().underline().bold(),
                        linum: style().dimmed(),
                        highlights: vec![style().red(), style().yellow(), style().bright_cyan()],
                    }
                } else {
                    ThemeStyles::none()
                };
                let mut graphical_theme = if supports_unicode::on(supports_unicode::Stream::Stderr)
                {
                    GraphicalTheme::unicode()
                } else {
                    GraphicalTheme::ascii()
                };
                graphical_theme.characters.error = "error:".into();
                graphical_theme.styles = theme_styles;

                let handler = MietteHandlerOpts::new().graphical_theme(graphical_theme);
                Box::new(handler.build())
            }))
            .expect("miette::set_hook should only be called once");
        });
    }

    pub(crate) fn should_colorize(self, stream: supports_color::Stream) -> bool {
        match self {
            Color::Auto => supports_color::on_cached(stream).is_some(),
            Color::Always => true,
            Color::Never => false,
        }
    }

    pub(crate) fn to_arg(self) -> &'static str {
        match self {
            Color::Auto => "--color=auto",
            Color::Always => "--color=always",
            Color::Never => "--color=never",
        }
    }
}

#[derive(Debug, Default)]
struct LogStyles {
    error: Style,
    warning: Style,
    info: Style,
    debug: Style,
    trace: Style,
}

impl LogStyles {
    fn colorize(&mut self) {
        self.error = style().red().bold();
        self.warning = style().yellow().bold();
        self.info = style().bold();
        self.debug = style().bold();
        self.trace = style().dimmed();
    }
}

#[derive(Debug, Default)]
pub struct StderrStyles {
    pub(crate) bold: Style,
    pub(crate) warning_text: Style,
}

impl StderrStyles {
    fn colorize(&mut self) {
        self.bold = style().bold();
        self.warning_text = style().yellow();
    }
}

/// A helper for capturing output in tests
///
/// The test pass is gated by `#[cfg(test)]` to allow a better
/// optimization in the binary.
pub enum OutputWriter {
    /// No capture
    Normal,
    /// Output captured
    #[cfg(test)]
    Test {
        /// stdout capture
        stdout: Vec<u8>,
        /// stderr capture
        stderr: Vec<u8>,
    },
}

impl Default for OutputWriter {
    fn default() -> Self {
        Self::Normal
    }
}

impl OutputWriter {
    pub(crate) fn stdout_writer(&mut self) -> StdoutWriter<'_> {
        match self {
            Self::Normal => StdoutWriter::Normal {
                buf: BufWriter::new(std::io::stdout()),
                _lifetime: PhantomData,
            },
            #[cfg(test)]
            Self::Test { ref mut stdout, .. } => StdoutWriter::Test { buf: stdout },
        }
    }

    pub(crate) fn reporter_output(&mut self) -> ReporterStderr<'_> {
        match self {
            Self::Normal => ReporterStderr::Terminal,
            #[cfg(test)]
            Self::Test { ref mut stderr, .. } => ReporterStderr::Buffer(stderr),
        }
    }

    pub(crate) fn stderr_writer(&mut self) -> StderrWriter<'_> {
        match self {
            Self::Normal => StderrWriter::Normal {
                buf: BufWriter::new(std::io::stderr()),
                _lifetime: PhantomData,
            },
            #[cfg(test)]
            Self::Test { ref mut stderr, .. } => StderrWriter::Test { buf: stderr },
        }
    }
}

pub(crate) enum StdoutWriter<'a> {
    Normal {
        buf: BufWriter<Stdout>,
        _lifetime: PhantomData<&'a ()>,
    },
    #[cfg(test)]
    Test { buf: &'a mut Vec<u8> },
}

impl Write for StdoutWriter<'_> {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        match self {
            Self::Normal { buf, .. } => buf.write(data),
            #[cfg(test)]
            Self::Test { buf } => buf.write(data),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            Self::Normal { buf, .. } => buf.flush(),
            #[cfg(test)]
            Self::Test { .. } => Ok(()),
        }
    }
}

impl WriteStr for StdoutWriter<'_> {
    fn write_str(&mut self, s: &str) -> io::Result<()> {
        match self {
            Self::Normal { buf, .. } => buf.write_all(s.as_bytes()),
            #[cfg(test)]
            Self::Test { buf } => buf.write_all(s.as_bytes()),
        }
    }

    fn write_str_flush(&mut self) -> io::Result<()> {
        match self {
            Self::Normal { buf, .. } => buf.flush(),
            #[cfg(test)]
            Self::Test { .. } => Ok(()),
        }
    }
}

pub(crate) enum StderrWriter<'a> {
    Normal {
        buf: BufWriter<Stderr>,
        _lifetime: PhantomData<&'a ()>,
    },
    #[cfg(test)]
    Test { buf: &'a mut Vec<u8> },
}

impl Write for StderrWriter<'_> {
    fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
        match self {
            Self::Normal { buf, .. } => buf.write(data),
            #[cfg(test)]
            Self::Test { buf } => buf.write(data),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            Self::Normal { buf, .. } => buf.flush(),
            #[cfg(test)]
            Self::Test { .. } => Ok(()),
        }
    }
}

pub(crate) fn should_redact() -> bool {
    std::env::var("__NEXTEST_REDACT") == Ok("1".to_string())
}