1use crate::CommandError;
5use camino::{Utf8Path, Utf8PathBuf};
6use serde::{Deserialize, Serialize};
7use smol_str::SmolStr;
8use std::{
9 borrow::Cow,
10 cmp::Ordering,
11 collections::{BTreeMap, BTreeSet},
12 fmt::{self, Write as _},
13 path::PathBuf,
14 process::Command,
15};
16use target_spec::summaries::PlatformSummary;
17
18#[derive(Clone, Debug, Default)]
20pub struct ListCommand {
21 cargo_path: Option<Box<Utf8Path>>,
22 manifest_path: Option<Box<Utf8Path>>,
23 current_dir: Option<Box<Utf8Path>>,
24 args: Vec<Box<str>>,
25}
26
27impl ListCommand {
28 pub fn new() -> Self {
32 Self::default()
33 }
34
35 pub fn cargo_path(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
38 self.cargo_path = Some(path.into().into());
39 self
40 }
41
42 pub fn manifest_path(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
44 self.manifest_path = Some(path.into().into());
45 self
46 }
47
48 pub fn current_dir(&mut self, path: impl Into<Utf8PathBuf>) -> &mut Self {
50 self.current_dir = Some(path.into().into());
51 self
52 }
53
54 pub fn add_arg(&mut self, arg: impl Into<String>) -> &mut Self {
56 self.args.push(arg.into().into());
57 self
58 }
59
60 pub fn add_args(&mut self, args: impl IntoIterator<Item = impl Into<String>>) -> &mut Self {
62 for arg in args {
63 self.add_arg(arg.into());
64 }
65 self
66 }
67
68 pub fn cargo_command(&self) -> Command {
71 let cargo_path: PathBuf = self.cargo_path.as_ref().map_or_else(
72 || std::env::var_os("CARGO").map_or("cargo".into(), PathBuf::from),
73 |path| PathBuf::from(path.as_std_path()),
74 );
75
76 let mut command = Command::new(cargo_path);
77 if let Some(path) = &self.manifest_path.as_deref() {
78 command.args(["--manifest-path", path.as_str()]);
79 }
80 if let Some(current_dir) = &self.current_dir.as_deref() {
81 command.current_dir(current_dir);
82 }
83
84 command.args(["nextest", "list", "--message-format=json"]);
85
86 command.args(self.args.iter().map(|s| s.as_ref()));
87 command
88 }
89
90 pub fn exec(&self) -> Result<TestListSummary, CommandError> {
92 let mut command = self.cargo_command();
93 let output = command.output().map_err(CommandError::Exec)?;
94
95 if !output.status.success() {
96 let exit_code = output.status.code();
98 let stderr = output.stderr;
99 return Err(CommandError::CommandFailed { exit_code, stderr });
100 }
101
102 serde_json::from_slice(&output.stdout).map_err(CommandError::Json)
104 }
105
106 pub fn exec_binaries_only(&self) -> Result<BinaryListSummary, CommandError> {
109 let mut command = self.cargo_command();
110 command.arg("--list-type=binaries-only");
111 let output = command.output().map_err(CommandError::Exec)?;
112
113 if !output.status.success() {
114 let exit_code = output.status.code();
116 let stderr = output.stderr;
117 return Err(CommandError::CommandFailed { exit_code, stderr });
118 }
119
120 serde_json::from_slice(&output.stdout).map_err(CommandError::Json)
122 }
123}
124
125#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
127#[serde(rename_all = "kebab-case")]
128#[non_exhaustive]
129pub struct TestListSummary {
130 pub rust_build_meta: RustBuildMetaSummary,
132
133 pub test_count: usize,
135
136 pub rust_suites: BTreeMap<RustBinaryId, RustTestSuiteSummary>,
139}
140
141impl TestListSummary {
142 pub fn new(rust_build_meta: RustBuildMetaSummary) -> Self {
144 Self {
145 rust_build_meta,
146 test_count: 0,
147 rust_suites: BTreeMap::new(),
148 }
149 }
150 pub fn parse_json(json: impl AsRef<str>) -> Result<Self, serde_json::Error> {
152 serde_json::from_str(json.as_ref())
153 }
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
158#[serde(rename_all = "kebab-case")]
159pub enum BuildPlatform {
160 Target,
162
163 Host,
165}
166
167impl fmt::Display for BuildPlatform {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169 match self {
170 Self::Target => write!(f, "target"),
171 Self::Host => write!(f, "host"),
172 }
173 }
174}
175
176#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
180#[serde(rename_all = "kebab-case")]
181pub struct RustTestBinarySummary {
182 pub binary_id: RustBinaryId,
184
185 pub binary_name: String,
187
188 pub package_id: String,
192
193 pub kind: RustTestBinaryKind,
195
196 pub binary_path: Utf8PathBuf,
198
199 pub build_platform: BuildPlatform,
202}
203
204#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
209#[serde(transparent)]
210pub struct RustTestBinaryKind(pub Cow<'static, str>);
211
212impl RustTestBinaryKind {
213 #[inline]
215 pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
216 Self(kind.into())
217 }
218
219 #[inline]
221 pub const fn new_const(kind: &'static str) -> Self {
222 Self(Cow::Borrowed(kind))
223 }
224
225 pub fn as_str(&self) -> &str {
227 &self.0
228 }
229
230 pub const LIB: Self = Self::new_const("lib");
232
233 pub const TEST: Self = Self::new_const("test");
235
236 pub const BENCH: Self = Self::new_const("bench");
238
239 pub const BIN: Self = Self::new_const("bin");
241
242 pub const EXAMPLE: Self = Self::new_const("example");
244
245 pub const PROC_MACRO: Self = Self::new_const("proc-macro");
247}
248
249impl fmt::Display for RustTestBinaryKind {
250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 write!(f, "{}", self.0)
252 }
253}
254
255#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
257#[serde(rename_all = "kebab-case")]
258pub struct BinaryListSummary {
259 pub rust_build_meta: RustBuildMetaSummary,
261
262 pub rust_binaries: BTreeMap<RustBinaryId, RustTestBinarySummary>,
264}
265
266#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
270#[serde(transparent)]
271pub struct RustBinaryId(SmolStr);
272
273impl fmt::Display for RustBinaryId {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.write_str(&self.0)
276 }
277}
278
279impl RustBinaryId {
280 #[inline]
282 pub fn new(id: &str) -> Self {
283 Self(id.into())
284 }
285
286 pub fn from_parts(package_name: &str, kind: &RustTestBinaryKind, target_name: &str) -> Self {
330 let mut id = package_name.to_owned();
331 if kind == &RustTestBinaryKind::LIB || kind == &RustTestBinaryKind::PROC_MACRO {
333 } else if kind == &RustTestBinaryKind::TEST {
335 id.push_str("::");
338 id.push_str(target_name);
339 } else {
340 write!(id, "::{kind}/{target_name}").unwrap();
344 }
345
346 Self(id.into())
347 }
348
349 #[inline]
351 pub fn as_str(&self) -> &str {
352 &self.0
353 }
354
355 #[inline]
357 pub fn len(&self) -> usize {
358 self.0.len()
359 }
360
361 #[inline]
363 pub fn is_empty(&self) -> bool {
364 self.0.is_empty()
365 }
366
367 #[inline]
369 pub fn components(&self) -> RustBinaryIdComponents<'_> {
370 RustBinaryIdComponents::new(self)
371 }
372}
373
374impl<S> From<S> for RustBinaryId
375where
376 S: AsRef<str>,
377{
378 #[inline]
379 fn from(s: S) -> Self {
380 Self(s.as_ref().into())
381 }
382}
383
384impl Ord for RustBinaryId {
385 fn cmp(&self, other: &RustBinaryId) -> Ordering {
386 self.components().cmp(&other.components())
391 }
392}
393
394impl PartialOrd for RustBinaryId {
395 fn partial_cmp(&self, other: &RustBinaryId) -> Option<Ordering> {
396 Some(self.cmp(other))
397 }
398}
399
400#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
406pub struct RustBinaryIdComponents<'a> {
407 pub package_name: &'a str,
409
410 pub binary_name_and_kind: RustBinaryIdNameAndKind<'a>,
412}
413
414impl<'a> RustBinaryIdComponents<'a> {
415 fn new(id: &'a RustBinaryId) -> Self {
416 let mut parts = id.as_str().splitn(2, "::");
417
418 let package_name = parts
419 .next()
420 .expect("splitn(2) returns at least 1 component");
421 let binary_name_and_kind = if let Some(suffix) = parts.next() {
422 let mut parts = suffix.splitn(2, '/');
423
424 let part1 = parts
425 .next()
426 .expect("splitn(2) returns at least 1 component");
427 if let Some(binary_name) = parts.next() {
428 RustBinaryIdNameAndKind::NameAndKind {
429 kind: part1,
430 binary_name,
431 }
432 } else {
433 RustBinaryIdNameAndKind::NameOnly { binary_name: part1 }
434 }
435 } else {
436 RustBinaryIdNameAndKind::None
437 };
438
439 Self {
440 package_name,
441 binary_name_and_kind,
442 }
443 }
444}
445
446#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
450pub enum RustBinaryIdNameAndKind<'a> {
451 None,
453
454 NameOnly {
456 binary_name: &'a str,
458 },
459
460 NameAndKind {
462 kind: &'a str,
464
465 binary_name: &'a str,
467 },
468}
469
470#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
472#[serde(rename_all = "kebab-case")]
473pub struct RustBuildMetaSummary {
474 pub target_directory: Utf8PathBuf,
476
477 pub base_output_directories: BTreeSet<Utf8PathBuf>,
479
480 pub non_test_binaries: BTreeMap<String, BTreeSet<RustNonTestBinarySummary>>,
482
483 #[serde(default)]
488 pub build_script_out_dirs: BTreeMap<String, Utf8PathBuf>,
489
490 pub linked_paths: BTreeSet<Utf8PathBuf>,
492
493 #[serde(default)]
497 pub platforms: Option<BuildPlatformsSummary>,
498
499 #[serde(default)]
503 pub target_platforms: Vec<PlatformSummary>,
504
505 #[serde(default)]
510 pub target_platform: Option<String>,
511}
512
513#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
516#[serde(rename_all = "kebab-case")]
517pub struct RustNonTestBinarySummary {
518 pub name: String,
520
521 pub kind: RustNonTestBinaryKind,
523
524 pub path: Utf8PathBuf,
526}
527
528#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
530#[serde(rename_all = "kebab-case")]
531pub struct BuildPlatformsSummary {
532 pub host: HostPlatformSummary,
534
535 pub targets: Vec<TargetPlatformSummary>,
539}
540
541#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
543#[serde(rename_all = "kebab-case")]
544pub struct HostPlatformSummary {
545 pub platform: PlatformSummary,
547
548 pub libdir: PlatformLibdirSummary,
550}
551
552#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
554#[serde(rename_all = "kebab-case")]
555pub struct TargetPlatformSummary {
556 pub platform: PlatformSummary,
558
559 pub libdir: PlatformLibdirSummary,
563}
564
565#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
567#[serde(tag = "status", rename_all = "kebab-case")]
568pub enum PlatformLibdirSummary {
569 Available {
571 path: Utf8PathBuf,
573 },
574
575 Unavailable {
577 reason: PlatformLibdirUnavailable,
579 },
580}
581
582#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
588pub struct PlatformLibdirUnavailable(pub Cow<'static, str>);
589
590impl PlatformLibdirUnavailable {
591 pub const RUSTC_FAILED: Self = Self::new_const("rustc-failed");
593
594 pub const RUSTC_OUTPUT_ERROR: Self = Self::new_const("rustc-output-error");
597
598 pub const OLD_SUMMARY: Self = Self::new_const("old-summary");
601
602 pub const NOT_IN_ARCHIVE: Self = Self::new_const("not-in-archive");
605
606 pub const fn new_const(reason: &'static str) -> Self {
608 Self(Cow::Borrowed(reason))
609 }
610
611 pub fn new(reason: impl Into<Cow<'static, str>>) -> Self {
613 Self(reason.into())
614 }
615
616 pub fn as_str(&self) -> &str {
618 &self.0
619 }
620}
621
622#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
627#[serde(transparent)]
628pub struct RustNonTestBinaryKind(pub Cow<'static, str>);
629
630impl RustNonTestBinaryKind {
631 #[inline]
633 pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
634 Self(kind.into())
635 }
636
637 #[inline]
639 pub const fn new_const(kind: &'static str) -> Self {
640 Self(Cow::Borrowed(kind))
641 }
642
643 pub fn as_str(&self) -> &str {
645 &self.0
646 }
647
648 pub const DYLIB: Self = Self::new_const("dylib");
651
652 pub const BIN_EXE: Self = Self::new_const("bin-exe");
654}
655
656impl fmt::Display for RustNonTestBinaryKind {
657 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658 write!(f, "{}", self.0)
659 }
660}
661
662#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
666#[serde(rename_all = "kebab-case")]
667pub struct RustTestSuiteSummary {
668 pub package_name: String,
670
671 #[serde(flatten)]
673 pub binary: RustTestBinarySummary,
674
675 pub cwd: Utf8PathBuf,
677
678 #[serde(default = "listed_status")]
683 pub status: RustTestSuiteStatusSummary,
684
685 #[serde(rename = "testcases")]
687 pub test_cases: BTreeMap<String, RustTestCaseSummary>,
688}
689
690fn listed_status() -> RustTestSuiteStatusSummary {
691 RustTestSuiteStatusSummary::LISTED
692}
693
694#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)]
698#[serde(transparent)]
699pub struct RustTestSuiteStatusSummary(pub Cow<'static, str>);
700
701impl RustTestSuiteStatusSummary {
702 #[inline]
704 pub fn new(kind: impl Into<Cow<'static, str>>) -> Self {
705 Self(kind.into())
706 }
707
708 #[inline]
710 pub const fn new_const(kind: &'static str) -> Self {
711 Self(Cow::Borrowed(kind))
712 }
713
714 pub fn as_str(&self) -> &str {
716 &self.0
717 }
718
719 pub const LISTED: Self = Self::new_const("listed");
722
723 pub const SKIPPED: Self = Self::new_const("skipped");
728
729 pub const SKIPPED_DEFAULT_FILTER: Self = Self::new_const("skipped-default-filter");
733}
734
735#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
739#[serde(rename_all = "kebab-case")]
740pub struct RustTestCaseSummary {
741 pub ignored: bool,
745
746 pub filter_match: FilterMatch,
750}
751
752#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
754#[serde(rename_all = "kebab-case", tag = "status")]
755pub enum FilterMatch {
756 Matches,
758
759 Mismatch {
761 reason: MismatchReason,
763 },
764}
765
766impl FilterMatch {
767 pub fn is_match(&self) -> bool {
769 matches!(self, FilterMatch::Matches)
770 }
771}
772
773#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
775#[serde(rename_all = "kebab-case")]
776#[non_exhaustive]
777pub enum MismatchReason {
778 Ignored,
780
781 String,
783
784 Expression,
786
787 Partition,
789
790 DefaultFilter,
794}
795
796impl fmt::Display for MismatchReason {
797 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
798 match self {
799 MismatchReason::Ignored => write!(f, "does not match the run-ignored option"),
800 MismatchReason::String => write!(f, "does not match the provided string filters"),
801 MismatchReason::Expression => {
802 write!(f, "does not match the provided expression filters")
803 }
804 MismatchReason::Partition => write!(f, "is in a different partition"),
805 MismatchReason::DefaultFilter => {
806 write!(f, "is filtered out by the profile's default-filter")
807 }
808 }
809 }
810}
811
812#[cfg(test)]
813mod tests {
814 use super::*;
815 use test_case::test_case;
816
817 #[test_case(r#"{
818 "target-directory": "/foo",
819 "base-output-directories": [],
820 "non-test-binaries": {},
821 "linked-paths": []
822 }"#, RustBuildMetaSummary {
823 target_directory: "/foo".into(),
824 base_output_directories: BTreeSet::new(),
825 non_test_binaries: BTreeMap::new(),
826 build_script_out_dirs: BTreeMap::new(),
827 linked_paths: BTreeSet::new(),
828 target_platform: None,
829 target_platforms: vec![],
830 platforms: None,
831 }; "no target platform")]
832 #[test_case(r#"{
833 "target-directory": "/foo",
834 "base-output-directories": [],
835 "non-test-binaries": {},
836 "linked-paths": [],
837 "target-platform": "x86_64-unknown-linux-gnu"
838 }"#, RustBuildMetaSummary {
839 target_directory: "/foo".into(),
840 base_output_directories: BTreeSet::new(),
841 non_test_binaries: BTreeMap::new(),
842 build_script_out_dirs: BTreeMap::new(),
843 linked_paths: BTreeSet::new(),
844 target_platform: Some("x86_64-unknown-linux-gnu".to_owned()),
845 target_platforms: vec![],
846 platforms: None,
847 }; "single target platform specified")]
848 fn test_deserialize_old_rust_build_meta(input: &str, expected: RustBuildMetaSummary) {
849 let build_meta: RustBuildMetaSummary =
850 serde_json::from_str(input).expect("input deserialized correctly");
851 assert_eq!(
852 build_meta, expected,
853 "deserialized input matched expected output"
854 );
855 }
856
857 #[test]
858 fn test_binary_id_ord() {
859 let empty = RustBinaryId::new("");
860 let foo = RustBinaryId::new("foo");
861 let bar = RustBinaryId::new("bar");
862 let foo_name1 = RustBinaryId::new("foo::name1");
863 let foo_name2 = RustBinaryId::new("foo::name2");
864 let bar_name = RustBinaryId::new("bar::name");
865 let foo_bin_name1 = RustBinaryId::new("foo::bin/name1");
866 let foo_bin_name2 = RustBinaryId::new("foo::bin/name2");
867 let bar_bin_name = RustBinaryId::new("bar::bin/name");
868 let foo_proc_macro_name = RustBinaryId::new("foo::proc_macro/name");
869 let bar_proc_macro_name = RustBinaryId::new("bar::proc_macro/name");
870
871 let sorted_ids = [
873 empty,
874 bar,
875 bar_name,
876 bar_bin_name,
877 bar_proc_macro_name,
878 foo,
879 foo_name1,
880 foo_name2,
881 foo_bin_name1,
882 foo_bin_name2,
883 foo_proc_macro_name,
884 ];
885
886 for (i, id) in sorted_ids.iter().enumerate() {
887 for (j, other_id) in sorted_ids.iter().enumerate() {
888 let expected = i.cmp(&j);
889 assert_eq!(
890 id.cmp(other_id),
891 expected,
892 "comparing {id:?} to {other_id:?} gave {expected:?}"
893 );
894 }
895 }
896 }
897}