1use crate::{
7 cargo_config::{TargetTriple, TargetTripleSource},
8 config::{
9 core::ConfigExperimental,
10 elements::{CustomTestGroup, TestGroup},
11 scripts::{ProfileScriptType, ScriptId, ScriptType},
12 },
13 helpers::{display_exited_with, dylib_path_envvar},
14 redact::Redactor,
15 reuse_build::{ArchiveFormat, ArchiveStep},
16 target_runner::PlatformRunnerSource,
17};
18use camino::{FromPathBufError, Utf8Path, Utf8PathBuf};
19use config::ConfigError;
20use indent_write::{fmt::IndentWriter, indentable::Indented};
21use itertools::{Either, Itertools};
22use nextest_filtering::errors::FiltersetParseErrors;
23use nextest_metadata::RustBinaryId;
24use smol_str::SmolStr;
25use std::{
26 borrow::Cow,
27 collections::BTreeSet,
28 env::JoinPathsError,
29 fmt::{self, Write as _},
30 process::ExitStatus,
31 sync::Arc,
32};
33use target_spec_miette::IntoMietteDiagnostic;
34use thiserror::Error;
35
36#[derive(Debug, Error)]
38#[error(
39 "failed to parse nextest config at `{config_file}`{}",
40 provided_by_tool(tool.as_deref())
41)]
42#[non_exhaustive]
43pub struct ConfigParseError {
44 config_file: Utf8PathBuf,
45 tool: Option<String>,
46 #[source]
47 kind: ConfigParseErrorKind,
48}
49
50impl ConfigParseError {
51 pub(crate) fn new(
52 config_file: impl Into<Utf8PathBuf>,
53 tool: Option<&str>,
54 kind: ConfigParseErrorKind,
55 ) -> Self {
56 Self {
57 config_file: config_file.into(),
58 tool: tool.map(|s| s.to_owned()),
59 kind,
60 }
61 }
62
63 pub fn config_file(&self) -> &Utf8Path {
65 &self.config_file
66 }
67
68 pub fn tool(&self) -> Option<&str> {
70 self.tool.as_deref()
71 }
72
73 pub fn kind(&self) -> &ConfigParseErrorKind {
75 &self.kind
76 }
77}
78
79pub fn provided_by_tool(tool: Option<&str>) -> String {
81 match tool {
82 Some(tool) => format!(" provided by tool `{tool}`"),
83 None => String::new(),
84 }
85}
86
87#[derive(Debug, Error)]
91#[non_exhaustive]
92pub enum ConfigParseErrorKind {
93 #[error(transparent)]
95 BuildError(Box<ConfigError>),
96 #[error(transparent)]
97 DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
99 #[error(transparent)]
101 VersionOnlyReadError(std::io::Error),
102 #[error(transparent)]
104 VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
105 #[error("error parsing compiled data (destructure this variant for more details)")]
107 CompileErrors(Vec<ConfigCompileError>),
108 #[error("invalid test groups defined: {}\n(test groups cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
110 InvalidTestGroupsDefined(BTreeSet<CustomTestGroup>),
111 #[error(
113 "invalid test groups defined by tool: {}\n(test groups must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
114 InvalidTestGroupsDefinedByTool(BTreeSet<CustomTestGroup>),
115 #[error("unknown test groups specified by config (destructure this variant for more details)")]
117 UnknownTestGroups {
118 errors: Vec<UnknownTestGroupError>,
120
121 known_groups: BTreeSet<TestGroup>,
123 },
124 #[error(
126 "both `[script.*]` and `[scripts.*]` defined\n\
127 (hint: [script.*] will be removed in the future: switch to [scripts.setup.*])"
128 )]
129 BothScriptAndScriptsDefined,
130 #[error("invalid config scripts defined: {}\n(config scripts cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
132 InvalidConfigScriptsDefined(BTreeSet<ScriptId>),
133 #[error(
135 "invalid config scripts defined by tool: {}\n(config scripts must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
136 InvalidConfigScriptsDefinedByTool(BTreeSet<ScriptId>),
137 #[error(
139 "config script names used more than once: {}\n\
140 (config script names must be unique across all script types)", .0.iter().join(", ")
141 )]
142 DuplicateConfigScriptNames(BTreeSet<ScriptId>),
143 #[error(
145 "errors in profile-specific config scripts (destructure this variant for more details)"
146 )]
147 ProfileScriptErrors {
148 errors: Box<ProfileScriptErrors>,
150
151 known_scripts: BTreeSet<ScriptId>,
153 },
154 #[error("unknown experimental features defined (destructure this variant for more details)")]
156 UnknownExperimentalFeatures {
157 unknown: BTreeSet<String>,
159
160 known: BTreeSet<ConfigExperimental>,
162 },
163 #[error(
167 "tool config file specifies experimental features `{}` \
168 -- only repository config files can do so",
169 .features.iter().join(", "),
170 )]
171 ExperimentalFeaturesInToolConfig {
172 features: BTreeSet<String>,
174 },
175 #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
177 ExperimentalFeaturesNotEnabled {
178 missing_features: BTreeSet<ConfigExperimental>,
180 },
181}
182
183#[derive(Debug)]
186#[non_exhaustive]
187pub struct ConfigCompileError {
188 pub profile_name: String,
190
191 pub section: ConfigCompileSection,
193
194 pub kind: ConfigCompileErrorKind,
196}
197
198#[derive(Debug)]
201pub enum ConfigCompileSection {
202 DefaultFilter,
204
205 Override(usize),
207
208 Script(usize),
210}
211
212#[derive(Debug)]
214#[non_exhaustive]
215pub enum ConfigCompileErrorKind {
216 ConstraintsNotSpecified {
218 default_filter_specified: bool,
223 },
224
225 FilterAndDefaultFilterSpecified,
229
230 Parse {
232 host_parse_error: Option<target_spec::Error>,
234
235 target_parse_error: Option<target_spec::Error>,
237
238 filter_parse_errors: Vec<FiltersetParseErrors>,
240 },
241}
242
243impl ConfigCompileErrorKind {
244 pub fn reports(&self) -> impl Iterator<Item = miette::Report> + '_ {
246 match self {
247 Self::ConstraintsNotSpecified {
248 default_filter_specified,
249 } => {
250 let message = if *default_filter_specified {
251 "for override with `default-filter`, `platform` must also be specified"
252 } else {
253 "at least one of `platform` and `filter` must be specified"
254 };
255 Either::Left(std::iter::once(miette::Report::msg(message)))
256 }
257 Self::FilterAndDefaultFilterSpecified => {
258 Either::Left(std::iter::once(miette::Report::msg(
259 "at most one of `filter` and `default-filter` must be specified",
260 )))
261 }
262 Self::Parse {
263 host_parse_error,
264 target_parse_error,
265 filter_parse_errors,
266 } => {
267 let host_parse_report = host_parse_error
268 .as_ref()
269 .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
270 let target_parse_report = target_parse_error
271 .as_ref()
272 .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
273 let filter_parse_reports =
274 filter_parse_errors.iter().flat_map(|filter_parse_errors| {
275 filter_parse_errors.errors.iter().map(|single_error| {
276 miette::Report::new(single_error.clone())
277 .with_source_code(filter_parse_errors.input.to_owned())
278 })
279 });
280
281 Either::Right(
282 host_parse_report
283 .into_iter()
284 .chain(target_parse_report)
285 .chain(filter_parse_reports),
286 )
287 }
288 }
289 }
290}
291
292#[derive(Clone, Debug, Error)]
294#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
295pub struct TestPriorityOutOfRange {
296 pub priority: i8,
298}
299
300#[derive(Clone, Debug, Error)]
302pub enum ChildStartError {
303 #[error("error creating temporary path for setup script")]
305 TempPath(#[source] Arc<std::io::Error>),
306
307 #[error("error spawning child process")]
309 Spawn(#[source] Arc<std::io::Error>),
310}
311
312#[derive(Clone, Debug, Error)]
314pub enum SetupScriptOutputError {
315 #[error("error opening environment file `{path}`")]
317 EnvFileOpen {
318 path: Utf8PathBuf,
320
321 #[source]
323 error: Arc<std::io::Error>,
324 },
325
326 #[error("error reading environment file `{path}`")]
328 EnvFileRead {
329 path: Utf8PathBuf,
331
332 #[source]
334 error: Arc<std::io::Error>,
335 },
336
337 #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
339 EnvFileParse {
340 path: Utf8PathBuf,
342 line: String,
344 },
345
346 #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
348 EnvFileReservedKey {
349 key: String,
351 },
352}
353
354#[derive(Clone, Debug)]
359pub struct ErrorList<T> {
360 description: &'static str,
362 inner: Vec<T>,
364}
365
366impl<T: std::error::Error> ErrorList<T> {
367 pub(crate) fn new<U>(description: &'static str, errors: Vec<U>) -> Option<Self>
368 where
369 T: From<U>,
370 {
371 if errors.is_empty() {
372 None
373 } else {
374 Some(Self {
375 description,
376 inner: errors.into_iter().map(T::from).collect(),
377 })
378 }
379 }
380
381 pub(crate) fn short_message(&self) -> String {
383 let string = self.to_string();
384 match string.lines().next() {
385 Some(first_line) => first_line.trim_end_matches(':').to_string(),
387 None => String::new(),
388 }
389 }
390
391 pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
392 self.inner.iter()
393 }
394}
395
396impl<T: std::error::Error> fmt::Display for ErrorList<T> {
397 fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
398 if self.inner.len() == 1 {
400 return write!(f, "{}", self.inner[0]);
401 }
402
403 writeln!(
405 f,
406 "{} errors occurred {}:",
407 self.inner.len(),
408 self.description,
409 )?;
410 for error in &self.inner {
411 let mut indent = IndentWriter::new_skip_initial(" ", f);
412 writeln!(indent, "* {}", DisplayErrorChain::new(error))?;
413 f = indent.into_inner();
414 }
415 Ok(())
416 }
417}
418
419impl<T: std::error::Error> std::error::Error for ErrorList<T> {
420 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
421 if self.inner.len() == 1 {
422 self.inner[0].source()
423 } else {
424 None
427 }
428 }
429}
430
431pub(crate) struct DisplayErrorChain<E> {
436 error: E,
437 initial_indent: &'static str,
438}
439
440impl<E: std::error::Error> DisplayErrorChain<E> {
441 pub(crate) fn new(error: E) -> Self {
442 Self {
443 error,
444 initial_indent: "",
445 }
446 }
447
448 pub(crate) fn new_with_initial_indent(initial_indent: &'static str, error: E) -> Self {
449 Self {
450 error,
451 initial_indent,
452 }
453 }
454}
455
456impl<E> fmt::Display for DisplayErrorChain<E>
457where
458 E: std::error::Error,
459{
460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461 let mut writer = IndentWriter::new(self.initial_indent, f);
462 write!(writer, "{}", self.error)?;
463
464 let Some(mut cause) = self.error.source() else {
465 return Ok(());
466 };
467
468 write!(writer, "\n caused by:")?;
469
470 loop {
471 writeln!(writer)?;
472 let mut indent = IndentWriter::new_skip_initial(" ", writer);
473 write!(indent, " - {cause}")?;
474
475 let Some(next_cause) = cause.source() else {
476 break Ok(());
477 };
478
479 cause = next_cause;
480 writer = indent.into_inner();
481 }
482 }
483}
484
485#[derive(Clone, Debug, Error)]
487pub enum ChildError {
488 #[error(transparent)]
490 Fd(#[from] ChildFdError),
491
492 #[error(transparent)]
494 SetupScriptOutput(#[from] SetupScriptOutputError),
495}
496
497#[derive(Clone, Debug, Error)]
499pub enum ChildFdError {
500 #[error("error reading standard output")]
502 ReadStdout(#[source] Arc<std::io::Error>),
503
504 #[error("error reading standard error")]
506 ReadStderr(#[source] Arc<std::io::Error>),
507
508 #[error("error reading combined stream")]
510 ReadCombined(#[source] Arc<std::io::Error>),
511
512 #[error("error waiting for child process to exit")]
514 Wait(#[source] Arc<std::io::Error>),
515}
516
517#[derive(Clone, Debug, Eq, PartialEq)]
519#[non_exhaustive]
520pub struct UnknownTestGroupError {
521 pub profile_name: String,
523
524 pub name: TestGroup,
526}
527
528#[derive(Clone, Debug, Eq, PartialEq)]
531pub struct ProfileUnknownScriptError {
532 pub profile_name: String,
534
535 pub name: ScriptId,
537}
538
539#[derive(Clone, Debug, Eq, PartialEq)]
542pub struct ProfileWrongConfigScriptTypeError {
543 pub profile_name: String,
545
546 pub name: ScriptId,
548
549 pub attempted: ProfileScriptType,
551
552 pub actual: ScriptType,
554}
555
556#[derive(Clone, Debug, Eq, PartialEq)]
559pub struct ProfileListScriptUsesRunFiltersError {
560 pub profile_name: String,
562
563 pub name: ScriptId,
565
566 pub script_type: ProfileScriptType,
568
569 pub filters: BTreeSet<String>,
571}
572
573#[derive(Clone, Debug, Default)]
575pub struct ProfileScriptErrors {
576 pub unknown_scripts: Vec<ProfileUnknownScriptError>,
578
579 pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
581
582 pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
584}
585
586impl ProfileScriptErrors {
587 pub fn is_empty(&self) -> bool {
589 self.unknown_scripts.is_empty()
590 && self.wrong_script_types.is_empty()
591 && self.list_scripts_using_run_filters.is_empty()
592 }
593}
594
595#[derive(Clone, Debug, Error)]
597#[error("profile `{profile} not found (known profiles: {})`", .all_profiles.join(", "))]
598pub struct ProfileNotFound {
599 profile: String,
600 all_profiles: Vec<String>,
601}
602
603impl ProfileNotFound {
604 pub(crate) fn new(
605 profile: impl Into<String>,
606 all_profiles: impl IntoIterator<Item = impl Into<String>>,
607 ) -> Self {
608 let mut all_profiles: Vec<_> = all_profiles.into_iter().map(|s| s.into()).collect();
609 all_profiles.sort_unstable();
610 Self {
611 profile: profile.into(),
612 all_profiles,
613 }
614 }
615}
616
617#[derive(Clone, Debug, Error, Eq, PartialEq)]
619pub enum InvalidIdentifier {
620 #[error("identifier is empty")]
622 Empty,
623
624 #[error("invalid identifier `{0}`")]
626 InvalidXid(SmolStr),
627
628 #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
630 ToolIdentifierInvalidFormat(SmolStr),
631
632 #[error("tool identifier has empty component: `{0}`")]
634 ToolComponentEmpty(SmolStr),
635
636 #[error("invalid tool identifier `{0}`")]
638 ToolIdentifierInvalidXid(SmolStr),
639}
640
641#[derive(Clone, Debug, Error)]
643#[error("invalid custom test group name: {0}")]
644pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
645
646#[derive(Clone, Debug, Error)]
648#[error("invalid configuration script name: {0}")]
649pub struct InvalidConfigScriptName(pub InvalidIdentifier);
650
651#[derive(Clone, Debug, Error)]
653pub enum ToolConfigFileParseError {
654 #[error(
655 "tool-config-file has invalid format: {input}\n(hint: tool configs must be in the format <tool-name>:<path>)"
656 )]
657 InvalidFormat {
659 input: String,
661 },
662
663 #[error("tool-config-file has empty tool name: {input}")]
665 EmptyToolName {
666 input: String,
668 },
669
670 #[error("tool-config-file has empty config file path: {input}")]
672 EmptyConfigFile {
673 input: String,
675 },
676
677 #[error("tool-config-file is not an absolute path: {config_file}")]
679 ConfigFileNotAbsolute {
680 config_file: Utf8PathBuf,
682 },
683}
684
685#[derive(Clone, Debug, Error)]
687#[error(
688 "unrecognized value for max-fail: {input}\n(hint: expected either a positive integer or \"all\")"
689)]
690pub struct MaxFailParseError {
691 pub input: String,
693}
694
695impl MaxFailParseError {
696 pub(crate) fn new(input: impl Into<String>) -> Self {
697 Self {
698 input: input.into(),
699 }
700 }
701}
702
703#[derive(Clone, Debug, Error)]
705#[error(
706 "unrecognized value for stress-count: {input}\n\
707 (hint: expected either a positive integer or \"infinite\")"
708)]
709pub struct StressCountParseError {
710 pub input: String,
712}
713
714impl StressCountParseError {
715 pub(crate) fn new(input: impl Into<String>) -> Self {
716 Self {
717 input: input.into(),
718 }
719 }
720}
721
722#[derive(Clone, Debug, Error)]
724#[error(
725 "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
726)]
727pub struct TestThreadsParseError {
728 pub input: String,
730}
731
732impl TestThreadsParseError {
733 pub(crate) fn new(input: impl Into<String>) -> Self {
734 Self {
735 input: input.into(),
736 }
737 }
738}
739
740#[derive(Clone, Debug, Error)]
743pub struct PartitionerBuilderParseError {
744 expected_format: Option<&'static str>,
745 message: Cow<'static, str>,
746}
747
748impl PartitionerBuilderParseError {
749 pub(crate) fn new(
750 expected_format: Option<&'static str>,
751 message: impl Into<Cow<'static, str>>,
752 ) -> Self {
753 Self {
754 expected_format,
755 message: message.into(),
756 }
757 }
758}
759
760impl fmt::Display for PartitionerBuilderParseError {
761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762 match self.expected_format {
763 Some(format) => {
764 write!(
765 f,
766 "partition must be in the format \"{}\":\n{}",
767 format, self.message
768 )
769 }
770 None => write!(f, "{}", self.message),
771 }
772 }
773}
774
775#[derive(Clone, Debug, Error)]
778pub enum TestFilterBuilderError {
779 #[error("error constructing test filters")]
781 Construct {
782 #[from]
784 error: aho_corasick::BuildError,
785 },
786}
787
788#[derive(Debug, Error)]
790pub enum PathMapperConstructError {
791 #[error("{kind} `{input}` failed to canonicalize")]
793 Canonicalization {
794 kind: PathMapperConstructKind,
796
797 input: Utf8PathBuf,
799
800 #[source]
802 err: std::io::Error,
803 },
804 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
806 NonUtf8Path {
807 kind: PathMapperConstructKind,
809
810 input: Utf8PathBuf,
812
813 #[source]
815 err: FromPathBufError,
816 },
817 #[error("{kind} `{canonicalized_path}` is not a directory")]
819 NotADirectory {
820 kind: PathMapperConstructKind,
822
823 input: Utf8PathBuf,
825
826 canonicalized_path: Utf8PathBuf,
828 },
829}
830
831impl PathMapperConstructError {
832 pub fn kind(&self) -> PathMapperConstructKind {
834 match self {
835 Self::Canonicalization { kind, .. }
836 | Self::NonUtf8Path { kind, .. }
837 | Self::NotADirectory { kind, .. } => *kind,
838 }
839 }
840
841 pub fn input(&self) -> &Utf8Path {
843 match self {
844 Self::Canonicalization { input, .. }
845 | Self::NonUtf8Path { input, .. }
846 | Self::NotADirectory { input, .. } => input,
847 }
848 }
849}
850
851#[derive(Copy, Clone, Debug, PartialEq, Eq)]
856pub enum PathMapperConstructKind {
857 WorkspaceRoot,
859
860 TargetDir,
862}
863
864impl fmt::Display for PathMapperConstructKind {
865 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
866 match self {
867 Self::WorkspaceRoot => write!(f, "remapped workspace root"),
868 Self::TargetDir => write!(f, "remapped target directory"),
869 }
870 }
871}
872
873#[derive(Debug, Error)]
875pub enum RustBuildMetaParseError {
876 #[error("error deserializing platform from build metadata")]
878 PlatformDeserializeError(#[from] target_spec::Error),
879
880 #[error("the host platform could not be determined")]
882 DetectBuildTargetError(#[source] target_spec::Error),
883
884 #[error("unsupported features in the build metadata: {message}")]
886 Unsupported {
887 message: String,
889 },
890}
891
892#[derive(Clone, Debug, thiserror::Error)]
895#[error("invalid format version: {input}")]
896pub struct FormatVersionError {
897 pub input: String,
899 #[source]
901 pub error: FormatVersionErrorInner,
902}
903
904#[derive(Clone, Debug, thiserror::Error)]
906pub enum FormatVersionErrorInner {
907 #[error("expected format version in form of `{expected}`")]
909 InvalidFormat {
910 expected: &'static str,
912 },
913 #[error("version component `{which}` could not be parsed as an integer")]
915 InvalidInteger {
916 which: &'static str,
918 #[source]
920 err: std::num::ParseIntError,
921 },
922 #[error("version component `{which}` value {value} is out of range {range:?}")]
924 InvalidValue {
925 which: &'static str,
927 value: u8,
929 range: std::ops::Range<u8>,
931 },
932}
933
934#[derive(Debug, Error)]
937#[non_exhaustive]
938pub enum FromMessagesError {
939 #[error("error reading Cargo JSON messages")]
941 ReadMessages(#[source] std::io::Error),
942
943 #[error("error querying package graph")]
945 PackageGraph(#[source] guppy::Error),
946
947 #[error("missing kind for target {binary_name} in package {package_name}")]
949 MissingTargetKind {
950 package_name: String,
952 binary_name: String,
954 },
955}
956
957#[derive(Debug, Error)]
959#[non_exhaustive]
960pub enum CreateTestListError {
961 #[error(
963 "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
964 (hint: ensure project source is available at this location)"
965 )]
966 CwdIsNotDir {
967 binary_id: RustBinaryId,
969
970 cwd: Utf8PathBuf,
972 },
973
974 #[error(
976 "for `{binary_id}`, running command `{}` failed to execute",
977 shell_words::join(command)
978 )]
979 CommandExecFail {
980 binary_id: RustBinaryId,
982
983 command: Vec<String>,
985
986 #[source]
988 error: std::io::Error,
989 },
990
991 #[error(
993 "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
994 shell_words::join(command),
995 display_exited_with(*exit_status),
996 String::from_utf8_lossy(stdout),
997 String::from_utf8_lossy(stderr),
998 )]
999 CommandFail {
1000 binary_id: RustBinaryId,
1002
1003 command: Vec<String>,
1005
1006 exit_status: ExitStatus,
1008
1009 stdout: Vec<u8>,
1011
1012 stderr: Vec<u8>,
1014 },
1015
1016 #[error(
1018 "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1019 shell_words::join(command),
1020 String::from_utf8_lossy(stdout),
1021 String::from_utf8_lossy(stderr)
1022 )]
1023 CommandNonUtf8 {
1024 binary_id: RustBinaryId,
1026
1027 command: Vec<String>,
1029
1030 stdout: Vec<u8>,
1032
1033 stderr: Vec<u8>,
1035 },
1036
1037 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1039 ParseLine {
1040 binary_id: RustBinaryId,
1042
1043 message: Cow<'static, str>,
1045
1046 full_output: String,
1048 },
1049
1050 #[error(
1052 "error joining dynamic library paths for {}: [{}]",
1053 dylib_path_envvar(),
1054 itertools::join(.new_paths, ", ")
1055 )]
1056 DylibJoinPaths {
1057 new_paths: Vec<Utf8PathBuf>,
1059
1060 #[source]
1062 error: JoinPathsError,
1063 },
1064
1065 #[error("error creating Tokio runtime")]
1067 TokioRuntimeCreate(#[source] std::io::Error),
1068}
1069
1070impl CreateTestListError {
1071 pub(crate) fn parse_line(
1072 binary_id: RustBinaryId,
1073 message: impl Into<Cow<'static, str>>,
1074 full_output: impl Into<String>,
1075 ) -> Self {
1076 Self::ParseLine {
1077 binary_id,
1078 message: message.into(),
1079 full_output: full_output.into(),
1080 }
1081 }
1082
1083 pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1084 Self::DylibJoinPaths { new_paths, error }
1085 }
1086}
1087
1088#[derive(Debug, Error)]
1090#[non_exhaustive]
1091pub enum WriteTestListError {
1092 #[error("error writing to output")]
1094 Io(#[source] std::io::Error),
1095
1096 #[error("error serializing to JSON")]
1098 Json(#[source] serde_json::Error),
1099}
1100
1101#[derive(Debug, Error)]
1105pub enum ConfigureHandleInheritanceError {
1106 #[cfg(windows)]
1108 #[error("error configuring handle inheritance")]
1109 WindowsError(#[from] std::io::Error),
1110}
1111
1112#[derive(Debug, Error)]
1114#[non_exhaustive]
1115pub enum TestRunnerBuildError {
1116 #[error("error creating Tokio runtime")]
1118 TokioRuntimeCreate(#[source] std::io::Error),
1119
1120 #[error("error setting up signals")]
1122 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1123}
1124
1125#[derive(Debug, Error)]
1127pub struct TestRunnerExecuteErrors<E> {
1128 pub report_error: Option<E>,
1130
1131 pub join_errors: Vec<tokio::task::JoinError>,
1134}
1135
1136impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138 if let Some(report_error) = &self.report_error {
1139 write!(f, "error reporting results: {report_error}")?;
1140 }
1141
1142 if !self.join_errors.is_empty() {
1143 if self.report_error.is_some() {
1144 write!(f, "; ")?;
1145 }
1146
1147 write!(f, "errors joining tasks: ")?;
1148
1149 for (i, join_error) in self.join_errors.iter().enumerate() {
1150 if i > 0 {
1151 write!(f, ", ")?;
1152 }
1153
1154 write!(f, "{join_error}")?;
1155 }
1156 }
1157
1158 Ok(())
1159 }
1160}
1161
1162#[derive(Debug, Error)]
1166#[error(
1167 "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1168 supported_extensions()
1169)]
1170pub struct UnknownArchiveFormat {
1171 pub file_name: String,
1173}
1174
1175fn supported_extensions() -> String {
1176 ArchiveFormat::SUPPORTED_FORMATS
1177 .iter()
1178 .map(|(extension, _)| *extension)
1179 .join(", ")
1180}
1181
1182#[derive(Debug, Error)]
1184#[non_exhaustive]
1185pub enum ArchiveCreateError {
1186 #[error("error creating binary list")]
1188 CreateBinaryList(#[source] WriteTestListError),
1189
1190 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1192 MissingExtraPath {
1193 path: Utf8PathBuf,
1195
1196 redactor: Redactor,
1201 },
1202
1203 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1205 InputFileRead {
1206 step: ArchiveStep,
1208
1209 path: Utf8PathBuf,
1211
1212 is_dir: Option<bool>,
1214
1215 #[source]
1217 error: std::io::Error,
1218 },
1219
1220 #[error("error reading directory entry from `{path}")]
1222 DirEntryRead {
1223 path: Utf8PathBuf,
1225
1226 #[source]
1228 error: std::io::Error,
1229 },
1230
1231 #[error("error writing to archive")]
1233 OutputArchiveIo(#[source] std::io::Error),
1234
1235 #[error("error reporting archive status")]
1237 ReporterIo(#[source] std::io::Error),
1238}
1239
1240fn kind_str(is_dir: Option<bool>) -> &'static str {
1241 match is_dir {
1242 Some(true) => "directory",
1243 Some(false) => "file",
1244 None => "path",
1245 }
1246}
1247
1248#[derive(Debug, Error)]
1250pub enum MetadataMaterializeError {
1251 #[error("I/O error reading metadata file `{path}`")]
1253 Read {
1254 path: Utf8PathBuf,
1256
1257 #[source]
1259 error: std::io::Error,
1260 },
1261
1262 #[error("error deserializing metadata file `{path}`")]
1264 Deserialize {
1265 path: Utf8PathBuf,
1267
1268 #[source]
1270 error: serde_json::Error,
1271 },
1272
1273 #[error("error parsing Rust build metadata from `{path}`")]
1275 RustBuildMeta {
1276 path: Utf8PathBuf,
1278
1279 #[source]
1281 error: RustBuildMetaParseError,
1282 },
1283
1284 #[error("error building package graph from `{path}`")]
1286 PackageGraphConstruct {
1287 path: Utf8PathBuf,
1289
1290 #[source]
1292 error: guppy::Error,
1293 },
1294}
1295
1296#[derive(Debug, Error)]
1300#[non_exhaustive]
1301pub enum ArchiveReadError {
1302 #[error("I/O error reading archive")]
1304 Io(#[source] std::io::Error),
1305
1306 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1308 NonUtf8Path(Vec<u8>),
1309
1310 #[error("path in archive `{0}` doesn't start with `target/`")]
1312 NoTargetPrefix(Utf8PathBuf),
1313
1314 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1316 InvalidComponent {
1317 path: Utf8PathBuf,
1319
1320 component: String,
1322 },
1323
1324 #[error("corrupted archive: checksum read error for path `{path}`")]
1326 ChecksumRead {
1327 path: Utf8PathBuf,
1329
1330 #[source]
1332 error: std::io::Error,
1333 },
1334
1335 #[error("corrupted archive: invalid checksum for path `{path}`")]
1337 InvalidChecksum {
1338 path: Utf8PathBuf,
1340
1341 expected: u32,
1343
1344 actual: u32,
1346 },
1347
1348 #[error("metadata file `{0}` not found in archive")]
1350 MetadataFileNotFound(&'static Utf8Path),
1351
1352 #[error("error deserializing metadata file `{path}` in archive")]
1354 MetadataDeserializeError {
1355 path: &'static Utf8Path,
1357
1358 #[source]
1360 error: serde_json::Error,
1361 },
1362
1363 #[error("error building package graph from `{path}` in archive")]
1365 PackageGraphConstructError {
1366 path: &'static Utf8Path,
1368
1369 #[source]
1371 error: guppy::Error,
1372 },
1373}
1374
1375#[derive(Debug, Error)]
1379#[non_exhaustive]
1380pub enum ArchiveExtractError {
1381 #[error("error creating temporary directory")]
1383 TempDirCreate(#[source] std::io::Error),
1384
1385 #[error("error canonicalizing destination directory `{dir}`")]
1387 DestDirCanonicalization {
1388 dir: Utf8PathBuf,
1390
1391 #[source]
1393 error: std::io::Error,
1394 },
1395
1396 #[error("destination `{0}` already exists")]
1398 DestinationExists(Utf8PathBuf),
1399
1400 #[error("error reading archive")]
1402 Read(#[source] ArchiveReadError),
1403
1404 #[error("error deserializing Rust build metadata")]
1406 RustBuildMeta(#[from] RustBuildMetaParseError),
1407
1408 #[error("error writing file `{path}` to disk")]
1410 WriteFile {
1411 path: Utf8PathBuf,
1413
1414 #[source]
1416 error: std::io::Error,
1417 },
1418
1419 #[error("error reporting extract status")]
1421 ReporterIo(std::io::Error),
1422}
1423
1424#[derive(Debug, Error)]
1426#[non_exhaustive]
1427pub enum WriteEventError {
1428 #[error("error writing to output")]
1430 Io(#[source] std::io::Error),
1431
1432 #[error("error operating on path {file}")]
1434 Fs {
1435 file: Utf8PathBuf,
1437
1438 #[source]
1440 error: std::io::Error,
1441 },
1442
1443 #[error("error writing JUnit output to {file}")]
1445 Junit {
1446 file: Utf8PathBuf,
1448
1449 #[source]
1451 error: quick_junit::SerializeError,
1452 },
1453}
1454
1455#[derive(Debug, Error)]
1458#[non_exhaustive]
1459pub enum CargoConfigError {
1460 #[error("failed to retrieve current directory")]
1462 GetCurrentDir(#[source] std::io::Error),
1463
1464 #[error("current directory is invalid UTF-8")]
1466 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1467
1468 #[error("failed to parse --config argument `{config_str}` as TOML")]
1470 CliConfigParseError {
1471 config_str: String,
1473
1474 #[source]
1476 error: toml_edit::TomlError,
1477 },
1478
1479 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1481 CliConfigDeError {
1482 config_str: String,
1484
1485 #[source]
1487 error: toml_edit::de::Error,
1488 },
1489
1490 #[error(
1492 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1493 )]
1494 InvalidCliConfig {
1495 config_str: String,
1497
1498 #[source]
1500 reason: InvalidCargoCliConfigReason,
1501 },
1502
1503 #[error("non-UTF-8 path encountered")]
1505 NonUtf8Path(#[source] FromPathBufError),
1506
1507 #[error("failed to retrieve the Cargo home directory")]
1509 GetCargoHome(#[source] std::io::Error),
1510
1511 #[error("failed to canonicalize path `{path}")]
1513 FailedPathCanonicalization {
1514 path: Utf8PathBuf,
1516
1517 #[source]
1519 error: std::io::Error,
1520 },
1521
1522 #[error("failed to read config at `{path}`")]
1524 ConfigReadError {
1525 path: Utf8PathBuf,
1527
1528 #[source]
1530 error: std::io::Error,
1531 },
1532
1533 #[error(transparent)]
1535 ConfigParseError(#[from] Box<CargoConfigParseError>),
1536}
1537
1538#[derive(Debug, Error)]
1542#[error("failed to parse config at `{path}`")]
1543pub struct CargoConfigParseError {
1544 pub path: Utf8PathBuf,
1546
1547 #[source]
1549 pub error: toml::de::Error,
1550}
1551
1552#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1556#[non_exhaustive]
1557pub enum InvalidCargoCliConfigReason {
1558 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1560 NotDottedKv,
1561
1562 #[error("includes non-whitespace decoration")]
1564 IncludesNonWhitespaceDecoration,
1565
1566 #[error("sets a value to an inline table, which is not accepted")]
1568 SetsValueToInlineTable,
1569
1570 #[error("sets a value to an array of tables, which is not accepted")]
1572 SetsValueToArrayOfTables,
1573
1574 #[error("doesn't provide a value")]
1576 DoesntProvideValue,
1577}
1578
1579#[derive(Debug, Error)]
1581pub enum HostPlatformDetectError {
1582 #[error(
1585 "error spawning `rustc -vV`, and detecting the build \
1586 target failed as well\n\
1587 - rustc spawn error: {}\n\
1588 - build target error: {}\n",
1589 DisplayErrorChain::new_with_initial_indent(" ", error),
1590 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1591 )]
1592 RustcVvSpawnError {
1593 error: std::io::Error,
1595
1596 build_target_error: Box<target_spec::Error>,
1598 },
1599
1600 #[error(
1603 "`rustc -vV` failed with {}, and detecting the \
1604 build target failed as well\n\
1605 - `rustc -vV` stdout:\n{}\n\
1606 - `rustc -vV` stderr:\n{}\n\
1607 - build target error:\n{}\n",
1608 status,
1609 Indented { item: String::from_utf8_lossy(stdout), indent: " " },
1610 Indented { item: String::from_utf8_lossy(stderr), indent: " " },
1611 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1612 )]
1613 RustcVvFailed {
1614 status: ExitStatus,
1616
1617 stdout: Vec<u8>,
1619
1620 stderr: Vec<u8>,
1622
1623 build_target_error: Box<target_spec::Error>,
1625 },
1626
1627 #[error(
1630 "parsing `rustc -vV` output failed, and detecting the build target \
1631 failed as well\n\
1632 - host platform error:\n{}\n\
1633 - build target error:\n{}\n",
1634 DisplayErrorChain::new_with_initial_indent(" ", host_platform_error),
1635 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1636 )]
1637 HostPlatformParseError {
1638 host_platform_error: Box<target_spec::Error>,
1640
1641 build_target_error: Box<target_spec::Error>,
1643 },
1644
1645 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1648 BuildTargetError {
1649 #[source]
1651 build_target_error: Box<target_spec::Error>,
1652 },
1653}
1654
1655#[derive(Debug, Error)]
1657pub enum TargetTripleError {
1658 #[error(
1660 "environment variable '{}' contained non-UTF-8 data",
1661 TargetTriple::CARGO_BUILD_TARGET_ENV
1662 )]
1663 InvalidEnvironmentVar,
1664
1665 #[error("error deserializing target triple from {source}")]
1667 TargetSpecError {
1668 source: TargetTripleSource,
1670
1671 #[source]
1673 error: target_spec::Error,
1674 },
1675
1676 #[error("target path `{path}` is not a valid file")]
1678 TargetPathReadError {
1679 source: TargetTripleSource,
1681
1682 path: Utf8PathBuf,
1684
1685 #[source]
1687 error: std::io::Error,
1688 },
1689
1690 #[error(
1692 "for custom platform obtained from {source}, \
1693 failed to create temporary directory for custom platform"
1694 )]
1695 CustomPlatformTempDirError {
1696 source: TargetTripleSource,
1698
1699 #[source]
1701 error: std::io::Error,
1702 },
1703
1704 #[error(
1706 "for custom platform obtained from {source}, \
1707 failed to write JSON to temporary path `{path}`"
1708 )]
1709 CustomPlatformWriteError {
1710 source: TargetTripleSource,
1712
1713 path: Utf8PathBuf,
1715
1716 #[source]
1718 error: std::io::Error,
1719 },
1720
1721 #[error(
1723 "for custom platform obtained from {source}, \
1724 failed to close temporary directory `{dir_path}`"
1725 )]
1726 CustomPlatformCloseError {
1727 source: TargetTripleSource,
1729
1730 dir_path: Utf8PathBuf,
1732
1733 #[source]
1735 error: std::io::Error,
1736 },
1737}
1738
1739impl TargetTripleError {
1740 pub fn source_report(&self) -> Option<miette::Report> {
1745 match self {
1746 Self::TargetSpecError { error, .. } => {
1747 Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1748 }
1749 TargetTripleError::InvalidEnvironmentVar
1751 | TargetTripleError::TargetPathReadError { .. }
1752 | TargetTripleError::CustomPlatformTempDirError { .. }
1753 | TargetTripleError::CustomPlatformWriteError { .. }
1754 | TargetTripleError::CustomPlatformCloseError { .. } => None,
1755 }
1756 }
1757}
1758
1759#[derive(Debug, Error)]
1761pub enum TargetRunnerError {
1762 #[error("environment variable '{0}' contained non-UTF-8 data")]
1764 InvalidEnvironmentVar(String),
1765
1766 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1769 BinaryNotSpecified {
1770 key: PlatformRunnerSource,
1772
1773 value: String,
1775 },
1776}
1777
1778#[derive(Debug, Error)]
1780#[error("error setting up signal handler")]
1781pub struct SignalHandlerSetupError(#[from] std::io::Error);
1782
1783#[derive(Debug, Error)]
1785pub enum ShowTestGroupsError {
1786 #[error(
1788 "unknown test groups specified: {}\n(known groups: {})",
1789 unknown_groups.iter().join(", "),
1790 known_groups.iter().join(", "),
1791 )]
1792 UnknownGroups {
1793 unknown_groups: BTreeSet<TestGroup>,
1795
1796 known_groups: BTreeSet<TestGroup>,
1798 },
1799}
1800
1801#[cfg(feature = "self-update")]
1802mod self_update_errors {
1803 use super::*;
1804 use mukti_metadata::ReleaseStatus;
1805 use semver::{Version, VersionReq};
1806
1807 #[cfg(feature = "self-update")]
1811 #[derive(Debug, Error)]
1812 #[non_exhaustive]
1813 pub enum UpdateError {
1814 #[error("failed to read release metadata from `{path}`")]
1816 ReadLocalMetadata {
1817 path: Utf8PathBuf,
1819
1820 #[source]
1822 error: std::io::Error,
1823 },
1824
1825 #[error("self-update failed")]
1827 SelfUpdate(#[source] self_update::errors::Error),
1828
1829 #[error("deserializing release metadata failed")]
1831 ReleaseMetadataDe(#[source] serde_json::Error),
1832
1833 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1835 VersionNotFound {
1836 version: Version,
1838
1839 known: Vec<(Version, ReleaseStatus)>,
1841 },
1842
1843 #[error("no version found matching requirement `{req}`")]
1845 NoMatchForVersionReq {
1846 req: VersionReq,
1848 },
1849
1850 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1852 MuktiProjectNotFound {
1853 not_found: String,
1855
1856 known: Vec<String>,
1858 },
1859
1860 #[error(
1862 "for version {version}, no release information found for target `{triple}` \
1863 (known targets: {})",
1864 known_triples.iter().join(", ")
1865 )]
1866 NoTargetData {
1867 version: Version,
1869
1870 triple: String,
1872
1873 known_triples: BTreeSet<String>,
1875 },
1876
1877 #[error("the current executable's path could not be determined")]
1879 CurrentExe(#[source] std::io::Error),
1880
1881 #[error("temporary directory could not be created at `{location}`")]
1883 TempDirCreate {
1884 location: Utf8PathBuf,
1886
1887 #[source]
1889 error: std::io::Error,
1890 },
1891
1892 #[error("temporary archive could not be created at `{archive_path}`")]
1894 TempArchiveCreate {
1895 archive_path: Utf8PathBuf,
1897
1898 #[source]
1900 error: std::io::Error,
1901 },
1902
1903 #[error("error writing to temporary archive at `{archive_path}`")]
1905 TempArchiveWrite {
1906 archive_path: Utf8PathBuf,
1908
1909 #[source]
1911 error: std::io::Error,
1912 },
1913
1914 #[error("error reading from temporary archive at `{archive_path}`")]
1916 TempArchiveRead {
1917 archive_path: Utf8PathBuf,
1919
1920 #[source]
1922 error: std::io::Error,
1923 },
1924
1925 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1927 ChecksumMismatch {
1928 expected: String,
1930
1931 actual: String,
1933 },
1934
1935 #[error("error renaming `{source}` to `{dest}`")]
1937 FsRename {
1938 source: Utf8PathBuf,
1940
1941 dest: Utf8PathBuf,
1943
1944 #[source]
1946 error: std::io::Error,
1947 },
1948
1949 #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
1951 SelfSetup(#[source] std::io::Error),
1952 }
1953
1954 fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
1955 use std::fmt::Write;
1956
1957 const DISPLAY_COUNT: usize = 4;
1959
1960 let display_versions: Vec<_> = versions
1961 .iter()
1962 .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
1963 .map(|(v, _)| v.to_string())
1964 .take(DISPLAY_COUNT)
1965 .collect();
1966 let mut display_str = display_versions.join(", ");
1967 if versions.len() > display_versions.len() {
1968 write!(
1969 display_str,
1970 " and {} others",
1971 versions.len() - display_versions.len()
1972 )
1973 .unwrap();
1974 }
1975
1976 display_str
1977 }
1978
1979 #[cfg(feature = "self-update")]
1980 #[derive(Debug, Error)]
1982 pub enum UpdateVersionParseError {
1983 #[error("version string is empty")]
1985 EmptyString,
1986
1987 #[error(
1989 "`{input}` is not a valid semver requirement\n\
1990 (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
1991 )]
1992 InvalidVersionReq {
1993 input: String,
1995
1996 #[source]
1998 error: semver::Error,
1999 },
2000
2001 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2003 InvalidVersion {
2004 input: String,
2006
2007 #[source]
2009 error: semver::Error,
2010 },
2011 }
2012
2013 fn extra_semver_output(input: &str) -> String {
2014 if input.parse::<VersionReq>().is_ok() {
2017 format!(
2018 "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2019 )
2020 } else {
2021 "".to_owned()
2022 }
2023 }
2024}
2025
2026#[cfg(feature = "self-update")]
2027pub use self_update_errors::*;
2028
2029#[cfg(test)]
2030mod tests {
2031 use super::*;
2032
2033 #[test]
2034 fn display_error_chain() {
2035 let err1 = StringError::new("err1", None);
2036
2037 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2038
2039 let err2 = StringError::new("err2", Some(err1));
2040 let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2041
2042 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2043 err3
2044 err3 line 2
2045 caused by:
2046 - err2
2047 - err1
2048 ");
2049 }
2050
2051 #[test]
2052 fn display_error_list() {
2053 let err1 = StringError::new("err1", None);
2054
2055 let error_list =
2056 ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2057 .expect(">= 1 error");
2058 insta::assert_snapshot!(format!("{}", error_list), @"err1");
2059 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2060
2061 let err2 = StringError::new("err2", Some(err1));
2062 let err3 = StringError::new("err3", Some(err2));
2063
2064 let error_list =
2065 ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2066 .expect(">= 1 error");
2067 insta::assert_snapshot!(format!("{}", error_list), @"err3");
2068 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2069 err3
2070 caused by:
2071 - err2
2072 - err1
2073 ");
2074
2075 let err4 = StringError::new("err4", None);
2076 let err5 = StringError::new("err5", Some(err4));
2077 let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2078
2079 let error_list = ErrorList::<StringError>::new(
2080 "waiting for the heat death of the universe",
2081 vec![err3, err6],
2082 )
2083 .expect(">= 1 error");
2084
2085 insta::assert_snapshot!(format!("{}", error_list), @r"
2086 2 errors occurred waiting for the heat death of the universe:
2087 * err3
2088 caused by:
2089 - err2
2090 - err1
2091 * err6
2092 err6 line 2
2093 caused by:
2094 - err5
2095 - err4
2096 ");
2097 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2098 2 errors occurred waiting for the heat death of the universe:
2099 * err3
2100 caused by:
2101 - err2
2102 - err1
2103 * err6
2104 err6 line 2
2105 caused by:
2106 - err5
2107 - err4
2108 ");
2109 }
2110
2111 #[derive(Clone, Debug, Error)]
2112 struct StringError {
2113 message: String,
2114 #[source]
2115 source: Option<Box<StringError>>,
2116 }
2117
2118 impl StringError {
2119 fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2120 Self {
2121 message: message.into(),
2122 source: source.map(Box::new),
2123 }
2124 }
2125 }
2126
2127 impl fmt::Display for StringError {
2128 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2129 write!(f, "{}", self.message)
2130 }
2131 }
2132}