nextest-runner 0.114.0

Core runner logic for cargo nextest.
Documentation
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use super::ArchiveStep;
use crate::{helpers::plural, redact::Redactor, write_str::WriteStr};
use camino::Utf8Path;
use owo_colors::{OwoColorize, Style};
use std::{io, time::Duration};
use swrite::{SWrite, swrite};

#[derive(Debug)]
/// Reporter for archive operations.
pub struct ArchiveReporter {
    styles: Styles,
    verbose: bool,
    redactor: Redactor,

    linked_path_hint_emitted: bool,
    // TODO: message-format json?
}

impl ArchiveReporter {
    /// Creates a new reporter for archive events.
    pub fn new(verbose: bool, redactor: Redactor) -> Self {
        Self {
            styles: Styles::default(),
            verbose,
            redactor,

            linked_path_hint_emitted: false,
        }
    }

    /// Colorizes output.
    pub fn colorize(&mut self) {
        self.styles.colorize();
    }

    /// Reports an archive event.
    pub fn report_event(
        &mut self,
        event: ArchiveEvent<'_>,
        writer: &mut dyn WriteStr,
    ) -> io::Result<()> {
        match event {
            ArchiveEvent::ArchiveStarted {
                counts,
                output_file,
            } => {
                write!(writer, "{:>12} ", "Archiving".style(self.styles.success))?;

                self.report_counts(counts, writer)?;

                writeln!(
                    writer,
                    " to {}",
                    self.redactor
                        .redact_path(output_file)
                        .style(self.styles.bold)
                )?;
            }
            ArchiveEvent::StdlibPathError { error } => {
                write!(writer, "{:>12} ", "Warning".style(self.styles.bold))?;
                writeln!(
                    writer,
                    "could not find standard library for host (proc macro tests may not work): {error}"
                )?;
            }
            ArchiveEvent::ExtraPathMissing { path, warn } => {
                if warn {
                    write!(writer, "{:>12} ", "Warning".style(self.styles.warning))?;
                } else if self.verbose {
                    write!(writer, "{:>12} ", "Skipped".style(self.styles.skipped))?;
                } else {
                    return Ok(()); // Skip
                }

                writeln!(
                    writer,
                    "ignoring extra path `{}` because it does not exist",
                    self.redactor.redact_path(path).style(self.styles.bold),
                )?;
            }
            ArchiveEvent::DirectoryAtDepthZero { path } => {
                write!(writer, "{:>12} ", "Warning".style(self.styles.warning))?;
                writeln!(
                    writer,
                    "ignoring extra path `{}` specified with depth 0 since it is a directory",
                    self.redactor.redact_path(path).style(self.styles.bold),
                )?;
            }
            ArchiveEvent::RecursionDepthExceeded {
                step,
                path,
                limit,
                warn,
            } => {
                if warn {
                    write!(writer, "{:>12} ", "Warning".style(self.styles.warning))?;
                } else if self.verbose {
                    write!(writer, "{:>12} ", "Skipped".style(self.styles.skipped))?;
                } else {
                    return Ok(()); // Skip
                }

                writeln!(
                    writer,
                    "while archiving {step}, recursion depth exceeded at {} (limit: {limit})",
                    self.redactor.redact_path(path).style(self.styles.bold),
                )?;
            }
            ArchiveEvent::UnknownFileType { step, path } => {
                write!(writer, "{:>12} ", "Warning".style(self.styles.warning))?;
                writeln!(
                    writer,
                    "while archiving {step}, ignoring `{}` because it is not a file, \
                     directory, or symbolic link",
                    self.redactor.redact_path(path).style(self.styles.bold),
                )?;
            }
            ArchiveEvent::LinkedPathNotFound { path, requested_by } => {
                write!(writer, "{:>12} ", "Warning".style(self.styles.warning))?;
                writeln!(
                    writer,
                    "linked path `{}` not found, requested by: {}",
                    self.redactor.redact_path(path).style(self.styles.bold),
                    requested_by.join(", ").style(self.styles.bold),
                )?;
                if !self.linked_path_hint_emitted {
                    write!(writer, "{:>12} ", "")?;
                    writeln!(
                        writer,
                        "(this is a bug in {} that should be fixed)",
                        plural::this_crate_str(requested_by.len())
                    )?;
                    self.linked_path_hint_emitted = true;
                }
            }
            ArchiveEvent::Archived {
                file_count,
                output_file,
                elapsed,
            } => {
                write!(writer, "{:>12} ", "Archived".style(self.styles.success))?;
                writeln!(
                    writer,
                    "{} files to {} in {}",
                    self.redactor
                        .redact_file_count(file_count)
                        .style(self.styles.bold),
                    self.redactor
                        .redact_path(output_file)
                        .style(self.styles.bold),
                    self.redactor.redact_duration(elapsed),
                )?;
            }
            ArchiveEvent::ExtractStarted {
                test_binary_count,
                non_test_binary_count,
                build_script_out_dir_count,
                linked_path_count,
                dest_dir: destination_dir,
            } => {
                write!(writer, "{:>12} ", "Extracting".style(self.styles.success))?;

                self.report_counts(
                    ArchiveCounts {
                        test_binary_count,
                        // We don't track filtered-out test binaries during
                        // extraction.
                        filter_counts: ArchiveFilterCounts::default(),
                        non_test_binary_count,
                        build_script_out_dir_count,
                        linked_path_count,
                        // TODO: we currently don't store a list of extra paths or standard libs at
                        // manifest creation time, so we can't report this count here.
                        extra_path_count: 0,
                        stdlib_count: 0,
                    },
                    writer,
                )?;

                writeln!(writer, " to {}", destination_dir.style(self.styles.bold))?;
            }
            ArchiveEvent::Extracted {
                file_count,
                dest_dir: destination_dir,
                elapsed,
            } => {
                write!(writer, "{:>12} ", "Extracted".style(self.styles.success))?;
                writeln!(
                    writer,
                    "{} {} to {} in {}",
                    self.redactor
                        .redact_file_count(file_count)
                        .style(self.styles.bold),
                    plural::files_str(file_count),
                    self.redactor
                        .redact_path(destination_dir)
                        .style(self.styles.bold),
                    self.redactor.redact_duration(elapsed),
                )?;
            }
        }

        Ok(())
    }

