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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::CommandError;
use camino::{Utf8Path, Utf8PathBuf};
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::{
    borrow::Cow,
    cmp::Ordering,
    collections::{BTreeMap, BTreeSet},
    fmt::{self, Write as _},
    path::PathBuf,
    process::Command,
};
use target_spec::summaries::PlatformSummary;

/// Command builder for `cargo nextest list`.
#[derive(Clone, Debug, Default)]
pub struct ListCommand {
    cargo_path: Option<Box<Utf8Path>>,
    manifest_path: Option<Box<Utf8Path>>,
    current_dir: Option<Box<Utf8Path>>,
    args: Vec<Box<str>>,
}

impl ListCommand {
    /// Creates a new `ListCommand`.
    ///
    /// This command runs `cargo nextest list`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Path to `cargo` executable. If not set, this will use the the `$CARGO` environment variable, and
    /// if that is not set, will simply be `cargo`.
    pub fn cargo_path(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
        self.cargo_path = Some(path.into().into());
        self
    }

    /// Path to `Cargo.toml`.
    pub fn manifest_path(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
        self.manifest_path = Some(path.into().into());
        self
    }

    /// Current directory of the `cargo nextest list` process.
    pub fn current_dir(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
        self.current_dir = Some(path.into().into());
        self
    }

    /// Adds an argument to the end of `cargo nextest list`.
    pub fn add_arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.args.push(arg.into().into());
        self
    }

    /// Adds several arguments to the end of `cargo nextest list`.
    pub fn add_args(&mut self, args: impl IntoIterator<Item = impl Into<String>>) -> &mut Self {
        for arg in args {
            self.add_arg(arg.into());
        }
        self
    }

    /// Builds a command for `cargo nextest list`. This is the first part of the work of [`self.exec`].
    pub fn cargo_command(&self) -> Command {
        let cargo_path: PathBuf = self.cargo_path.as_ref().map_or_else(
            || std::env::var_os("CARGO").map_or("cargo".into(), PathBuf::from),
            |path| PathBuf::from(path.as_std_path()),
        );

        let mut command = Command::new(cargo_path);
        if let Some(path) = &self.manifest_path.as_deref() {
            command.args(["--manifest-path", path.as_str()]);
        }
        if let Some(current_dir) = &self.current_dir.as_deref() {
            command.current_dir(current_dir);
        }

        command.args(["nextest", "list", "--message-format=json"]);

        command.args(self.args.iter().map(|s| s.as_ref()));
        command
    }

    /// Executes `cargo nextest list` and parses the output into a [`TestListSummary`].
    pub fn exec(&self) -> Result<TestListSummary, CommandError> {
        let mut command = self.cargo_command();
        let output = command.output().map_err(CommandError::Exec)?;

        if !output.status.success() {
            // The process exited with a non-zero code.
            let exit_code = output.status.code();
            let stderr = output.stderr;
            return Err(CommandError::CommandFailed { exit_code, stderr });
        }

        // Try parsing stdout.
        serde_json::from_slice(&output.stdout).map_err(CommandError::Json)
    }

    /// Executes `cargo nextest list --list-type binaries-only` and parses the output into a
    /// [`BinaryListSummary`].
    pub fn exec_binaries_only(&self) -> Result<BinaryListSummary, CommandError> {
        let mut command = self.cargo_command();
        command.arg("--list-type=binaries-only");
        let output = command.output().map_err(CommandError::Exec)?;

        if !output.status.success() {
            // The process exited with a non-zero code.
            let exit_code = output.status.code();
            let stderr = output.stderr;
            return Err(CommandError::CommandFailed { exit_code, stderr });
        }

        // Try parsing stdout.
        serde_json::from_slice(&output.stdout).map_err(CommandError::Json)
    }
}

/// Root element for a serializable list of tests generated by nextest.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct TestListSummary {
    /// Rust metadata used for builds and test runs.
    pub rust_build_meta: RustBuildMetaSummary,

    /// Number of tests (including skipped and ignored) across all binaries.
    pub test_count: usize,

    /// A map of Rust test suites to the test binaries within them, keyed by a unique identifier
    /// for each test suite.
    pub rust_suites: BTreeMap<RustBinaryId, RustTestSuiteSummary>,
}

