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("unrecognized value for max-fail: {reason}")]
688pub struct MaxFailParseError {
689 pub reason: String,
691}
692
693impl MaxFailParseError {
694 pub(crate) fn new(reason: impl Into<String>) -> Self {
695 Self {
696 reason: reason.into(),
697 }
698 }
699}
700
701#[derive(Clone, Debug, Error)]
703#[error(
704 "unrecognized value for stress-count: {input}\n\
705 (hint: expected either a positive integer or \"infinite\")"
706)]
707pub struct StressCountParseError {
708 pub input: String,
710}
711
712impl StressCountParseError {
713 pub(crate) fn new(input: impl Into<String>) -> Self {
714 Self {
715 input: input.into(),
716 }
717 }
718}
719
720#[derive(Clone, Debug, Error)]
722#[error(
723 "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
724)]
725pub struct TestThreadsParseError {
726 pub input: String,
728}
729
730impl TestThreadsParseError {
731 pub(crate) fn new(input: impl Into<String>) -> Self {
732 Self {
733 input: input.into(),
734 }
735 }
736}
737
738#[derive(Clone, Debug, Error)]
741pub struct PartitionerBuilderParseError {
742 expected_format: Option<&'static str>,
743 message: Cow<'static, str>,
744}
745
746impl PartitionerBuilderParseError {
747 pub(crate) fn new(
748 expected_format: Option<&'static str>,
749 message: impl Into<Cow<'static, str>>,
750 ) -> Self {
751 Self {
752 expected_format,
753 message: message.into(),
754 }
755 }
756}
757
758impl fmt::Display for PartitionerBuilderParseError {
759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
760 match self.expected_format {
761 Some(format) => {
762 write!(
763 f,
764 "partition must be in the format \"{}\":\n{}",
765 format, self.message
766 )
767 }
768 None => write!(f, "{}", self.message),
769 }
770 }
771}
772
773#[derive(Clone, Debug, Error)]
776pub enum TestFilterBuilderError {
777 #[error("error constructing test filters")]
779 Construct {
780 #[from]
782 error: aho_corasick::BuildError,
783 },
784}
785
786#[derive(Debug, Error)]
788pub enum PathMapperConstructError {
789 #[error("{kind} `{input}` failed to canonicalize")]
791 Canonicalization {
792 kind: PathMapperConstructKind,
794
795 input: Utf8PathBuf,
797
798 #[source]
800 err: std::io::Error,
801 },
802 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
804 NonUtf8Path {
805 kind: PathMapperConstructKind,
807
808 input: Utf8PathBuf,
810
811 #[source]
813 err: FromPathBufError,
814 },
815 #[error("{kind} `{canonicalized_path}` is not a directory")]
817 NotADirectory {
818 kind: PathMapperConstructKind,
820
821 input: Utf8PathBuf,
823
824 canonicalized_path: Utf8PathBuf,
826 },
827}
828
829impl PathMapperConstructError {
830 pub fn kind(&self) -> PathMapperConstructKind {
832 match self {
833 Self::Canonicalization { kind, .. }
834 | Self::NonUtf8Path { kind, .. }
835 | Self::NotADirectory { kind, .. } => *kind,
836 }
837 }
838
839 pub fn input(&self) -> &Utf8Path {
841 match self {
842 Self::Canonicalization { input, .. }
843 | Self::NonUtf8Path { input, .. }
844 | Self::NotADirectory { input, .. } => input,
845 }
846 }
847}
848
849#[derive(Copy, Clone, Debug, PartialEq, Eq)]
854pub enum PathMapperConstructKind {
855 WorkspaceRoot,
857
858 TargetDir,
860}
861
862impl fmt::Display for PathMapperConstructKind {
863 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
864 match self {
865 Self::WorkspaceRoot => write!(f, "remapped workspace root"),
866 Self::TargetDir => write!(f, "remapped target directory"),
867 }
868 }
869}
870
871#[derive(Debug, Error)]
873pub enum RustBuildMetaParseError {
874 #[error("error deserializing platform from build metadata")]
876 PlatformDeserializeError(#[from] target_spec::Error),
877
878 #[error("the host platform could not be determined")]
880 DetectBuildTargetError(#[source] target_spec::Error),
881
882 #[error("unsupported features in the build metadata: {message}")]
884 Unsupported {
885 message: String,
887 },
888}
889
890#[derive(Clone, Debug, thiserror::Error)]
893#[error("invalid format version: {input}")]
894pub struct FormatVersionError {
895 pub input: String,
897 #[source]
899 pub error: FormatVersionErrorInner,
900}
901
902#[derive(Clone, Debug, thiserror::Error)]
904pub enum FormatVersionErrorInner {
905 #[error("expected format version in form of `{expected}`")]
907 InvalidFormat {
908 expected: &'static str,
910 },
911 #[error("version component `{which}` could not be parsed as an integer")]
913 InvalidInteger {
914 which: &'static str,
916 #[source]
918 err: std::num::ParseIntError,
919 },
920 #[error("version component `{which}` value {value} is out of range {range:?}")]
922 InvalidValue {
923 which: &'static str,
925 value: u8,
927 range: std::ops::Range<u8>,
929 },
930}
931
932#[derive(Debug, Error)]
935#[non_exhaustive]
936pub enum FromMessagesError {
937 #[error("error reading Cargo JSON messages")]
939 ReadMessages(#[source] std::io::Error),
940
941 #[error("error querying package graph")]
943 PackageGraph(#[source] guppy::Error),
944
945 #[error("missing kind for target {binary_name} in package {package_name}")]
947 MissingTargetKind {
948 package_name: String,
950 binary_name: String,
952 },
953}
954
955#[derive(Debug, Error)]
957#[non_exhaustive]
958pub enum CreateTestListError {
959 #[error(
961 "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
962 (hint: ensure project source is available at this location)"
963 )]
964 CwdIsNotDir {
965 binary_id: RustBinaryId,
967
968 cwd: Utf8PathBuf,
970 },
971
972 #[error(
974 "for `{binary_id}`, running command `{}` failed to execute",
975 shell_words::join(command)
976 )]
977 CommandExecFail {
978 binary_id: RustBinaryId,
980
981 command: Vec<String>,
983
984 #[source]
986 error: std::io::Error,
987 },
988
989 #[error(
991 "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
992 shell_words::join(command),
993 display_exited_with(*exit_status),
994 String::from_utf8_lossy(stdout),
995 String::from_utf8_lossy(stderr),
996 )]
997 CommandFail {
998 binary_id: RustBinaryId,
1000
1001 command: Vec<String>,
1003
1004 exit_status: ExitStatus,
1006
1007 stdout: Vec<u8>,
1009
1010 stderr: Vec<u8>,
1012 },
1013
1014 #[error(
1016 "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1017 shell_words::join(command),
1018 String::from_utf8_lossy(stdout),
1019 String::from_utf8_lossy(stderr)
1020 )]
1021 CommandNonUtf8 {
1022 binary_id: RustBinaryId,
1024
1025 command: Vec<String>,
1027
1028 stdout: Vec<u8>,
1030
1031 stderr: Vec<u8>,
1033 },
1034
1035 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1037 ParseLine {
1038 binary_id: RustBinaryId,
1040
1041 message: Cow<'static, str>,
1043
1044 full_output: String,
1046 },
1047
1048 #[error(
1050 "error joining dynamic library paths for {}: [{}]",
1051 dylib_path_envvar(),
1052 itertools::join(.new_paths, ", ")
1053 )]
1054 DylibJoinPaths {
1055 new_paths: Vec<Utf8PathBuf>,
1057
1058 #[source]
1060 error: JoinPathsError,
1061 },
1062
1063 #[error("error creating Tokio runtime")]
1065 TokioRuntimeCreate(#[source] std::io::Error),
1066}
1067
1068impl CreateTestListError {
1069 pub(crate) fn parse_line(
1070 binary_id: RustBinaryId,
1071 message: impl Into<Cow<'static, str>>,
1072 full_output: impl Into<String>,
1073 ) -> Self {
1074 Self::ParseLine {
1075 binary_id,
1076 message: message.into(),
1077 full_output: full_output.into(),
1078 }
1079 }
1080
1081 pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1082 Self::DylibJoinPaths { new_paths, error }
1083 }
1084}
1085
1086#[derive(Debug, Error)]
1088#[non_exhaustive]
1089pub enum WriteTestListError {
1090 #[error("error writing to output")]
1092 Io(#[source] std::io::Error),
1093
1094 #[error("error serializing to JSON")]
1096 Json(#[source] serde_json::Error),
1097}
1098
1099#[derive(Debug, Error)]
1103pub enum ConfigureHandleInheritanceError {
1104 #[cfg(windows)]
1106 #[error("error configuring handle inheritance")]
1107 WindowsError(#[from] std::io::Error),
1108}
1109
1110#[derive(Debug, Error)]
1112#[non_exhaustive]
1113pub enum TestRunnerBuildError {
1114 #[error("error creating Tokio runtime")]
1116 TokioRuntimeCreate(#[source] std::io::Error),
1117
1118 #[error("error setting up signals")]
1120 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1121}
1122
1123#[derive(Debug, Error)]
1125pub struct TestRunnerExecuteErrors<E> {
1126 pub report_error: Option<E>,
1128
1129 pub join_errors: Vec<tokio::task::JoinError>,
1132}
1133
1134impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 if let Some(report_error) = &self.report_error {
1137 write!(f, "error reporting results: {report_error}")?;
1138 }
1139
1140 if !self.join_errors.is_empty() {
1141 if self.report_error.is_some() {
1142 write!(f, "; ")?;
1143 }
1144
1145 write!(f, "errors joining tasks: ")?;
1146
1147 for (i, join_error) in self.join_errors.iter().enumerate() {
1148 if i > 0 {
1149 write!(f, ", ")?;
1150 }
1151
1152 write!(f, "{join_error}")?;
1153 }
1154 }
1155
1156 Ok(())
1157 }
1158}
1159
1160#[derive(Debug, Error)]
1164#[error(
1165 "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1166 supported_extensions()
1167)]
1168pub struct UnknownArchiveFormat {
1169 pub file_name: String,
1171}
1172
1173fn supported_extensions() -> String {
1174 ArchiveFormat::SUPPORTED_FORMATS
1175 .iter()
1176 .map(|(extension, _)| *extension)
1177 .join(", ")
1178}
1179
1180#[derive(Debug, Error)]
1182#[non_exhaustive]
1183pub enum ArchiveCreateError {
1184 #[error("error creating binary list")]
1186 CreateBinaryList(#[source] WriteTestListError),
1187
1188 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1190 MissingExtraPath {
1191 path: Utf8PathBuf,
1193
1194 redactor: Redactor,
1199 },
1200
1201 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1203 InputFileRead {
1204 step: ArchiveStep,
1206
1207 path: Utf8PathBuf,
1209
1210 is_dir: Option<bool>,
1212
1213 #[source]
1215 error: std::io::Error,
1216 },
1217
1218 #[error("error reading directory entry from `{path}")]
1220 DirEntryRead {
1221 path: Utf8PathBuf,
1223
1224 #[source]
1226 error: std::io::Error,
1227 },
1228
1229 #[error("error writing to archive")]
1231 OutputArchiveIo(#[source] std::io::Error),
1232
1233 #[error("error reporting archive status")]
1235 ReporterIo(#[source] std::io::Error),
1236}
1237
1238fn kind_str(is_dir: Option<bool>) -> &'static str {
1239 match is_dir {
1240 Some(true) => "directory",
1241 Some(false) => "file",
1242 None => "path",
1243 }
1244}
1245
1246#[derive(Debug, Error)]
1248pub enum MetadataMaterializeError {
1249 #[error("I/O error reading metadata file `{path}`")]
1251 Read {
1252 path: Utf8PathBuf,
1254
1255 #[source]
1257 error: std::io::Error,
1258 },
1259
1260 #[error("error deserializing metadata file `{path}`")]
1262 Deserialize {
1263 path: Utf8PathBuf,
1265
1266 #[source]
1268 error: serde_json::Error,
1269 },
1270
1271 #[error("error parsing Rust build metadata from `{path}`")]
1273 RustBuildMeta {
1274 path: Utf8PathBuf,
1276
1277 #[source]
1279 error: RustBuildMetaParseError,
1280 },
1281
1282 #[error("error building package graph from `{path}`")]
1284 PackageGraphConstruct {
1285 path: Utf8PathBuf,
1287
1288 #[source]
1290 error: guppy::Error,
1291 },
1292}
1293
1294#[derive(Debug, Error)]
1298#[non_exhaustive]
1299pub enum ArchiveReadError {
1300 #[error("I/O error reading archive")]
1302 Io(#[source] std::io::Error),
1303
1304 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1306 NonUtf8Path(Vec<u8>),
1307
1308 #[error("path in archive `{0}` doesn't start with `target/`")]
1310 NoTargetPrefix(Utf8PathBuf),
1311
1312 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1314 InvalidComponent {
1315 path: Utf8PathBuf,
1317
1318 component: String,
1320 },
1321
1322 #[error("corrupted archive: checksum read error for path `{path}`")]
1324 ChecksumRead {
1325 path: Utf8PathBuf,
1327
1328 #[source]
1330 error: std::io::Error,
1331 },
1332
1333 #[error("corrupted archive: invalid checksum for path `{path}`")]
1335 InvalidChecksum {
1336 path: Utf8PathBuf,
1338
1339 expected: u32,
1341
1342 actual: u32,
1344 },
1345
1346 #[error("metadata file `{0}` not found in archive")]
1348 MetadataFileNotFound(&'static Utf8Path),
1349
1350 #[error("error deserializing metadata file `{path}` in archive")]
1352 MetadataDeserializeError {
1353 path: &'static Utf8Path,
1355
1356 #[source]
1358 error: serde_json::Error,
1359 },
1360
1361 #[error("error building package graph from `{path}` in archive")]
1363 PackageGraphConstructError {
1364 path: &'static Utf8Path,
1366
1367 #[source]
1369 error: guppy::Error,
1370 },
1371}
1372
1373#[derive(Debug, Error)]
1377#[non_exhaustive]
1378pub enum ArchiveExtractError {
1379 #[error("error creating temporary directory")]
1381 TempDirCreate(#[source] std::io::Error),
1382
1383 #[error("error canonicalizing destination directory `{dir}`")]
1385 DestDirCanonicalization {
1386 dir: Utf8PathBuf,
1388
1389 #[source]
1391 error: std::io::Error,
1392 },
1393
1394 #[error("destination `{0}` already exists")]
1396 DestinationExists(Utf8PathBuf),
1397
1398 #[error("error reading archive")]
1400 Read(#[source] ArchiveReadError),
1401
1402 #[error("error deserializing Rust build metadata")]
1404 RustBuildMeta(#[from] RustBuildMetaParseError),
1405
1406 #[error("error writing file `{path}` to disk")]
1408 WriteFile {
1409 path: Utf8PathBuf,
1411
1412 #[source]
1414 error: std::io::Error,
1415 },
1416
1417 #[error("error reporting extract status")]
1419 ReporterIo(std::io::Error),
1420}
1421
1422#[derive(Debug, Error)]
1424#[non_exhaustive]
1425pub enum WriteEventError {
1426 #[error("error writing to output")]
1428 Io(#[source] std::io::Error),
1429
1430 #[error("error operating on path {file}")]
1432 Fs {
1433 file: Utf8PathBuf,
1435
1436 #[source]
1438 error: std::io::Error,
1439 },
1440
1441 #[error("error writing JUnit output to {file}")]
1443 Junit {
1444 file: Utf8PathBuf,
1446
1447 #[source]
1449 error: quick_junit::SerializeError,
1450 },
1451}
1452
1453#[derive(Debug, Error)]
1456#[non_exhaustive]
1457pub enum CargoConfigError {
1458 #[error("failed to retrieve current directory")]
1460 GetCurrentDir(#[source] std::io::Error),
1461
1462 #[error("current directory is invalid UTF-8")]
1464 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1465
1466 #[error("failed to parse --config argument `{config_str}` as TOML")]
1468 CliConfigParseError {
1469 config_str: String,
1471
1472 #[source]
1474 error: toml_edit::TomlError,
1475 },
1476
1477 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1479 CliConfigDeError {
1480 config_str: String,
1482
1483 #[source]
1485 error: toml_edit::de::Error,
1486 },
1487
1488 #[error(
1490 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1491 )]
1492 InvalidCliConfig {
1493 config_str: String,
1495
1496 #[source]
1498 reason: InvalidCargoCliConfigReason,
1499 },
1500
1501 #[error("non-UTF-8 path encountered")]
1503 NonUtf8Path(#[source] FromPathBufError),
1504
1505 #[error("failed to retrieve the Cargo home directory")]
1507 GetCargoHome(#[source] std::io::Error),
1508
1509 #[error("failed to canonicalize path `{path}")]
1511 FailedPathCanonicalization {
1512 path: Utf8PathBuf,
1514
1515 #[source]
1517 error: std::io::Error,
1518 },
1519
1520 #[error("failed to read config at `{path}`")]
1522 ConfigReadError {
1523 path: Utf8PathBuf,
1525
1526 #[source]
1528 error: std::io::Error,
1529 },
1530
1531 #[error(transparent)]
1533 ConfigParseError(#[from] Box<CargoConfigParseError>),
1534}
1535
1536#[derive(Debug, Error)]
1540#[error("failed to parse config at `{path}`")]
1541pub struct CargoConfigParseError {
1542 pub path: Utf8PathBuf,
1544
1545 #[source]
1547 pub error: toml::de::Error,
1548}
1549
1550#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1554#[non_exhaustive]
1555pub enum InvalidCargoCliConfigReason {
1556 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1558 NotDottedKv,
1559
1560 #[error("includes non-whitespace decoration")]
1562 IncludesNonWhitespaceDecoration,
1563
1564 #[error("sets a value to an inline table, which is not accepted")]
1566 SetsValueToInlineTable,
1567
1568 #[error("sets a value to an array of tables, which is not accepted")]
1570 SetsValueToArrayOfTables,
1571
1572 #[error("doesn't provide a value")]
1574 DoesntProvideValue,
1575}
1576
1577#[derive(Debug, Error)]
1579pub enum HostPlatformDetectError {
1580 #[error(
1583 "error spawning `rustc -vV`, and detecting the build \
1584 target failed as well\n\
1585 - rustc spawn error: {}\n\
1586 - build target error: {}\n",
1587 DisplayErrorChain::new_with_initial_indent(" ", error),
1588 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1589 )]
1590 RustcVvSpawnError {
1591 error: std::io::Error,
1593
1594 build_target_error: Box<target_spec::Error>,
1596 },
1597
1598 #[error(
1601 "`rustc -vV` failed with {}, and detecting the \
1602 build target failed as well\n\
1603 - `rustc -vV` stdout:\n{}\n\
1604 - `rustc -vV` stderr:\n{}\n\
1605 - build target error:\n{}\n",
1606 status,
1607 Indented { item: String::from_utf8_lossy(stdout), indent: " " },
1608 Indented { item: String::from_utf8_lossy(stderr), indent: " " },
1609 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1610 )]
1611 RustcVvFailed {
1612 status: ExitStatus,
1614
1615 stdout: Vec<u8>,
1617
1618 stderr: Vec<u8>,
1620
1621 build_target_error: Box<target_spec::Error>,
1623 },
1624
1625 #[error(
1628 "parsing `rustc -vV` output failed, and detecting the build target \
1629 failed as well\n\
1630 - host platform error:\n{}\n\
1631 - build target error:\n{}\n",
1632 DisplayErrorChain::new_with_initial_indent(" ", host_platform_error),
1633 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1634 )]
1635 HostPlatformParseError {
1636 host_platform_error: Box<target_spec::Error>,
1638
1639 build_target_error: Box<target_spec::Error>,
1641 },
1642
1643 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1646 BuildTargetError {
1647 #[source]
1649 build_target_error: Box<target_spec::Error>,
1650 },
1651}
1652
1653#[derive(Debug, Error)]
1655pub enum TargetTripleError {
1656 #[error(
1658 "environment variable '{}' contained non-UTF-8 data",
1659 TargetTriple::CARGO_BUILD_TARGET_ENV
1660 )]
1661 InvalidEnvironmentVar,
1662
1663 #[error("error deserializing target triple from {source}")]
1665 TargetSpecError {
1666 source: TargetTripleSource,
1668
1669 #[source]
1671 error: target_spec::Error,
1672 },
1673
1674 #[error("target path `{path}` is not a valid file")]
1676 TargetPathReadError {
1677 source: TargetTripleSource,
1679
1680 path: Utf8PathBuf,
1682
1683 #[source]
1685 error: std::io::Error,
1686 },
1687
1688 #[error(
1690 "for custom platform obtained from {source}, \
1691 failed to create temporary directory for custom platform"
1692 )]
1693 CustomPlatformTempDirError {
1694 source: TargetTripleSource,
1696
1697 #[source]
1699 error: std::io::Error,
1700 },
1701
1702 #[error(
1704 "for custom platform obtained from {source}, \
1705 failed to write JSON to temporary path `{path}`"
1706 )]
1707 CustomPlatformWriteError {
1708 source: TargetTripleSource,
1710
1711 path: Utf8PathBuf,
1713
1714 #[source]
1716 error: std::io::Error,
1717 },
1718
1719 #[error(
1721 "for custom platform obtained from {source}, \
1722 failed to close temporary directory `{dir_path}`"
1723 )]
1724 CustomPlatformCloseError {
1725 source: TargetTripleSource,
1727
1728 dir_path: Utf8PathBuf,
1730
1731 #[source]
1733 error: std::io::Error,
1734 },
1735}
1736
1737impl TargetTripleError {
1738 pub fn source_report(&self) -> Option<miette::Report> {
1743 match self {
1744 Self::TargetSpecError { error, .. } => {
1745 Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1746 }
1747 TargetTripleError::InvalidEnvironmentVar
1749 | TargetTripleError::TargetPathReadError { .. }
1750 | TargetTripleError::CustomPlatformTempDirError { .. }
1751 | TargetTripleError::CustomPlatformWriteError { .. }
1752 | TargetTripleError::CustomPlatformCloseError { .. } => None,
1753 }
1754 }
1755}
1756
1757#[derive(Debug, Error)]
1759pub enum TargetRunnerError {
1760 #[error("environment variable '{0}' contained non-UTF-8 data")]
1762 InvalidEnvironmentVar(String),
1763
1764 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1767 BinaryNotSpecified {
1768 key: PlatformRunnerSource,
1770
1771 value: String,
1773 },
1774}
1775
1776#[derive(Debug, Error)]
1778#[error("error setting up signal handler")]
1779pub struct SignalHandlerSetupError(#[from] std::io::Error);
1780
1781#[derive(Debug, Error)]
1783pub enum ShowTestGroupsError {
1784 #[error(
1786 "unknown test groups specified: {}\n(known groups: {})",
1787 unknown_groups.iter().join(", "),
1788 known_groups.iter().join(", "),
1789 )]
1790 UnknownGroups {
1791 unknown_groups: BTreeSet<TestGroup>,
1793
1794 known_groups: BTreeSet<TestGroup>,
1796 },
1797}
1798
1799#[cfg(feature = "self-update")]
1800mod self_update_errors {
1801 use super::*;
1802 use mukti_metadata::ReleaseStatus;
1803 use semver::{Version, VersionReq};
1804
1805 #[cfg(feature = "self-update")]
1809 #[derive(Debug, Error)]
1810 #[non_exhaustive]
1811 pub enum UpdateError {
1812 #[error("failed to read release metadata from `{path}`")]
1814 ReadLocalMetadata {
1815 path: Utf8PathBuf,
1817
1818 #[source]
1820 error: std::io::Error,
1821 },
1822
1823 #[error("self-update failed")]
1825 SelfUpdate(#[source] self_update::errors::Error),
1826
1827 #[error("deserializing release metadata failed")]
1829 ReleaseMetadataDe(#[source] serde_json::Error),
1830
1831 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1833 VersionNotFound {
1834 version: Version,
1836
1837 known: Vec<(Version, ReleaseStatus)>,
1839 },
1840
1841 #[error("no version found matching requirement `{req}`")]
1843 NoMatchForVersionReq {
1844 req: VersionReq,
1846 },
1847
1848 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1850 MuktiProjectNotFound {
1851 not_found: String,
1853
1854 known: Vec<String>,
1856 },
1857
1858 #[error(
1860 "for version {version}, no release information found for target `{triple}` \
1861 (known targets: {})",
1862 known_triples.iter().join(", ")
1863 )]
1864 NoTargetData {
1865 version: Version,
1867
1868 triple: String,
1870
1871 known_triples: BTreeSet<String>,
1873 },
1874
1875 #[error("the current executable's path could not be determined")]
1877 CurrentExe(#[source] std::io::Error),
1878
1879 #[error("temporary directory could not be created at `{location}`")]
1881 TempDirCreate {
1882 location: Utf8PathBuf,
1884
1885 #[source]
1887 error: std::io::Error,
1888 },
1889
1890 #[error("temporary archive could not be created at `{archive_path}`")]
1892 TempArchiveCreate {
1893 archive_path: Utf8PathBuf,
1895
1896 #[source]
1898 error: std::io::Error,
1899 },
1900
1901 #[error("error writing to temporary archive at `{archive_path}`")]
1903 TempArchiveWrite {
1904 archive_path: Utf8PathBuf,
1906
1907 #[source]
1909 error: std::io::Error,
1910 },
1911
1912 #[error("error reading from temporary archive at `{archive_path}`")]
1914 TempArchiveRead {
1915 archive_path: Utf8PathBuf,
1917
1918 #[source]
1920 error: std::io::Error,
1921 },
1922
1923 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1925 ChecksumMismatch {
1926 expected: String,
1928
1929 actual: String,
1931 },
1932
1933 #[error("error renaming `{source}` to `{dest}`")]
1935 FsRename {
1936 source: Utf8PathBuf,
1938
1939 dest: Utf8PathBuf,
1941
1942 #[source]
1944 error: std::io::Error,
1945 },
1946
1947 #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
1949 SelfSetup(#[source] std::io::Error),
1950 }
1951
1952 fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
1953 use std::fmt::Write;
1954
1955 const DISPLAY_COUNT: usize = 4;
1957
1958 let display_versions: Vec<_> = versions
1959 .iter()
1960 .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
1961 .map(|(v, _)| v.to_string())
1962 .take(DISPLAY_COUNT)
1963 .collect();
1964 let mut display_str = display_versions.join(", ");
1965 if versions.len() > display_versions.len() {
1966 write!(
1967 display_str,
1968 " and {} others",
1969 versions.len() - display_versions.len()
1970 )
1971 .unwrap();
1972 }
1973
1974 display_str
1975 }
1976
1977 #[cfg(feature = "self-update")]
1978 #[derive(Debug, Error)]
1980 pub enum UpdateVersionParseError {
1981 #[error("version string is empty")]
1983 EmptyString,
1984
1985 #[error(
1987 "`{input}` is not a valid semver requirement\n\
1988 (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
1989 )]
1990 InvalidVersionReq {
1991 input: String,
1993
1994 #[source]
1996 error: semver::Error,
1997 },
1998
1999 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2001 InvalidVersion {
2002 input: String,
2004
2005 #[source]
2007 error: semver::Error,
2008 },
2009 }
2010
2011 fn extra_semver_output(input: &str) -> String {
2012 if input.parse::<VersionReq>().is_ok() {
2015 format!(
2016 "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2017 )
2018 } else {
2019 "".to_owned()
2020 }
2021 }
2022}
2023
2024#[cfg(feature = "self-update")]
2025pub use self_update_errors::*;
2026
2027#[cfg(test)]
2028mod tests {
2029 use super::*;
2030
2031 #[test]
2032 fn display_error_chain() {
2033 let err1 = StringError::new("err1", None);
2034
2035 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2036
2037 let err2 = StringError::new("err2", Some(err1));
2038 let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2039
2040 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2041 err3
2042 err3 line 2
2043 caused by:
2044 - err2
2045 - err1
2046 ");
2047 }
2048
2049 #[test]
2050 fn display_error_list() {
2051 let err1 = StringError::new("err1", None);
2052
2053 let error_list =
2054 ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2055 .expect(">= 1 error");
2056 insta::assert_snapshot!(format!("{}", error_list), @"err1");
2057 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2058
2059 let err2 = StringError::new("err2", Some(err1));
2060 let err3 = StringError::new("err3", Some(err2));
2061
2062 let error_list =
2063 ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2064 .expect(">= 1 error");
2065 insta::assert_snapshot!(format!("{}", error_list), @"err3");
2066 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2067 err3
2068 caused by:
2069 - err2
2070 - err1
2071 ");
2072
2073 let err4 = StringError::new("err4", None);
2074 let err5 = StringError::new("err5", Some(err4));
2075 let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2076
2077 let error_list = ErrorList::<StringError>::new(
2078 "waiting for the heat death of the universe",
2079 vec![err3, err6],
2080 )
2081 .expect(">= 1 error");
2082
2083 insta::assert_snapshot!(format!("{}", error_list), @r"
2084 2 errors occurred waiting for the heat death of the universe:
2085 * err3
2086 caused by:
2087 - err2
2088 - err1
2089 * err6
2090 err6 line 2
2091 caused by:
2092 - err5
2093 - err4
2094 ");
2095 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2096 2 errors occurred waiting for the heat death of the universe:
2097 * err3
2098 caused by:
2099 - err2
2100 - err1
2101 * err6
2102 err6 line 2
2103 caused by:
2104 - err5
2105 - err4
2106 ");
2107 }
2108
2109 #[derive(Clone, Debug, Error)]
2110 struct StringError {
2111 message: String,
2112 #[source]
2113 source: Option<Box<StringError>>,
2114 }
2115
2116 impl StringError {
2117 fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2118 Self {
2119 message: message.into(),
2120 source: source.map(Box::new),
2121 }
2122 }
2123 }
2124
2125 impl fmt::Display for StringError {
2126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2127 write!(f, "{}", self.message)
2128 }
2129 }
2130}