    fn report_counts(
        &mut self,
        counts: ArchiveCounts,
        writer: &mut dyn WriteStr,
    ) -> io::Result<()> {
        let ArchiveCounts {
            test_binary_count,
            filter_counts:
                ArchiveFilterCounts {
                    filtered_out_test_binary_count,
                    filtered_out_non_test_binary_count,
                    filtered_out_build_script_out_dir_count,
                },
            non_test_binary_count,
            build_script_out_dir_count,
            linked_path_count,
            extra_path_count,
            stdlib_count,
        } = counts;

        let total_binary_count = test_binary_count + non_test_binary_count;
        let mut in_parens = Vec::new();
        if non_test_binary_count > 0 {
            in_parens.push(format!(
                "including {} non-test {}",
                non_test_binary_count.style(self.styles.bold),
                plural::binaries_str(non_test_binary_count),
            ));
        }
        if filtered_out_test_binary_count > 0 || filtered_out_non_test_binary_count > 0 {
            let mut filtered_out = Vec::new();
            if filtered_out_test_binary_count > 0 {
                filtered_out.push(format!(
                    "{} test {}",
                    filtered_out_test_binary_count.style(self.styles.bold),
                    plural::binaries_str(filtered_out_test_binary_count),
                ));
            }
            if filtered_out_non_test_binary_count > 0 {
                filtered_out.push(format!(
                    "{} non-test {}",
                    filtered_out_non_test_binary_count.style(self.styles.bold),
                    plural::binaries_str(filtered_out_non_test_binary_count),
                ));
            }

            in_parens.push(format!("{} filtered out", filtered_out.join(" and ")));
        }
        let mut more = Vec::new();
        if build_script_out_dir_count > 0 {
            let mut s = format!(
                "{} build script output {}",
                build_script_out_dir_count.style(self.styles.bold),
                plural::directories_str(build_script_out_dir_count),
            );
            if filtered_out_build_script_out_dir_count > 0 {
                swrite!(
                    s,
                    " ({} filtered out)",
                    filtered_out_build_script_out_dir_count.style(self.styles.bold)
                );
            }
            more.push(s);
        }
        if linked_path_count > 0 {
            more.push(format!(
                "{} linked {}",
                linked_path_count.style(self.styles.bold),
                plural::paths_str(linked_path_count),
            ));
        }
        if extra_path_count > 0 {
            more.push(format!(
                "{} extra {}",
                extra_path_count.style(self.styles.bold),
                plural::paths_str(extra_path_count),
            ));
        }
        if stdlib_count > 0 {
            more.push(format!(
                "{} standard {}",
                stdlib_count.style(self.styles.bold),
                plural::libraries_str(stdlib_count),
            ));
        }

        let parens_text = if in_parens.is_empty() {
            String::new()
        } else {
            format!(" ({})", in_parens.join("; "))
        };

        write!(
            writer,
            "{} {}{parens_text}",
            total_binary_count.style(self.styles.bold),
            plural::binaries_str(total_binary_count),
        )?;

        match more.len() {
            0 => Ok(()),
            1 => {
                write!(writer, " and {}", more[0])
            }
            _ => {
                write!(
                    writer,
                    ", {}, and {}",
                    more[..more.len() - 1].join(", "),
                    more.last().unwrap(),
                )
            }
        }
    }
}