impl TestListSummary {
    /// Creates a new `TestListSummary` with the given Rust metadata.
    pub fn new(rust_build_meta: RustBuildMetaSummary) -> Self {
        Self {
            rust_build_meta,
            test_count: 0,
            rust_suites: BTreeMap::new(),
        }
    }
    /// Parse JSON output from `cargo nextest list --message-format json`.
    pub fn parse_json(json: impl AsRef<str>) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json.as_ref())
    }
}

/// The platform a binary was built on (useful for cross-compilation)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum BuildPlatform {
    /// The target platform.
    Target,

    /// The host platform: the platform the build was performed on.
    Host,
}

impl fmt::Display for BuildPlatform {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Target => write!(f, "target"),
            Self::Host => write!(f, "host"),
        }
    }
}

/// A serializable Rust test binary.
///
/// Part of a [`RustTestSuiteSummary`] and [`BinaryListSummary`].
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RustTestBinarySummary {
    /// A unique binary ID.
    pub binary_id: RustBinaryId,

    /// The name of the test binary within the package.
    pub binary_name: String,

    /// The unique package ID assigned by Cargo to this test.
    ///
    /// This package ID can be used for lookups in `cargo metadata`.
    pub package_id: String,

    /// The kind of Rust test binary this is.
    pub kind: RustTestBinaryKind,

    /// The path to the test binary executable.
    pub binary_path: Utf8PathBuf,

    /// Platform for which this binary was built.
    /// (Proc-macro tests are built for the host.)
    pub build_platform: BuildPlatform,
}

/// Information about the kind of a Rust test binary.
///
/// Kinds are used to generate [`RustBinaryId`] instances, and to figure out whether some
/// environment variables should be set.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(transparent)]
pub struct RustTestBinaryKind(pub Cow<'static, str>);

impl RustTestBinaryKind {
    /// Creates a new `RustTestBinaryKind` from a string.
    #[inline]
    pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
        Self(kind.into())
    }

    /// Creates a new `RustTestBinaryKind` from a static string.
    #[inline]
    pub const fn new_const(kind: &'static str) -> Self {
        Self(Cow::Borrowed(kind))
    }

    /// Returns the kind as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The "lib" kind, used for unit tests within the library.
    pub const LIB: Self = Self::new_const("lib");

    /// The "test" kind, used for integration tests.
    pub const TEST: Self = Self::new_const("test");

    /// The "bench" kind, used for benchmarks.
    pub const BENCH: Self = Self::new_const("bench");

    /// The "bin" kind, used for unit tests within binaries.
    pub const BIN: Self = Self::new_const("bin");

    /// The "proc-macro" kind, used for tests within procedural macros.
    pub const PROC_MACRO: Self = Self::new_const("proc-macro");
}

impl fmt::Display for RustTestBinaryKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A serializable suite of test binaries.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct BinaryListSummary {
    /// Rust metadata used for builds and test runs.
    pub rust_build_meta: RustBuildMetaSummary,

    /// The list of Rust test binaries (indexed by binary-id).
    pub rust_binaries: BTreeMap<RustBinaryId, RustTestBinarySummary>,
}

// IMPLEMENTATION NOTE: SmolStr is *not* part of the public API.

/// A unique identifier for a test suite (a Rust binary).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(transparent)]
pub struct RustBinaryId(SmolStr);

impl fmt::Display for RustBinaryId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl RustBinaryId {
    /// Creates a new `RustBinaryId` from a string.
    #[inline]
    pub fn new(id: &str) -> Self {
        Self(id.into())
    }

