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 test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
707)]
708pub struct TestThreadsParseError {
709 pub input: String,
711}
712
713impl TestThreadsParseError {
714 pub(crate) fn new(input: impl Into<String>) -> Self {
715 Self {
716 input: input.into(),
717 }
718 }
719}
720
721#[derive(Clone, Debug, Error)]
724pub struct PartitionerBuilderParseError {
725 expected_format: Option<&'static str>,
726 message: Cow<'static, str>,
727}
728
729impl PartitionerBuilderParseError {
730 pub(crate) fn new(
731 expected_format: Option<&'static str>,
732 message: impl Into<Cow<'static, str>>,
733 ) -> Self {
734 Self {
735 expected_format,
736 message: message.into(),
737 }
738 }
739}
740
741impl fmt::Display for PartitionerBuilderParseError {
742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
743 match self.expected_format {
744 Some(format) => {
745 write!(
746 f,
747 "partition must be in the format \"{}\":\n{}",
748 format, self.message
749 )
750 }
751 None => write!(f, "{}", self.message),
752 }
753 }
754}
755
756#[derive(Clone, Debug, Error)]
759pub enum TestFilterBuilderError {
760 #[error("error constructing test filters")]
762 Construct {
763 #[from]
765 error: aho_corasick::BuildError,
766 },
767}
768
769#[derive(Debug, Error)]
771pub enum PathMapperConstructError {
772 #[error("{kind} `{input}` failed to canonicalize")]
774 Canonicalization {
775 kind: PathMapperConstructKind,
777
778 input: Utf8PathBuf,
780
781 #[source]
783 err: std::io::Error,
784 },
785 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
787 NonUtf8Path {
788 kind: PathMapperConstructKind,
790
791 input: Utf8PathBuf,
793
794 #[source]
796 err: FromPathBufError,
797 },
798 #[error("{kind} `{canonicalized_path}` is not a directory")]
800 NotADirectory {
801 kind: PathMapperConstructKind,
803
804 input: Utf8PathBuf,
806
807 canonicalized_path: Utf8PathBuf,
809 },
810}
811
812impl PathMapperConstructError {
813 pub fn kind(&self) -> PathMapperConstructKind {
815 match self {
816 Self::Canonicalization { kind, .. }
817 | Self::NonUtf8Path { kind, .. }
818 | Self::NotADirectory { kind, .. } => *kind,
819 }
820 }
821
822 pub fn input(&self) -> &Utf8Path {
824 match self {
825 Self::Canonicalization { input, .. }
826 | Self::NonUtf8Path { input, .. }
827 | Self::NotADirectory { input, .. } => input,
828 }
829 }
830}
831
832#[derive(Copy, Clone, Debug, PartialEq, Eq)]
837pub enum PathMapperConstructKind {
838 WorkspaceRoot,
840
841 TargetDir,
843}
844
845impl fmt::Display for PathMapperConstructKind {
846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
847 match self {
848 Self::WorkspaceRoot => write!(f, "remapped workspace root"),
849 Self::TargetDir => write!(f, "remapped target directory"),
850 }
851 }
852}
853
854#[derive(Debug, Error)]
856pub enum RustBuildMetaParseError {
857 #[error("error deserializing platform from build metadata")]
859 PlatformDeserializeError(#[from] target_spec::Error),
860
861 #[error("the host platform could not be determined")]
863 DetectBuildTargetError(#[source] target_spec::Error),
864
865 #[error("unsupported features in the build metadata: {message}")]
867 Unsupported {
868 message: String,
870 },
871}
872
873#[derive(Clone, Debug, thiserror::Error)]
876#[error("invalid format version: {input}")]
877pub struct FormatVersionError {
878 pub input: String,
880 #[source]
882 pub error: FormatVersionErrorInner,
883}
884
885#[derive(Clone, Debug, thiserror::Error)]
887pub enum FormatVersionErrorInner {
888 #[error("expected format version in form of `{expected}`")]
890 InvalidFormat {
891 expected: &'static str,
893 },
894 #[error("version component `{which}` could not be parsed as an integer")]
896 InvalidInteger {
897 which: &'static str,
899 #[source]
901 err: std::num::ParseIntError,
902 },
903 #[error("version component `{which}` value {value} is out of range {range:?}")]
905 InvalidValue {
906 which: &'static str,
908 value: u8,
910 range: std::ops::Range<u8>,
912 },
913}
914
915#[derive(Debug, Error)]
918#[non_exhaustive]
919pub enum FromMessagesError {
920 #[error("error reading Cargo JSON messages")]
922 ReadMessages(#[source] std::io::Error),
923
924 #[error("error querying package graph")]
926 PackageGraph(#[source] guppy::Error),
927
928 #[error("missing kind for target {binary_name} in package {package_name}")]
930 MissingTargetKind {
931 package_name: String,
933 binary_name: String,
935 },
936}
937
938#[derive(Debug, Error)]
940#[non_exhaustive]
941pub enum CreateTestListError {
942 #[error(
944 "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
945 (hint: ensure project source is available at this location)"
946 )]
947 CwdIsNotDir {
948 binary_id: RustBinaryId,
950
951 cwd: Utf8PathBuf,
953 },
954
955 #[error(
957 "for `{binary_id}`, running command `{}` failed to execute",
958 shell_words::join(command)
959 )]
960 CommandExecFail {
961 binary_id: RustBinaryId,
963
964 command: Vec<String>,
966
967 #[source]
969 error: std::io::Error,
970 },
971
972 #[error(
974 "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
975 shell_words::join(command),
976 display_exited_with(*exit_status),
977 String::from_utf8_lossy(stdout),
978 String::from_utf8_lossy(stderr),
979 )]
980 CommandFail {
981 binary_id: RustBinaryId,
983
984 command: Vec<String>,
986
987 exit_status: ExitStatus,
989
990 stdout: Vec<u8>,
992
993 stderr: Vec<u8>,
995 },
996
997 #[error(
999 "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1000 shell_words::join(command),
1001 String::from_utf8_lossy(stdout),
1002 String::from_utf8_lossy(stderr)
1003 )]
1004 CommandNonUtf8 {
1005 binary_id: RustBinaryId,
1007
1008 command: Vec<String>,
1010
1011 stdout: Vec<u8>,
1013
1014 stderr: Vec<u8>,
1016 },
1017
1018 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1020 ParseLine {
1021 binary_id: RustBinaryId,
1023
1024 message: Cow<'static, str>,
1026
1027 full_output: String,
1029 },
1030
1031 #[error(
1033 "error joining dynamic library paths for {}: [{}]",
1034 dylib_path_envvar(),
1035 itertools::join(.new_paths, ", ")
1036 )]
1037 DylibJoinPaths {
1038 new_paths: Vec<Utf8PathBuf>,
1040
1041 #[source]
1043 error: JoinPathsError,
1044 },
1045
1046 #[error("error creating Tokio runtime")]
1048 TokioRuntimeCreate(#[source] std::io::Error),
1049}
1050
1051impl CreateTestListError {
1052 pub(crate) fn parse_line(
1053 binary_id: RustBinaryId,
1054 message: impl Into<Cow<'static, str>>,
1055 full_output: impl Into<String>,
1056 ) -> Self {
1057 Self::ParseLine {
1058 binary_id,
1059 message: message.into(),
1060 full_output: full_output.into(),
1061 }
1062 }
1063
1064 pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1065 Self::DylibJoinPaths { new_paths, error }
1066 }
1067}
1068
1069#[derive(Debug, Error)]
1071#[non_exhaustive]
1072pub enum WriteTestListError {
1073 #[error("error writing to output")]
1075 Io(#[source] std::io::Error),
1076
1077 #[error("error serializing to JSON")]
1079 Json(#[source] serde_json::Error),
1080}
1081
1082#[derive(Debug, Error)]
1086pub enum ConfigureHandleInheritanceError {
1087 #[cfg(windows)]
1089 #[error("error configuring handle inheritance")]
1090 WindowsError(#[from] std::io::Error),
1091}
1092
1093#[derive(Debug, Error)]
1095#[non_exhaustive]
1096pub enum TestRunnerBuildError {
1097 #[error("error creating Tokio runtime")]
1099 TokioRuntimeCreate(#[source] std::io::Error),
1100
1101 #[error("error setting up signals")]
1103 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1104}
1105
1106#[derive(Debug, Error)]
1108pub struct TestRunnerExecuteErrors<E> {
1109 pub report_error: Option<E>,
1111
1112 pub join_errors: Vec<tokio::task::JoinError>,
1115}
1116
1117impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119 if let Some(report_error) = &self.report_error {
1120 write!(f, "error reporting results: {report_error}")?;
1121 }
1122
1123 if !self.join_errors.is_empty() {
1124 if self.report_error.is_some() {
1125 write!(f, "; ")?;
1126 }
1127
1128 write!(f, "errors joining tasks: ")?;
1129
1130 for (i, join_error) in self.join_errors.iter().enumerate() {
1131 if i > 0 {
1132 write!(f, ", ")?;
1133 }
1134
1135 write!(f, "{join_error}")?;
1136 }
1137 }
1138
1139 Ok(())
1140 }
1141}
1142
1143#[derive(Debug, Error)]
1147#[error(
1148 "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1149 supported_extensions()
1150)]
1151pub struct UnknownArchiveFormat {
1152 pub file_name: String,
1154}
1155
1156fn supported_extensions() -> String {
1157 ArchiveFormat::SUPPORTED_FORMATS
1158 .iter()
1159 .map(|(extension, _)| *extension)
1160 .join(", ")
1161}
1162
1163#[derive(Debug, Error)]
1165#[non_exhaustive]
1166pub enum ArchiveCreateError {
1167 #[error("error creating binary list")]
1169 CreateBinaryList(#[source] WriteTestListError),
1170
1171 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1173 MissingExtraPath {
1174 path: Utf8PathBuf,
1176
1177 redactor: Redactor,
1182 },
1183
1184 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1186 InputFileRead {
1187 step: ArchiveStep,
1189
1190 path: Utf8PathBuf,
1192
1193 is_dir: Option<bool>,
1195
1196 #[source]
1198 error: std::io::Error,
1199 },
1200
1201 #[error("error reading directory entry from `{path}")]
1203 DirEntryRead {
1204 path: Utf8PathBuf,
1206
1207 #[source]
1209 error: std::io::Error,
1210 },
1211
1212 #[error("error writing to archive")]
1214 OutputArchiveIo(#[source] std::io::Error),
1215
1216 #[error("error reporting archive status")]
1218 ReporterIo(#[source] std::io::Error),
1219}
1220
1221fn kind_str(is_dir: Option<bool>) -> &'static str {
1222 match is_dir {
1223 Some(true) => "directory",
1224 Some(false) => "file",
1225 None => "path",
1226 }
1227}
1228
1229#[derive(Debug, Error)]
1231pub enum MetadataMaterializeError {
1232 #[error("I/O error reading metadata file `{path}`")]
1234 Read {
1235 path: Utf8PathBuf,
1237
1238 #[source]
1240 error: std::io::Error,
1241 },
1242
1243 #[error("error deserializing metadata file `{path}`")]
1245 Deserialize {
1246 path: Utf8PathBuf,
1248
1249 #[source]
1251 error: serde_json::Error,
1252 },
1253
1254 #[error("error parsing Rust build metadata from `{path}`")]
1256 RustBuildMeta {
1257 path: Utf8PathBuf,
1259
1260 #[source]
1262 error: RustBuildMetaParseError,
1263 },
1264
1265 #[error("error building package graph from `{path}`")]
1267 PackageGraphConstruct {
1268 path: Utf8PathBuf,
1270
1271 #[source]
1273 error: guppy::Error,
1274 },
1275}
1276
1277#[derive(Debug, Error)]
1281#[non_exhaustive]
1282pub enum ArchiveReadError {
1283 #[error("I/O error reading archive")]
1285 Io(#[source] std::io::Error),
1286
1287 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1289 NonUtf8Path(Vec<u8>),
1290
1291 #[error("path in archive `{0}` doesn't start with `target/`")]
1293 NoTargetPrefix(Utf8PathBuf),
1294
1295 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1297 InvalidComponent {
1298 path: Utf8PathBuf,
1300
1301 component: String,
1303 },
1304
1305 #[error("corrupted archive: checksum read error for path `{path}`")]
1307 ChecksumRead {
1308 path: Utf8PathBuf,
1310
1311 #[source]
1313 error: std::io::Error,
1314 },
1315
1316 #[error("corrupted archive: invalid checksum for path `{path}`")]
1318 InvalidChecksum {
1319 path: Utf8PathBuf,
1321
1322 expected: u32,
1324
1325 actual: u32,
1327 },
1328
1329 #[error("metadata file `{0}` not found in archive")]
1331 MetadataFileNotFound(&'static Utf8Path),
1332
1333 #[error("error deserializing metadata file `{path}` in archive")]
1335 MetadataDeserializeError {
1336 path: &'static Utf8Path,
1338
1339 #[source]
1341 error: serde_json::Error,
1342 },
1343
1344 #[error("error building package graph from `{path}` in archive")]
1346 PackageGraphConstructError {
1347 path: &'static Utf8Path,
1349
1350 #[source]
1352 error: guppy::Error,
1353 },
1354}
1355
1356#[derive(Debug, Error)]
1360#[non_exhaustive]
1361pub enum ArchiveExtractError {
1362 #[error("error creating temporary directory")]
1364 TempDirCreate(#[source] std::io::Error),
1365
1366 #[error("error canonicalizing destination directory `{dir}`")]
1368 DestDirCanonicalization {
1369 dir: Utf8PathBuf,
1371
1372 #[source]
1374 error: std::io::Error,
1375 },
1376
1377 #[error("destination `{0}` already exists")]
1379 DestinationExists(Utf8PathBuf),
1380
1381 #[error("error reading archive")]
1383 Read(#[source] ArchiveReadError),
1384
1385 #[error("error deserializing Rust build metadata")]
1387 RustBuildMeta(#[from] RustBuildMetaParseError),
1388
1389 #[error("error writing file `{path}` to disk")]
1391 WriteFile {
1392 path: Utf8PathBuf,
1394
1395 #[source]
1397 error: std::io::Error,
1398 },
1399
1400 #[error("error reporting extract status")]
1402 ReporterIo(std::io::Error),
1403}
1404
1405#[derive(Debug, Error)]
1407#[non_exhaustive]
1408pub enum WriteEventError {
1409 #[error("error writing to output")]
1411 Io(#[source] std::io::Error),
1412
1413 #[error("error operating on path {file}")]
1415 Fs {
1416 file: Utf8PathBuf,
1418
1419 #[source]
1421 error: std::io::Error,
1422 },
1423
1424 #[error("error writing JUnit output to {file}")]
1426 Junit {
1427 file: Utf8PathBuf,
1429
1430 #[source]
1432 error: quick_junit::SerializeError,
1433 },
1434}
1435
1436#[derive(Debug, Error)]
1439#[non_exhaustive]
1440pub enum CargoConfigError {
1441 #[error("failed to retrieve current directory")]
1443 GetCurrentDir(#[source] std::io::Error),
1444
1445 #[error("current directory is invalid UTF-8")]
1447 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1448
1449 #[error("failed to parse --config argument `{config_str}` as TOML")]
1451 CliConfigParseError {
1452 config_str: String,
1454
1455 #[source]
1457 error: toml_edit::TomlError,
1458 },
1459
1460 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1462 CliConfigDeError {
1463 config_str: String,
1465
1466 #[source]
1468 error: toml_edit::de::Error,
1469 },
1470
1471 #[error(
1473 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1474 )]
1475 InvalidCliConfig {
1476 config_str: String,
1478
1479 #[source]
1481 reason: InvalidCargoCliConfigReason,
1482 },
1483
1484 #[error("non-UTF-8 path encountered")]
1486 NonUtf8Path(#[source] FromPathBufError),
1487
1488 #[error("failed to retrieve the Cargo home directory")]
1490 GetCargoHome(#[source] std::io::Error),
1491
1492 #[error("failed to canonicalize path `{path}")]
1494 FailedPathCanonicalization {
1495 path: Utf8PathBuf,
1497
1498 #[source]
1500 error: std::io::Error,
1501 },
1502
1503 #[error("failed to read config at `{path}`")]
1505 ConfigReadError {
1506 path: Utf8PathBuf,
1508
1509 #[source]
1511 error: std::io::Error,
1512 },
1513
1514 #[error(transparent)]
1516 ConfigParseError(#[from] Box<CargoConfigParseError>),
1517}
1518
1519#[derive(Debug, Error)]
1523#[error("failed to parse config at `{path}`")]
1524pub struct CargoConfigParseError {
1525 pub path: Utf8PathBuf,
1527
1528 #[source]
1530 pub error: toml::de::Error,
1531}
1532
1533#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1537#[non_exhaustive]
1538pub enum InvalidCargoCliConfigReason {
1539 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1541 NotDottedKv,
1542
1543 #[error("includes non-whitespace decoration")]
1545 IncludesNonWhitespaceDecoration,
1546
1547 #[error("sets a value to an inline table, which is not accepted")]
1549 SetsValueToInlineTable,
1550
1551 #[error("sets a value to an array of tables, which is not accepted")]
1553 SetsValueToArrayOfTables,
1554
1555 #[error("doesn't provide a value")]
1557 DoesntProvideValue,
1558}
1559
1560#[derive(Debug, Error)]
1562pub enum HostPlatformDetectError {
1563 #[error(
1566 "error spawning `rustc -vV`, and detecting the build \
1567 target failed as well\n\
1568 - rustc spawn error: {}\n\
1569 - build target error: {}\n",
1570 DisplayErrorChain::new_with_initial_indent(" ", error),
1571 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1572 )]
1573 RustcVvSpawnError {
1574 error: std::io::Error,
1576
1577 build_target_error: Box<target_spec::Error>,
1579 },
1580
1581 #[error(
1584 "`rustc -vV` failed with {}, and detecting the \
1585 build target failed as well\n\
1586 - `rustc -vV` stdout:\n{}\n\
1587 - `rustc -vV` stderr:\n{}\n\
1588 - build target error:\n{}\n",
1589 status,
1590 Indented { item: String::from_utf8_lossy(stdout), indent: " " },
1591 Indented { item: String::from_utf8_lossy(stderr), indent: " " },
1592 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1593 )]
1594 RustcVvFailed {
1595 status: ExitStatus,
1597
1598 stdout: Vec<u8>,
1600
1601 stderr: Vec<u8>,
1603
1604 build_target_error: Box<target_spec::Error>,
1606 },
1607
1608 #[error(
1611 "parsing `rustc -vV` output failed, and detecting the build target \
1612 failed as well\n\
1613 - host platform error:\n{}\n\
1614 - build target error:\n{}\n",
1615 DisplayErrorChain::new_with_initial_indent(" ", host_platform_error),
1616 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1617 )]
1618 HostPlatformParseError {
1619 host_platform_error: Box<target_spec::Error>,
1621
1622 build_target_error: Box<target_spec::Error>,
1624 },
1625
1626 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1629 BuildTargetError {
1630 #[source]
1632 build_target_error: Box<target_spec::Error>,
1633 },
1634}
1635
1636#[derive(Debug, Error)]
1638pub enum TargetTripleError {
1639 #[error(
1641 "environment variable '{}' contained non-UTF-8 data",
1642 TargetTriple::CARGO_BUILD_TARGET_ENV
1643 )]
1644 InvalidEnvironmentVar,
1645
1646 #[error("error deserializing target triple from {source}")]
1648 TargetSpecError {
1649 source: TargetTripleSource,
1651
1652 #[source]
1654 error: target_spec::Error,
1655 },
1656
1657 #[error("target path `{path}` is not a valid file")]
1659 TargetPathReadError {
1660 source: TargetTripleSource,
1662
1663 path: Utf8PathBuf,
1665
1666 #[source]
1668 error: std::io::Error,
1669 },
1670
1671 #[error(
1673 "for custom platform obtained from {source}, \
1674 failed to create temporary directory for custom platform"
1675 )]
1676 CustomPlatformTempDirError {
1677 source: TargetTripleSource,
1679
1680 #[source]
1682 error: std::io::Error,
1683 },
1684
1685 #[error(
1687 "for custom platform obtained from {source}, \
1688 failed to write JSON to temporary path `{path}`"
1689 )]
1690 CustomPlatformWriteError {
1691 source: TargetTripleSource,
1693
1694 path: Utf8PathBuf,
1696
1697 #[source]
1699 error: std::io::Error,
1700 },
1701
1702 #[error(
1704 "for custom platform obtained from {source}, \
1705 failed to close temporary directory `{dir_path}`"
1706 )]
1707 CustomPlatformCloseError {
1708 source: TargetTripleSource,
1710
1711 dir_path: Utf8PathBuf,
1713
1714 #[source]
1716 error: std::io::Error,
1717 },
1718}
1719
1720impl TargetTripleError {
1721 pub fn source_report(&self) -> Option<miette::Report> {
1726 match self {
1727 Self::TargetSpecError { error, .. } => {
1728 Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1729 }
1730 TargetTripleError::InvalidEnvironmentVar
1732 | TargetTripleError::TargetPathReadError { .. }
1733 | TargetTripleError::CustomPlatformTempDirError { .. }
1734 | TargetTripleError::CustomPlatformWriteError { .. }
1735 | TargetTripleError::CustomPlatformCloseError { .. } => None,
1736 }
1737 }
1738}
1739
1740#[derive(Debug, Error)]
1742pub enum TargetRunnerError {
1743 #[error("environment variable '{0}' contained non-UTF-8 data")]
1745 InvalidEnvironmentVar(String),
1746
1747 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1750 BinaryNotSpecified {
1751 key: PlatformRunnerSource,
1753
1754 value: String,
1756 },
1757}
1758
1759#[derive(Debug, Error)]
1761#[error("error setting up signal handler")]
1762pub struct SignalHandlerSetupError(#[from] std::io::Error);
1763
1764#[derive(Debug, Error)]
1766pub enum ShowTestGroupsError {
1767 #[error(
1769 "unknown test groups specified: {}\n(known groups: {})",
1770 unknown_groups.iter().join(", "),
1771 known_groups.iter().join(", "),
1772 )]
1773 UnknownGroups {
1774 unknown_groups: BTreeSet<TestGroup>,
1776
1777 known_groups: BTreeSet<TestGroup>,
1779 },
1780}
1781
1782#[cfg(feature = "self-update")]
1783mod self_update_errors {
1784 use super::*;
1785 use mukti_metadata::ReleaseStatus;
1786 use semver::{Version, VersionReq};
1787
1788 #[cfg(feature = "self-update")]
1792 #[derive(Debug, Error)]
1793 #[non_exhaustive]
1794 pub enum UpdateError {
1795 #[error("failed to read release metadata from `{path}`")]
1797 ReadLocalMetadata {
1798 path: Utf8PathBuf,
1800
1801 #[source]
1803 error: std::io::Error,
1804 },
1805
1806 #[error("self-update failed")]
1808 SelfUpdate(#[source] self_update::errors::Error),
1809
1810 #[error("deserializing release metadata failed")]
1812 ReleaseMetadataDe(#[source] serde_json::Error),
1813
1814 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1816 VersionNotFound {
1817 version: Version,
1819
1820 known: Vec<(Version, ReleaseStatus)>,
1822 },
1823
1824 #[error("no version found matching requirement `{req}`")]
1826 NoMatchForVersionReq {
1827 req: VersionReq,
1829 },
1830
1831 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1833 MuktiProjectNotFound {
1834 not_found: String,
1836
1837 known: Vec<String>,
1839 },
1840
1841 #[error(
1843 "for version {version}, no release information found for target `{triple}` \
1844 (known targets: {})",
1845 known_triples.iter().join(", ")
1846 )]
1847 NoTargetData {
1848 version: Version,
1850
1851 triple: String,
1853
1854 known_triples: BTreeSet<String>,
1856 },
1857
1858 #[error("the current executable's path could not be determined")]
1860 CurrentExe(#[source] std::io::Error),
1861
1862 #[error("temporary directory could not be created at `{location}`")]
1864 TempDirCreate {
1865 location: Utf8PathBuf,
1867
1868 #[source]
1870 error: std::io::Error,
1871 },
1872
1873 #[error("temporary archive could not be created at `{archive_path}`")]
1875 TempArchiveCreate {
1876 archive_path: Utf8PathBuf,
1878
1879 #[source]
1881 error: std::io::Error,
1882 },
1883
1884 #[error("error writing to temporary archive at `{archive_path}`")]
1886 TempArchiveWrite {
1887 archive_path: Utf8PathBuf,
1889
1890 #[source]
1892 error: std::io::Error,
1893 },
1894
1895 #[error("error reading from temporary archive at `{archive_path}`")]
1897 TempArchiveRead {
1898 archive_path: Utf8PathBuf,
1900
1901 #[source]
1903 error: std::io::Error,
1904 },
1905
1906 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1908 ChecksumMismatch {
1909 expected: String,
1911
1912 actual: String,
1914 },
1915
1916 #[error("error renaming `{source}` to `{dest}`")]
1918 FsRename {
1919 source: Utf8PathBuf,
1921
1922 dest: Utf8PathBuf,
1924
1925 #[source]
1927 error: std::io::Error,
1928 },
1929
1930 #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
1932 SelfSetup(#[source] std::io::Error),
1933 }
1934
1935 fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
1936 use std::fmt::Write;
1937
1938 const DISPLAY_COUNT: usize = 4;
1940
1941 let display_versions: Vec<_> = versions
1942 .iter()
1943 .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
1944 .map(|(v, _)| v.to_string())
1945 .take(DISPLAY_COUNT)
1946 .collect();
1947 let mut display_str = display_versions.join(", ");
1948 if versions.len() > display_versions.len() {
1949 write!(
1950 display_str,
1951 " and {} others",
1952 versions.len() - display_versions.len()
1953 )
1954 .unwrap();
1955 }
1956
1957 display_str
1958 }
1959
1960 #[cfg(feature = "self-update")]
1961 #[derive(Debug, Error)]
1963 pub enum UpdateVersionParseError {
1964 #[error("version string is empty")]
1966 EmptyString,
1967
1968 #[error(
1970 "`{input}` is not a valid semver requirement\n\
1971 (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
1972 )]
1973 InvalidVersionReq {
1974 input: String,
1976
1977 #[source]
1979 error: semver::Error,
1980 },
1981
1982 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
1984 InvalidVersion {
1985 input: String,
1987
1988 #[source]
1990 error: semver::Error,
1991 },
1992 }
1993
1994 fn extra_semver_output(input: &str) -> String {
1995 if input.parse::<VersionReq>().is_ok() {
1998 format!(
1999 "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2000 )
2001 } else {
2002 "".to_owned()
2003 }
2004 }
2005}
2006
2007#[cfg(feature = "self-update")]
2008pub use self_update_errors::*;
2009
2010#[cfg(test)]
2011mod tests {
2012 use super::*;
2013
2014 #[test]
2015 fn display_error_chain() {
2016 let err1 = StringError::new("err1", None);
2017
2018 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2019
2020 let err2 = StringError::new("err2", Some(err1));
2021 let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2022
2023 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2024 err3
2025 err3 line 2
2026 caused by:
2027 - err2
2028 - err1
2029 ");
2030 }
2031
2032 #[test]
2033 fn display_error_list() {
2034 let err1 = StringError::new("err1", None);
2035
2036 let error_list =
2037 ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2038 .expect(">= 1 error");
2039 insta::assert_snapshot!(format!("{}", error_list), @"err1");
2040 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2041
2042 let err2 = StringError::new("err2", Some(err1));
2043 let err3 = StringError::new("err3", Some(err2));
2044
2045 let error_list =
2046 ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2047 .expect(">= 1 error");
2048 insta::assert_snapshot!(format!("{}", error_list), @"err3");
2049 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2050 err3
2051 caused by:
2052 - err2
2053 - err1
2054 ");
2055
2056 let err4 = StringError::new("err4", None);
2057 let err5 = StringError::new("err5", Some(err4));
2058 let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2059
2060 let error_list = ErrorList::<StringError>::new(
2061 "waiting for the heat death of the universe",
2062 vec![err3, err6],
2063 )
2064 .expect(">= 1 error");
2065
2066 insta::assert_snapshot!(format!("{}", error_list), @r"
2067 2 errors occurred waiting for the heat death of the universe:
2068 * err3
2069 caused by:
2070 - err2
2071 - err1
2072 * err6
2073 err6 line 2
2074 caused by:
2075 - err5
2076 - err4
2077 ");
2078 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2079 2 errors occurred waiting for the heat death of the universe:
2080 * err3
2081 caused by:
2082 - err2
2083 - err1
2084 * err6
2085 err6 line 2
2086 caused by:
2087 - err5
2088 - err4
2089 ");
2090 }
2091
2092 #[derive(Clone, Debug, Error)]
2093 struct StringError {
2094 message: String,
2095 #[source]
2096 source: Option<Box<StringError>>,
2097 }
2098
2099 impl StringError {
2100 fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2101 Self {
2102 message: message.into(),
2103 source: source.map(Box::new),
2104 }
2105 }
2106 }
2107
2108 impl fmt::Display for StringError {
2109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2110 write!(f, "{}", self.message)
2111 }
2112 }
2113}