#[derive(Debug, Default)]
struct Styles {
    bold: Style,
    success: Style,
    warning: Style,
    skipped: Style,
}

impl Styles {
    fn colorize(&mut self) {
        self.bold = Style::new().bold();
        self.success = Style::new().green().bold();
        self.warning = Style::new().yellow().bold();
        self.skipped = Style::new().bold();
    }
}

/// An archive event.
///
/// Events are produced by archive and extract operations, and consumed by an [`ArchiveReporter`].
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum ArchiveEvent<'a> {
    /// The archive process started.
    ArchiveStarted {
        /// File counts.
        counts: ArchiveCounts,

        /// The archive output file.
        output_file: &'a Utf8Path,
    },

    /// An error occurred while obtaining the path to a standard library.
    StdlibPathError {
        /// The error that occurred.
        error: &'a str,
    },

    /// A provided extra path did not exist.
    ExtraPathMissing {
        /// The path that was missing.
        path: &'a Utf8Path,

        /// Whether the reporter should produce a warning about this.
        warn: bool,
    },

    /// For an extra include, a directory was specified at depth 0.
    DirectoryAtDepthZero {
        /// The directory that was at depth 0.
        path: &'a Utf8Path,
    },

    /// While performing the archive, the recursion depth was exceeded.
    RecursionDepthExceeded {
        /// The current step in the archive process.
        step: ArchiveStep,

        /// The path that exceeded the recursion depth.
        path: &'a Utf8Path,

        /// The recursion depth limit that was hit.
        limit: usize,

        /// Whether the reporter should produce a warning about this.
        warn: bool,
    },

    /// The archive process encountered an unknown file type.
    UnknownFileType {
        /// The current step in the archive process.
        step: ArchiveStep,

        /// The path of the unknown type.
        path: &'a Utf8Path,
    },

    /// A crate linked against a non-existent path.
    LinkedPathNotFound {
        /// The path of the linked file.
        path: &'a Utf8Path,

        /// The crates that linked against the path.
        requested_by: &'a [String],
    },

    /// The archive operation completed successfully.
    Archived {
        /// The number of files archived.
        file_count: usize,

        /// The archive output file.
        output_file: &'a Utf8Path,

        /// How long it took to create the archive.
        elapsed: Duration,
    },

    /// The extraction process started.
    ExtractStarted {
        /// The number of test binaries to extract.
        test_binary_count: usize,

        /// The number of non-test binaries to extract.
        non_test_binary_count: usize,

        /// The number of build script output directories to archive.
        build_script_out_dir_count: usize,

        /// The number of linked paths to extract.
        linked_path_count: usize,

        /// The destination directory.
        dest_dir: &'a Utf8Path,
    },

    /// The extraction process completed successfully.
    Extracted {
        /// The number of files extracted.
        file_count: usize,

        /// The destination directory.
        dest_dir: &'a Utf8Path,

        /// How long it took to extract the archive.
        elapsed: Duration,
    },
}

/// Counts of various types of files in an archive.
#[derive(Clone, Copy, Debug, Default)]
pub struct ArchiveCounts {
    /// The number of test binaries that will be included in the archive, not
    /// including filtered out test binaries.
    pub test_binary_count: usize,

    /// Counts for filtered out binaries.
    pub filter_counts: ArchiveFilterCounts,

    /// The number of non-test binaries.
    pub non_test_binary_count: usize,

    /// The number of build script output directories.
    pub build_script_out_dir_count: usize,

    /// The number of linked paths.
    pub linked_path_count: usize,

    /// The number of extra paths.
    pub extra_path_count: usize,