    /// Creates a new `RustBinaryId` from its constituent parts:
    ///
    /// * `package_name`: The name of the package as defined in `Cargo.toml`.
    /// * `kind`: The kind of the target (see [`RustTestBinaryKind`]).
    /// * `target_name`: The name of the target.
    ///
    /// The algorithm is as follows:
    ///
    /// 1. If the kind is `lib` or `proc-macro` (i.e. for unit tests), the binary ID is the same as
    ///    the package name. There can only be one library per package, so this will always be
    ///    unique.
    /// 2. If the target is an integration test, the binary ID is `package_name::target_name`.
    /// 3. Otherwise, the binary ID is `package_name::{kind}/{target_name}`.
    ///
    /// This format is part of nextest's stable API.
    ///
    /// # Examples
    ///
    /// ```
    /// use nextest_metadata::{RustBinaryId, RustTestBinaryKind};
    ///
    /// // The lib and proc-macro kinds.
    /// assert_eq!(
    ///     RustBinaryId::from_parts("foo-lib", &RustTestBinaryKind::LIB, "foo_lib"),
    ///     RustBinaryId::new("foo-lib"),
    /// );
    /// assert_eq!(
    ///    RustBinaryId::from_parts("foo-derive", &RustTestBinaryKind::PROC_MACRO, "derive"),
    ///    RustBinaryId::new("foo-derive"),
    /// );
    ///
    /// // Integration tests.
    /// assert_eq!(
    ///    RustBinaryId::from_parts("foo-lib", &RustTestBinaryKind::TEST, "foo_test"),
    ///    RustBinaryId::new("foo-lib::foo_test"),
    /// );
    ///
    /// // Other kinds.
    /// assert_eq!(
    ///     RustBinaryId::from_parts("foo-lib", &RustTestBinaryKind::BIN, "foo_bin"),
    ///     RustBinaryId::new("foo-lib::bin/foo_bin"),
    /// );
    /// ```
    pub fn from_parts(package_name: &str, kind: &RustTestBinaryKind, target_name: &str) -> Self {
        let mut id = package_name.to_owned();
        // To ensure unique binary IDs, we use the following scheme:
        if kind == &RustTestBinaryKind::LIB || kind == &RustTestBinaryKind::PROC_MACRO {
            // 1. The binary ID is the same as the package name.
        } else if kind == &RustTestBinaryKind::TEST {
            // 2. For integration tests, use package_name::target_name. Cargo enforces unique names
            //    for the same kind of targets in a package, so these will always be unique.
            id.push_str("::");
            id.push_str(target_name);
        } else {
            // 3. For all other target kinds, use a combination of the target kind and
            //    the target name. For the same reason as above, these will always be
            //    unique.
            write!(id, "::{kind}/{target_name}").unwrap();
        }

        Self(id.into())
    }

    /// Returns the identifier as a string.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the length of the identifier in bytes.
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if the identifier is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the components of this identifier.
    #[inline]
    pub fn components(&self) -> RustBinaryIdComponents<'_> {
        RustBinaryIdComponents::new(self)
    }
}

impl<S> From<S> for RustBinaryId
where
    S: AsRef<str>,
{
    #[inline]
    fn from(s: S) -> Self {
        Self(s.as_ref().into())
    }
}

impl Ord for RustBinaryId {
    fn cmp(&self, other: &RustBinaryId) -> Ordering {
        // Use the components as the canonical sort order.
        self.components().cmp(&other.components())
    }
}

impl PartialOrd for RustBinaryId {
    fn partial_cmp(&self, other: &RustBinaryId) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// The components of a [`RustBinaryId`].
///
/// This defines the canonical sort order for a `RustBinaryId`.
///
/// Returned by [`RustBinaryId::components`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct RustBinaryIdComponents<'a> {
    /// The name of the package.
    pub package_name: &'a str,

    /// The kind and binary name, if specified.
    pub binary_name_and_kind: RustBinaryIdNameAndKind<'a>,
}

impl<'a> RustBinaryIdComponents<'a> {
    fn new(id: &'a RustBinaryId) -> Self {
        let mut parts = id.as_str().splitn(2, "::");

        let package_name = parts
            .next()
            .expect("splitn(2) returns at least 1 component");
        let binary_name_and_kind = if let Some(suffix) = parts.next() {
            let mut parts = suffix.splitn(2, '/');

            let part1 = parts
                .next()
                .expect("splitn(2) returns at least 1 component");
            if let Some(binary_name) = parts.next() {
                RustBinaryIdNameAndKind::NameAndKind {
                    kind: part1,
                    binary_name,
                }
            } else {
                RustBinaryIdNameAndKind::NameOnly { binary_name: part1 }
            }
        } else {
            RustBinaryIdNameAndKind::None
        };

        Self {
            package_name,
            binary_name_and_kind,
        }
    }
}

/// The name and kind of a Rust binary, present within a [`RustBinaryId`].
///
/// Part of [`RustBinaryIdComponents`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum RustBinaryIdNameAndKind<'a> {
    /// The binary has no name or kind.
    None,

    /// The binary has a name but no kind.
    NameOnly {
        /// The name of the binary.
        binary_name: &'a str,
    },

    /// The binary has a name and kind.
    NameAndKind {
        /// The kind of the binary.
        kind: &'a str,

        /// The name of the binary.
        binary_name: &'a str,
    },
}