    /// The number of standard libraries.
    pub stdlib_count: usize,
}

/// Counts the number of filtered out binaries.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ArchiveFilterCounts {
    /// The number of filtered out test binaries.
    pub filtered_out_test_binary_count: usize,

    /// The number of filtered out non-test binaries.
    pub filtered_out_non_test_binary_count: usize,

    /// The number of filtered out build script output directories.
    pub filtered_out_build_script_out_dir_count: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_case::test_case;

    #[test_case(
        ArchiveCounts {
            test_binary_count: 1,
            ..Default::default()
        },
        "1 binary"
        ; "single test binary"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            ..Default::default()
        },
        "5 binaries"
        ; "multiple test binaries"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            non_test_binary_count: 2,
            ..Default::default()
        },
        "7 binaries (including 2 non-test binaries)"
        ; "with non-test binaries"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            filter_counts: ArchiveFilterCounts {
                filtered_out_test_binary_count: 2,
                ..Default::default()
            },
            ..Default::default()
        },
        "5 binaries (2 test binaries filtered out)"
        ; "with filtered out test binaries"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            filter_counts: ArchiveFilterCounts {
                filtered_out_non_test_binary_count: 1,
                ..Default::default()
            },
            ..Default::default()
        },
        "5 binaries (1 non-test binary filtered out)"
        ; "with filtered out non-test binary"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            filter_counts: ArchiveFilterCounts {
                filtered_out_test_binary_count: 2,
                filtered_out_non_test_binary_count: 3,
                ..Default::default()
            },
            ..Default::default()
        },
        "5 binaries (2 test binaries and 3 non-test binaries filtered out)"
        ; "with both types filtered out"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            filter_counts: ArchiveFilterCounts {
                filtered_out_test_binary_count: 1,
                filtered_out_non_test_binary_count: 2,
                ..Default::default()
            },
            non_test_binary_count: 3,
            ..Default::default()
        },
        "8 binaries (including 3 non-test binaries; 1 test binary and 2 non-test binaries filtered out)"
        ; "with non-test binaries and both types filtered out"
    )]
    #[test_case(
        ArchiveCounts {
            filter_counts: ArchiveFilterCounts {
                filtered_out_non_test_binary_count: 2,
                ..Default::default()
            },
            ..Default::default()
        },
        "0 binaries (2 non-test binaries filtered out)"
        ; "zero binaries with filtered out"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            build_script_out_dir_count: 1,
            ..Default::default()
        },
        "5 binaries and 1 build script output directory"
        ; "with single more item"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            build_script_out_dir_count: 3,
            filter_counts: ArchiveFilterCounts {
                filtered_out_build_script_out_dir_count: 2,
                ..Default::default()
            },
            ..Default::default()
        },
        "5 binaries and 3 build script output directories (2 filtered out)"
        ; "with filtered out build script out dirs"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            linked_path_count: 3,
            ..Default::default()
        },
        "5 binaries and 3 linked paths"
        ; "with linked paths"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 5,
            build_script_out_dir_count: 2,
            linked_path_count: 3,
            extra_path_count: 1,
            stdlib_count: 4,
            ..Default::default()
        },
        "5 binaries, 2 build script output directories, 3 linked paths, 1 extra path, and 4 standard libraries"
        ; "with multiple more items"
    )]
    #[test_case(
        ArchiveCounts {
            test_binary_count: 4,
            filter_counts: ArchiveFilterCounts {
                filtered_out_test_binary_count: 1,
                filtered_out_non_test_binary_count: 2,
                filtered_out_build_script_out_dir_count: 1,
            },
            non_test_binary_count: 2,
            build_script_out_dir_count: 3,
            linked_path_count: 2,
            extra_path_count: 1,
            stdlib_count: 2,
        },
        "6 binaries (including 2 non-test binaries; 1 test binary and 2 non-test binaries filtered out), 3 build script output directories (1 filtered out), 2 linked paths, 1 extra path, and 2 standard libraries"
        ; "all fields combined"
    )]
    #[test_case(
        ArchiveCounts::default(),
        "0 binaries"
        ; "all zeros"
    )]
    fn test_report_counts(counts: ArchiveCounts, expected: &str) {
        let mut reporter = ArchiveReporter::new(false, Redactor::noop());
        let mut buffer = String::new();

        reporter.report_counts(counts, &mut buffer).unwrap();

        assert_eq!(buffer, expected);
    }
}