/// Rust metadata used for builds and test runs.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RustBuildMetaSummary {
    /// The target directory for Rust artifacts.
    pub target_directory: Utf8PathBuf,

    /// Base output directories, relative to the target directory.
    pub base_output_directories: BTreeSet<Utf8PathBuf>,

    /// Information about non-test binaries, keyed by package ID.
    pub non_test_binaries: BTreeMap<String, BTreeSet<RustNonTestBinarySummary>>,

    /// Build script output directory, relative to the target directory and keyed by package ID.
    /// Only present for workspace packages that have build scripts.
    ///
    /// Added in cargo-nextest 0.9.65.
    #[serde(default)]
    pub build_script_out_dirs: BTreeMap<String, Utf8PathBuf>,

    /// Linked paths, relative to the target directory.
    pub linked_paths: BTreeSet<Utf8PathBuf>,

    /// The target platforms used while compiling the Rust artifacts.
    #[serde(default)]
    pub target_platforms: Vec<PlatformSummary>,

    /// A deprecated form of the target platform used for cross-compilation, if any.
    ///
    /// This is no longer used by nextest, but is maintained for compatibility with older versions
    /// which used to generate this.
    #[serde(default)]
    pub target_platform: Option<String>,
}

/// A non-test Rust binary. Used to set the correct environment
/// variables in reused builds.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RustNonTestBinarySummary {
    /// The name of the binary.
    pub name: String,

    /// The kind of binary this is.
    pub kind: RustNonTestBinaryKind,

    /// The path to the binary, relative to the target directory.
    pub path: Utf8PathBuf,
}

/// Information about the kind of a Rust non-test binary.
///
/// This is part of [`RustNonTestBinarySummary`], and is used to determine runtime environment
/// variables.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(transparent)]
pub struct RustNonTestBinaryKind(pub Cow<'static, str>);

impl RustNonTestBinaryKind {
    /// Creates a new `RustNonTestBinaryKind` from a string.
    #[inline]
    pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
        Self(kind.into())
    }

    /// Creates a new `RustNonTestBinaryKind` from a static string.
    #[inline]
    pub const fn new_const(kind: &'static str) -> Self {
        Self(Cow::Borrowed(kind))
    }

    /// Returns the kind as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The "dylib" kind, used for dynamic libraries (`.so` on Linux). Also used for
    /// .pdb and other similar files on Windows.
    pub const DYLIB: Self = Self::new_const("dylib");

    /// The "bin-exe" kind, used for binary executables.
    pub const BIN_EXE: Self = Self::new_const("bin-exe");
}

impl fmt::Display for RustNonTestBinaryKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// A serializable suite of tests within a Rust test binary.
///
/// Part of a [`TestListSummary`].
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RustTestSuiteSummary {
    /// The name of this package in the workspace.
    pub package_name: String,

    /// The binary within the package.
    #[serde(flatten)]
    pub binary: RustTestBinarySummary,

    /// The working directory that tests within this package are run in.
    pub cwd: Utf8PathBuf,

    /// Status of this test suite.
    ///
    /// Introduced in cargo-nextest 0.9.25. Older versions always imply
    /// [`LISTED`](RustTestSuiteStatusSummary::LISTED).
    #[serde(default = "listed_status")]
    pub status: RustTestSuiteStatusSummary,

    /// Test cases within this test suite.
    #[serde(rename = "testcases")]
    pub test_cases: BTreeMap<String, RustTestCaseSummary>,
}

fn listed_status() -> RustTestSuiteStatusSummary {
    RustTestSuiteStatusSummary::LISTED
}

/// Information about whether a test suite was listed or skipped.
///
/// This is part of [`RustTestSuiteSummary`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(transparent)]
pub struct RustTestSuiteStatusSummary(pub Cow<'static, str>);

impl RustTestSuiteStatusSummary {
    /// Creates a new `RustNonTestBinaryKind` from a string.
    #[inline]
    pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
        Self(kind.into())
    }

    /// Creates a new `RustNonTestBinaryKind` from a static string.
    #[inline]
    pub const fn new_const(kind: &'static str) -> Self {
        Self(Cow::Borrowed(kind))
    }

    /// Returns the kind as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The "listed" kind, which means that the test binary was executed with `--list` to gather the
    /// list of tests in it.
    pub const LISTED: Self = Self::new_const("listed");

    /// The "skipped" kind, which indicates that the test binary was not executed because it didn't
    /// match any expression filters.
    ///
    /// If this is "skipped", the contents of `RustTestSuiteSummary::test_cases` is empty.
    pub const SKIPPED: Self = Self::new_const("skipped");
}

/// Serializable information about an individual test case within a Rust test suite.
///
/// Part of a [`RustTestSuiteSummary`].
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct RustTestCaseSummary {
    /// Returns true if this test is marked ignored.
    ///
    /// Ignored tests, if run, are executed with the `--ignored` argument.
    pub ignored: bool,

    /// Whether the test matches the provided test filter.
    ///
    /// Only tests that match the filter are run.
    pub filter_match: FilterMatch,
}

/// An enum describing whether a test matches a filter.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", tag = "status")]
pub enum FilterMatch {
    /// This test matches this filter.
    Matches,

    /// This test does not match this filter.
    Mismatch {
        /// Describes the reason this filter isn't matched.
        reason: MismatchReason,
    },
}

impl FilterMatch {
    /// Returns true if the filter doesn't match.
    pub fn is_match(&self) -> bool {
        matches!(self, FilterMatch::Matches)
    }
}

/// The reason for why a test doesn't match a filter.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum MismatchReason {
    /// This test does not match the run-ignored option in the filter.
    Ignored,

    /// This test does not match the provided string filters.
    String,

    /// This test does not match the provided expression filters.
    Expression,

    /// This test is in a different partition.
    Partition,
}

impl fmt::Display for MismatchReason {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            MismatchReason::Ignored => write!(f, "does not match the run-ignored option"),
            MismatchReason::String => write!(f, "does not match the provided string filters"),
            MismatchReason::Expression => {
                write!(f, "does not match the provided expression filters")
            }
            MismatchReason::Partition => write!(f, "is in a different partition"),
        }
    }
}

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

    #[test_case(r#"{
        "target-directory": "/foo",
        "base-output-directories": [],
        "non-test-binaries": {},
        "linked-paths": []
    }"#, RustBuildMetaSummary {
        target_directory: "/foo".into(),
        base_output_directories: BTreeSet::new(),
        non_test_binaries: BTreeMap::new(),
        build_script_out_dirs: BTreeMap::new(),
        linked_paths: BTreeSet::new(),
        target_platform: None,
        target_platforms: vec![],
    }; "no target platform")]
    #[test_case(r#"{
        "target-directory": "/foo",
        "base-output-directories": [],
        "non-test-binaries": {},
        "linked-paths": [],
        "target-platform": "x86_64-unknown-linux-gnu"
    }"#, RustBuildMetaSummary {
        target_directory: "/foo".into(),
        base_output_directories: BTreeSet::new(),
        non_test_binaries: BTreeMap::new(),
        build_script_out_dirs: BTreeMap::new(),
        linked_paths: BTreeSet::new(),
        target_platform: Some("x86_64-unknown-linux-gnu".to_owned()),
        target_platforms: vec![],
    }; "single target platform specified")]
    fn test_deserialize_old_rust_build_meta(input: &str, expected: RustBuildMetaSummary) {
        let build_meta: RustBuildMetaSummary =
            serde_json::from_str(input).expect("input deserialized correctly");
        assert_eq!(
            build_meta, expected,
            "deserialized input matched expected output"
        );
    }

    #[test]
    fn test_binary_id_ord() {
        let empty = RustBinaryId::new("");
        let foo = RustBinaryId::new("foo");
        let bar = RustBinaryId::new("bar");
        let foo_name1 = RustBinaryId::new("foo::name1");
        let foo_name2 = RustBinaryId::new("foo::name2");
        let bar_name = RustBinaryId::new("bar::name");
        let foo_bin_name1 = RustBinaryId::new("foo::bin/name1");
        let foo_bin_name2 = RustBinaryId::new("foo::bin/name2");
        let bar_bin_name = RustBinaryId::new("bar::bin/name");
        let foo_proc_macro_name = RustBinaryId::new("foo::proc_macro/name");
        let bar_proc_macro_name = RustBinaryId::new("bar::proc_macro/name");

        // This defines the expected sort order.
        let sorted_ids = [
            empty,
            bar,
            bar_name,
            bar_bin_name,
            bar_proc_macro_name,
            foo,
            foo_name1,
            foo_name2,
            foo_bin_name1,
            foo_bin_name2,
            foo_proc_macro_name,
        ];

        for (i, id) in sorted_ids.iter().enumerate() {
            for (j, other_id) in sorted_ids.iter().enumerate() {
                let expected = i.cmp(&j);
                assert_eq!(
                    id.cmp(other_id),
                    expected,
                    "comparing {id:?} to {other_id:?} gave {expected:?}"
                );
            }
        }
    }
}