1use crate::{
7 cargo_config::{TargetTriple, TargetTripleSource},
8 config::{
9 core::{ConfigExperimental, ToolName},
10 elements::{CustomTestGroup, TestGroup},
11 scripts::{ProfileScriptType, ScriptId, ScriptType},
12 },
13 helpers::{display_exited_with, dylib_path_envvar},
14 indenter::{DisplayIndented, indented},
15 redact::Redactor,
16 reuse_build::{ArchiveFormat, ArchiveStep},
17 target_runner::PlatformRunnerSource,
18};
19use camino::{FromPathBufError, Utf8Path, Utf8PathBuf};
20use config::ConfigError;
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_ref())
41)]
42#[non_exhaustive]
43pub struct ConfigParseError {
44 config_file: Utf8PathBuf,
45 tool: Option<ToolName>,
46 #[source]
47 kind: ConfigParseErrorKind,
48}
49
50impl ConfigParseError {
51 pub(crate) fn new(
52 config_file: impl Into<Utf8PathBuf>,
53 tool: Option<&ToolName>,
54 kind: ConfigParseErrorKind,
55 ) -> Self {
56 Self {
57 config_file: config_file.into(),
58 tool: tool.cloned(),
59 kind,
60 }
61 }
62
63 pub fn config_file(&self) -> &Utf8Path {
65 &self.config_file
66 }
67
68 pub fn tool(&self) -> Option<&ToolName> {
70 self.tool.as_ref()
71 }
72
73 pub fn kind(&self) -> &ConfigParseErrorKind {
75 &self.kind
76 }
77}
78
79pub fn provided_by_tool(tool: Option<&ToolName>) -> 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)]
98 TomlParseError(Box<toml::de::Error>),
99 #[error(transparent)]
100 DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
102 #[error(transparent)]
104 VersionOnlyReadError(std::io::Error),
105 #[error(transparent)]
107 VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
108 #[error("error parsing compiled data (destructure this variant for more details)")]
110 CompileErrors(Vec<ConfigCompileError>),
111 #[error("invalid test groups defined: {}\n(test groups cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
113 InvalidTestGroupsDefined(BTreeSet<CustomTestGroup>),
114 #[error(
116 "invalid test groups defined by tool: {}\n(test groups must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
117 InvalidTestGroupsDefinedByTool(BTreeSet<CustomTestGroup>),
118 #[error("unknown test groups specified by config (destructure this variant for more details)")]
120 UnknownTestGroups {
121 errors: Vec<UnknownTestGroupError>,
123
124 known_groups: BTreeSet<TestGroup>,
126 },
127 #[error(
129 "both `[script.*]` and `[scripts.*]` defined\n\
130 (hint: [script.*] will be removed in the future: switch to [scripts.setup.*])"
131 )]
132 BothScriptAndScriptsDefined,
133 #[error("invalid config scripts defined: {}\n(config scripts cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
135 InvalidConfigScriptsDefined(BTreeSet<ScriptId>),
136 #[error(
138 "invalid config scripts defined by tool: {}\n(config scripts must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
139 InvalidConfigScriptsDefinedByTool(BTreeSet<ScriptId>),
140 #[error(
142 "config script names used more than once: {}\n\
143 (config script names must be unique across all script types)", .0.iter().join(", ")
144 )]
145 DuplicateConfigScriptNames(BTreeSet<ScriptId>),
146 #[error(
148 "errors in profile-specific config scripts (destructure this variant for more details)"
149 )]
150 ProfileScriptErrors {
151 errors: Box<ProfileScriptErrors>,
153
154 known_scripts: BTreeSet<ScriptId>,
156 },
157 #[error("unknown experimental features defined (destructure this variant for more details)")]
159 UnknownExperimentalFeatures {
160 unknown: BTreeSet<String>,
162
163 known: BTreeSet<ConfigExperimental>,
165 },
166 #[error(
170 "tool config file specifies experimental features `{}` \
171 -- only repository config files can do so",
172 .features.iter().join(", "),
173 )]
174 ExperimentalFeaturesInToolConfig {
175 features: BTreeSet<String>,
177 },
178 #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
180 ExperimentalFeaturesNotEnabled {
181 missing_features: BTreeSet<ConfigExperimental>,
183 },
184 #[error("inheritance error(s) detected: {}", .0.iter().join(", "))]
186 InheritanceErrors(Vec<InheritsError>),
187}
188
189#[derive(Debug)]
192#[non_exhaustive]
193pub struct ConfigCompileError {
194 pub profile_name: String,
196
197 pub section: ConfigCompileSection,
199
200 pub kind: ConfigCompileErrorKind,
202}
203
204#[derive(Debug)]
207pub enum ConfigCompileSection {
208 DefaultFilter,
210
211 Override(usize),
213
214 Script(usize),
216}
217
218#[derive(Debug)]
220#[non_exhaustive]
221pub enum ConfigCompileErrorKind {
222 ConstraintsNotSpecified {
224 default_filter_specified: bool,
229 },
230
231 FilterAndDefaultFilterSpecified,
235
236 Parse {
238 host_parse_error: Option<target_spec::Error>,
240
241 target_parse_error: Option<target_spec::Error>,
243
244 filter_parse_errors: Vec<FiltersetParseErrors>,
246 },
247}
248
249impl ConfigCompileErrorKind {
250 pub fn reports(&self) -> impl Iterator<Item = miette::Report> + '_ {
252 match self {
253 Self::ConstraintsNotSpecified {
254 default_filter_specified,
255 } => {
256 let message = if *default_filter_specified {
257 "for override with `default-filter`, `platform` must also be specified"
258 } else {
259 "at least one of `platform` and `filter` must be specified"
260 };
261 Either::Left(std::iter::once(miette::Report::msg(message)))
262 }
263 Self::FilterAndDefaultFilterSpecified => {
264 Either::Left(std::iter::once(miette::Report::msg(
265 "at most one of `filter` and `default-filter` must be specified",
266 )))
267 }
268 Self::Parse {
269 host_parse_error,
270 target_parse_error,
271 filter_parse_errors,
272 } => {
273 let host_parse_report = host_parse_error
274 .as_ref()
275 .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
276 let target_parse_report = target_parse_error
277 .as_ref()
278 .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
279 let filter_parse_reports =
280 filter_parse_errors.iter().flat_map(|filter_parse_errors| {
281 filter_parse_errors.errors.iter().map(|single_error| {
282 miette::Report::new(single_error.clone())
283 .with_source_code(filter_parse_errors.input.to_owned())
284 })
285 });
286
287 Either::Right(
288 host_parse_report
289 .into_iter()
290 .chain(target_parse_report)
291 .chain(filter_parse_reports),
292 )
293 }
294 }
295 }
296}
297
298#[derive(Clone, Debug, Error)]
300#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
301pub struct TestPriorityOutOfRange {
302 pub priority: i8,
304}
305
306#[derive(Clone, Debug, Error)]
308pub enum ChildStartError {
309 #[error("error creating temporary path for setup script")]
311 TempPath(#[source] Arc<std::io::Error>),
312
313 #[error("error spawning child process")]
315 Spawn(#[source] Arc<std::io::Error>),
316}
317
318#[derive(Clone, Debug, Error)]
320pub enum SetupScriptOutputError {
321 #[error("error opening environment file `{path}`")]
323 EnvFileOpen {
324 path: Utf8PathBuf,
326
327 #[source]
329 error: Arc<std::io::Error>,
330 },
331
332 #[error("error reading environment file `{path}`")]
334 EnvFileRead {
335 path: Utf8PathBuf,
337
338 #[source]
340 error: Arc<std::io::Error>,
341 },
342
343 #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
345 EnvFileParse {
346 path: Utf8PathBuf,
348 line: String,
350 },
351
352 #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
354 EnvFileReservedKey {
355 key: String,
357 },
358}
359
360#[derive(Clone, Debug)]
365pub struct ErrorList<T> {
366 description: &'static str,
368 inner: Vec<T>,
370}
371
372impl<T: std::error::Error> ErrorList<T> {
373 pub(crate) fn new<U>(description: &'static str, errors: Vec<U>) -> Option<Self>
374 where
375 T: From<U>,
376 {
377 if errors.is_empty() {
378 None
379 } else {
380 Some(Self {
381 description,
382 inner: errors.into_iter().map(T::from).collect(),
383 })
384 }
385 }
386
387 pub(crate) fn short_message(&self) -> String {
389 let string = self.to_string();
390 match string.lines().next() {
391 Some(first_line) => first_line.trim_end_matches(':').to_string(),
393 None => String::new(),
394 }
395 }
396
397 pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
398 self.inner.iter()
399 }
400}
401
402impl<T: std::error::Error> fmt::Display for ErrorList<T> {
403 fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
404 if self.inner.len() == 1 {
406 return write!(f, "{}", self.inner[0]);
407 }
408
409 writeln!(
411 f,
412 "{} errors occurred {}:",
413 self.inner.len(),
414 self.description,
415 )?;
416 for error in &self.inner {
417 let mut indent = indented(f).with_str(" ").skip_initial();
418 writeln!(indent, "* {}", DisplayErrorChain::new(error))?;
419 f = indent.into_inner();
420 }
421 Ok(())
422 }
423}
424
425impl<T: std::error::Error> std::error::Error for ErrorList<T> {
426 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
427 if self.inner.len() == 1 {
428 self.inner[0].source()
429 } else {
430 None
433 }
434 }
435}
436
437pub(crate) struct DisplayErrorChain<E> {
442 error: E,
443 initial_indent: &'static str,
444}
445
446impl<E: std::error::Error> DisplayErrorChain<E> {
447 pub(crate) fn new(error: E) -> Self {
448 Self {
449 error,
450 initial_indent: "",
451 }
452 }
453
454 pub(crate) fn new_with_initial_indent(initial_indent: &'static str, error: E) -> Self {
455 Self {
456 error,
457 initial_indent,
458 }
459 }
460}
461
462impl<E> fmt::Display for DisplayErrorChain<E>
463where
464 E: std::error::Error,
465{
466 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
467 let mut writer = indented(f).with_str(self.initial_indent);
468 write!(writer, "{}", self.error)?;
469
470 let Some(mut cause) = self.error.source() else {
471 return Ok(());
472 };
473
474 write!(writer, "\n caused by:")?;
475
476 loop {
477 writeln!(writer)?;
478 let mut indent = indented(&mut writer).with_str(" ").skip_initial();
480 write!(indent, " - {cause}")?;
481
482 let Some(next_cause) = cause.source() else {
483 break Ok(());
484 };
485
486 cause = next_cause;
487 }
488 }
489}
490
491#[derive(Clone, Debug, Error)]
493pub enum ChildError {
494 #[error(transparent)]
496 Fd(#[from] ChildFdError),
497
498 #[error(transparent)]
500 SetupScriptOutput(#[from] SetupScriptOutputError),
501}
502
503#[derive(Clone, Debug, Error)]
505pub enum ChildFdError {
506 #[error("error reading standard output")]
508 ReadStdout(#[source] Arc<std::io::Error>),
509
510 #[error("error reading standard error")]
512 ReadStderr(#[source] Arc<std::io::Error>),
513
514 #[error("error reading combined stream")]
516 ReadCombined(#[source] Arc<std::io::Error>),
517
518 #[error("error waiting for child process to exit")]
520 Wait(#[source] Arc<std::io::Error>),
521}
522
523#[derive(Clone, Debug, Eq, PartialEq)]
525#[non_exhaustive]
526pub struct UnknownTestGroupError {
527 pub profile_name: String,
529
530 pub name: TestGroup,
532}
533
534#[derive(Clone, Debug, Eq, PartialEq)]
537pub struct ProfileUnknownScriptError {
538 pub profile_name: String,
540
541 pub name: ScriptId,
543}
544
545#[derive(Clone, Debug, Eq, PartialEq)]
548pub struct ProfileWrongConfigScriptTypeError {
549 pub profile_name: String,
551
552 pub name: ScriptId,
554
555 pub attempted: ProfileScriptType,
557
558 pub actual: ScriptType,
560}
561
562#[derive(Clone, Debug, Eq, PartialEq)]
565pub struct ProfileListScriptUsesRunFiltersError {
566 pub profile_name: String,
568
569 pub name: ScriptId,
571
572 pub script_type: ProfileScriptType,
574
575 pub filters: BTreeSet<String>,
577}
578
579#[derive(Clone, Debug, Default)]
581pub struct ProfileScriptErrors {
582 pub unknown_scripts: Vec<ProfileUnknownScriptError>,
584
585 pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
587
588 pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
590}
591
592impl ProfileScriptErrors {
593 pub fn is_empty(&self) -> bool {
595 self.unknown_scripts.is_empty()
596 && self.wrong_script_types.is_empty()
597 && self.list_scripts_using_run_filters.is_empty()
598 }
599}
600
601#[derive(Clone, Debug, Error)]
603#[error("profile `{profile}` not found (known profiles: {})", .all_profiles.join(", "))]
604pub struct ProfileNotFound {
605 profile: String,
606 all_profiles: Vec<String>,
607}
608
609impl ProfileNotFound {
610 pub(crate) fn new(
611 profile: impl Into<String>,
612 all_profiles: impl IntoIterator<Item = impl Into<String>>,
613 ) -> Self {
614 let mut all_profiles: Vec<_> = all_profiles.into_iter().map(|s| s.into()).collect();
615 all_profiles.sort_unstable();
616 Self {
617 profile: profile.into(),
618 all_profiles,
619 }
620 }
621}
622
623#[derive(Clone, Debug, Error, Eq, PartialEq)]
625pub enum InvalidIdentifier {
626 #[error("identifier is empty")]
628 Empty,
629
630 #[error("invalid identifier `{0}`")]
632 InvalidXid(SmolStr),
633
634 #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
636 ToolIdentifierInvalidFormat(SmolStr),
637
638 #[error("tool identifier has empty component: `{0}`")]
640 ToolComponentEmpty(SmolStr),
641
642 #[error("invalid tool identifier `{0}`")]
644 ToolIdentifierInvalidXid(SmolStr),
645}
646
647#[derive(Clone, Debug, Error, Eq, PartialEq)]
649pub enum InvalidToolName {
650 #[error("tool name is empty")]
652 Empty,
653
654 #[error("invalid tool name `{0}`")]
656 InvalidXid(SmolStr),
657
658 #[error("tool name cannot start with \"@tool\": `{0}`")]
660 StartsWithToolPrefix(SmolStr),
661}
662
663#[derive(Clone, Debug, Error)]
665#[error("invalid custom test group name: {0}")]
666pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
667
668#[derive(Clone, Debug, Error)]
670#[error("invalid configuration script name: {0}")]
671pub struct InvalidConfigScriptName(pub InvalidIdentifier);
672
673#[derive(Clone, Debug, Error, PartialEq, Eq)]
675pub enum ToolConfigFileParseError {
676 #[error(
677 "tool-config-file has invalid format: {input}\n(hint: tool configs must be in the format <tool-name>:<path>)"
678 )]
679 InvalidFormat {
681 input: String,
683 },
684
685 #[error("tool-config-file has invalid tool name: {input}")]
687 InvalidToolName {
688 input: String,
690
691 #[source]
693 error: InvalidToolName,
694 },
695
696 #[error("tool-config-file has empty config file path: {input}")]
698 EmptyConfigFile {
699 input: String,
701 },
702
703 #[error("tool-config-file is not an absolute path: {config_file}")]
705 ConfigFileNotAbsolute {
706 config_file: Utf8PathBuf,
708 },
709}
710
711#[derive(Clone, Debug, Error)]
713#[error("unrecognized value for max-fail: {reason}")]
714pub struct MaxFailParseError {
715 pub reason: String,
717}
718
719impl MaxFailParseError {
720 pub(crate) fn new(reason: impl Into<String>) -> Self {
721 Self {
722 reason: reason.into(),
723 }
724 }
725}
726
727#[derive(Clone, Debug, Error)]
729#[error(
730 "unrecognized value for stress-count: {input}\n\
731 (hint: expected either a positive integer or \"infinite\")"
732)]
733pub struct StressCountParseError {
734 pub input: String,
736}
737
738impl StressCountParseError {
739 pub(crate) fn new(input: impl Into<String>) -> Self {
740 Self {
741 input: input.into(),
742 }
743 }
744}
745
746#[derive(Clone, Debug, Error)]
748#[non_exhaustive]
749pub enum DebuggerCommandParseError {
750 #[error(transparent)]
752 ShellWordsParse(shell_words::ParseError),
753
754 #[error("debugger command cannot be empty")]
756 EmptyCommand,
757}
758
759#[derive(Clone, Debug, Error)]
761#[non_exhaustive]
762pub enum TracerCommandParseError {
763 #[error(transparent)]
765 ShellWordsParse(shell_words::ParseError),
766
767 #[error("tracer command cannot be empty")]
769 EmptyCommand,
770}
771
772#[derive(Clone, Debug, Error)]
774#[error(
775 "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
776)]
777pub struct TestThreadsParseError {
778 pub input: String,
780}
781
782impl TestThreadsParseError {
783 pub(crate) fn new(input: impl Into<String>) -> Self {
784 Self {
785 input: input.into(),
786 }
787 }
788}
789
790#[derive(Clone, Debug, Error)]
793pub struct PartitionerBuilderParseError {
794 expected_format: Option<&'static str>,
795 message: Cow<'static, str>,
796}
797
798impl PartitionerBuilderParseError {
799 pub(crate) fn new(
800 expected_format: Option<&'static str>,
801 message: impl Into<Cow<'static, str>>,
802 ) -> Self {
803 Self {
804 expected_format,
805 message: message.into(),
806 }
807 }
808}
809
810impl fmt::Display for PartitionerBuilderParseError {
811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
812 match self.expected_format {
813 Some(format) => {
814 write!(
815 f,
816 "partition must be in the format \"{}\":\n{}",
817 format, self.message
818 )
819 }
820 None => write!(f, "{}", self.message),
821 }
822 }
823}
824
825#[derive(Clone, Debug, Error)]
828pub enum TestFilterBuilderError {
829 #[error("error constructing test filters")]
831 Construct {
832 #[from]
834 error: aho_corasick::BuildError,
835 },
836}
837
838#[derive(Debug, Error)]
840pub enum PathMapperConstructError {
841 #[error("{kind} `{input}` failed to canonicalize")]
843 Canonicalization {
844 kind: PathMapperConstructKind,
846
847 input: Utf8PathBuf,
849
850 #[source]
852 err: std::io::Error,
853 },
854 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
856 NonUtf8Path {
857 kind: PathMapperConstructKind,
859
860 input: Utf8PathBuf,
862
863 #[source]
865 err: FromPathBufError,
866 },
867 #[error("{kind} `{canonicalized_path}` is not a directory")]
869 NotADirectory {
870 kind: PathMapperConstructKind,
872
873 input: Utf8PathBuf,
875
876 canonicalized_path: Utf8PathBuf,
878 },
879}
880
881impl PathMapperConstructError {
882 pub fn kind(&self) -> PathMapperConstructKind {
884 match self {
885 Self::Canonicalization { kind, .. }
886 | Self::NonUtf8Path { kind, .. }
887 | Self::NotADirectory { kind, .. } => *kind,
888 }
889 }
890
891 pub fn input(&self) -> &Utf8Path {
893 match self {
894 Self::Canonicalization { input, .. }
895 | Self::NonUtf8Path { input, .. }
896 | Self::NotADirectory { input, .. } => input,
897 }
898 }
899}
900
901#[derive(Copy, Clone, Debug, PartialEq, Eq)]
906pub enum PathMapperConstructKind {
907 WorkspaceRoot,
909
910 TargetDir,
912}
913
914impl fmt::Display for PathMapperConstructKind {
915 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
916 match self {
917 Self::WorkspaceRoot => write!(f, "remapped workspace root"),
918 Self::TargetDir => write!(f, "remapped target directory"),
919 }
920 }
921}
922
923#[derive(Debug, Error)]
925pub enum RustBuildMetaParseError {
926 #[error("error deserializing platform from build metadata")]
928 PlatformDeserializeError(#[from] target_spec::Error),
929
930 #[error("the host platform could not be determined")]
932 DetectBuildTargetError(#[source] target_spec::Error),
933
934 #[error("unsupported features in the build metadata: {message}")]
936 Unsupported {
937 message: String,
939 },
940}
941
942#[derive(Clone, Debug, thiserror::Error)]
945#[error("invalid format version: {input}")]
946pub struct FormatVersionError {
947 pub input: String,
949 #[source]
951 pub error: FormatVersionErrorInner,
952}
953
954#[derive(Clone, Debug, thiserror::Error)]
956pub enum FormatVersionErrorInner {
957 #[error("expected format version in form of `{expected}`")]
959 InvalidFormat {
960 expected: &'static str,
962 },
963 #[error("version component `{which}` could not be parsed as an integer")]
965 InvalidInteger {
966 which: &'static str,
968 #[source]
970 err: std::num::ParseIntError,
971 },
972 #[error("version component `{which}` value {value} is out of range {range:?}")]
974 InvalidValue {
975 which: &'static str,
977 value: u8,
979 range: std::ops::Range<u8>,
981 },
982}
983
984#[derive(Debug, Error)]
987#[non_exhaustive]
988pub enum FromMessagesError {
989 #[error("error reading Cargo JSON messages")]
991 ReadMessages(#[source] std::io::Error),
992
993 #[error("error querying package graph")]
995 PackageGraph(#[source] guppy::Error),
996
997 #[error("missing kind for target {binary_name} in package {package_name}")]
999 MissingTargetKind {
1000 package_name: String,
1002 binary_name: String,
1004 },
1005}
1006
1007#[derive(Debug, Error)]
1009#[non_exhaustive]
1010pub enum CreateTestListError {
1011 #[error(
1013 "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
1014 (hint: ensure project source is available at this location)"
1015 )]
1016 CwdIsNotDir {
1017 binary_id: RustBinaryId,
1019
1020 cwd: Utf8PathBuf,
1022 },
1023
1024 #[error(
1026 "for `{binary_id}`, running command `{}` failed to execute",
1027 shell_words::join(command)
1028 )]
1029 CommandExecFail {
1030 binary_id: RustBinaryId,
1032
1033 command: Vec<String>,
1035
1036 #[source]
1038 error: std::io::Error,
1039 },
1040
1041 #[error(
1043 "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1044 shell_words::join(command),
1045 display_exited_with(*exit_status),
1046 String::from_utf8_lossy(stdout),
1047 String::from_utf8_lossy(stderr),
1048 )]
1049 CommandFail {
1050 binary_id: RustBinaryId,
1052
1053 command: Vec<String>,
1055
1056 exit_status: ExitStatus,
1058
1059 stdout: Vec<u8>,
1061
1062 stderr: Vec<u8>,
1064 },
1065
1066 #[error(
1068 "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1069 shell_words::join(command),
1070 String::from_utf8_lossy(stdout),
1071 String::from_utf8_lossy(stderr)
1072 )]
1073 CommandNonUtf8 {
1074 binary_id: RustBinaryId,
1076
1077 command: Vec<String>,
1079
1080 stdout: Vec<u8>,
1082
1083 stderr: Vec<u8>,
1085 },
1086
1087 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1089 ParseLine {
1090 binary_id: RustBinaryId,
1092
1093 message: Cow<'static, str>,
1095
1096 full_output: String,
1098 },
1099
1100 #[error(
1102 "error joining dynamic library paths for {}: [{}]",
1103 dylib_path_envvar(),
1104 itertools::join(.new_paths, ", ")
1105 )]
1106 DylibJoinPaths {
1107 new_paths: Vec<Utf8PathBuf>,
1109
1110 #[source]
1112 error: JoinPathsError,
1113 },
1114
1115 #[error("error creating Tokio runtime")]
1117 TokioRuntimeCreate(#[source] std::io::Error),
1118}
1119
1120impl CreateTestListError {
1121 pub(crate) fn parse_line(
1122 binary_id: RustBinaryId,
1123 message: impl Into<Cow<'static, str>>,
1124 full_output: impl Into<String>,
1125 ) -> Self {
1126 Self::ParseLine {
1127 binary_id,
1128 message: message.into(),
1129 full_output: full_output.into(),
1130 }
1131 }
1132
1133 pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1134 Self::DylibJoinPaths { new_paths, error }
1135 }
1136}
1137
1138#[derive(Debug, Error)]
1140#[non_exhaustive]
1141pub enum WriteTestListError {
1142 #[error("error writing to output")]
1144 Io(#[source] std::io::Error),
1145
1146 #[error("error serializing to JSON")]
1148 Json(#[source] serde_json::Error),
1149}
1150
1151#[derive(Debug, Error)]
1155pub enum ConfigureHandleInheritanceError {
1156 #[cfg(windows)]
1158 #[error("error configuring handle inheritance")]
1159 WindowsError(#[from] std::io::Error),
1160}
1161
1162#[derive(Debug, Error)]
1164#[non_exhaustive]
1165pub enum TestRunnerBuildError {
1166 #[error("error creating Tokio runtime")]
1168 TokioRuntimeCreate(#[source] std::io::Error),
1169
1170 #[error("error setting up signals")]
1172 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1173}
1174
1175#[derive(Debug, Error)]
1177pub struct TestRunnerExecuteErrors<E> {
1178 pub report_error: Option<E>,
1180
1181 pub join_errors: Vec<tokio::task::JoinError>,
1184}
1185
1186impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188 if let Some(report_error) = &self.report_error {
1189 write!(f, "error reporting results: {report_error}")?;
1190 }
1191
1192 if !self.join_errors.is_empty() {
1193 if self.report_error.is_some() {
1194 write!(f, "; ")?;
1195 }
1196
1197 write!(f, "errors joining tasks: ")?;
1198
1199 for (i, join_error) in self.join_errors.iter().enumerate() {
1200 if i > 0 {
1201 write!(f, ", ")?;
1202 }
1203
1204 write!(f, "{join_error}")?;
1205 }
1206 }
1207
1208 Ok(())
1209 }
1210}
1211
1212#[derive(Debug, Error)]
1216#[error(
1217 "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1218 supported_extensions()
1219)]
1220pub struct UnknownArchiveFormat {
1221 pub file_name: String,
1223}
1224
1225fn supported_extensions() -> String {
1226 ArchiveFormat::SUPPORTED_FORMATS
1227 .iter()
1228 .map(|(extension, _)| *extension)
1229 .join(", ")
1230}
1231
1232#[derive(Debug, Error)]
1234#[non_exhaustive]
1235pub enum ArchiveCreateError {
1236 #[error("error creating binary list")]
1238 CreateBinaryList(#[source] WriteTestListError),
1239
1240 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1242 MissingExtraPath {
1243 path: Utf8PathBuf,
1245
1246 redactor: Redactor,
1251 },
1252
1253 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1255 InputFileRead {
1256 step: ArchiveStep,
1258
1259 path: Utf8PathBuf,
1261
1262 is_dir: Option<bool>,
1264
1265 #[source]
1267 error: std::io::Error,
1268 },
1269
1270 #[error("error reading directory entry from `{path}")]
1272 DirEntryRead {
1273 path: Utf8PathBuf,
1275
1276 #[source]
1278 error: std::io::Error,
1279 },
1280
1281 #[error("error writing to archive")]
1283 OutputArchiveIo(#[source] std::io::Error),
1284
1285 #[error("error reporting archive status")]
1287 ReporterIo(#[source] std::io::Error),
1288}
1289
1290fn kind_str(is_dir: Option<bool>) -> &'static str {
1291 match is_dir {
1292 Some(true) => "directory",
1293 Some(false) => "file",
1294 None => "path",
1295 }
1296}
1297
1298#[derive(Debug, Error)]
1300pub enum MetadataMaterializeError {
1301 #[error("I/O error reading metadata file `{path}`")]
1303 Read {
1304 path: Utf8PathBuf,
1306
1307 #[source]
1309 error: std::io::Error,
1310 },
1311
1312 #[error("error deserializing metadata file `{path}`")]
1314 Deserialize {
1315 path: Utf8PathBuf,
1317
1318 #[source]
1320 error: serde_json::Error,
1321 },
1322
1323 #[error("error parsing Rust build metadata from `{path}`")]
1325 RustBuildMeta {
1326 path: Utf8PathBuf,
1328
1329 #[source]
1331 error: RustBuildMetaParseError,
1332 },
1333
1334 #[error("error building package graph from `{path}`")]
1336 PackageGraphConstruct {
1337 path: Utf8PathBuf,
1339
1340 #[source]
1342 error: guppy::Error,
1343 },
1344}
1345
1346#[derive(Debug, Error)]
1350#[non_exhaustive]
1351pub enum ArchiveReadError {
1352 #[error("I/O error reading archive")]
1354 Io(#[source] std::io::Error),
1355
1356 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1358 NonUtf8Path(Vec<u8>),
1359
1360 #[error("path in archive `{0}` doesn't start with `target/`")]
1362 NoTargetPrefix(Utf8PathBuf),
1363
1364 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1366 InvalidComponent {
1367 path: Utf8PathBuf,
1369
1370 component: String,
1372 },
1373
1374 #[error("corrupted archive: checksum read error for path `{path}`")]
1376 ChecksumRead {
1377 path: Utf8PathBuf,
1379
1380 #[source]
1382 error: std::io::Error,
1383 },
1384
1385 #[error("corrupted archive: invalid checksum for path `{path}`")]
1387 InvalidChecksum {
1388 path: Utf8PathBuf,
1390
1391 expected: u32,
1393
1394 actual: u32,
1396 },
1397
1398 #[error("metadata file `{0}` not found in archive")]
1400 MetadataFileNotFound(&'static Utf8Path),
1401
1402 #[error("error deserializing metadata file `{path}` in archive")]
1404 MetadataDeserializeError {
1405 path: &'static Utf8Path,
1407
1408 #[source]
1410 error: serde_json::Error,
1411 },
1412
1413 #[error("error building package graph from `{path}` in archive")]
1415 PackageGraphConstructError {
1416 path: &'static Utf8Path,
1418
1419 #[source]
1421 error: guppy::Error,
1422 },
1423}
1424
1425#[derive(Debug, Error)]
1429#[non_exhaustive]
1430pub enum ArchiveExtractError {
1431 #[error("error creating temporary directory")]
1433 TempDirCreate(#[source] std::io::Error),
1434
1435 #[error("error canonicalizing destination directory `{dir}`")]
1437 DestDirCanonicalization {
1438 dir: Utf8PathBuf,
1440
1441 #[source]
1443 error: std::io::Error,
1444 },
1445
1446 #[error("destination `{0}` already exists")]
1448 DestinationExists(Utf8PathBuf),
1449
1450 #[error("error reading archive")]
1452 Read(#[source] ArchiveReadError),
1453
1454 #[error("error deserializing Rust build metadata")]
1456 RustBuildMeta(#[from] RustBuildMetaParseError),
1457
1458 #[error("error writing file `{path}` to disk")]
1460 WriteFile {
1461 path: Utf8PathBuf,
1463
1464 #[source]
1466 error: std::io::Error,
1467 },
1468
1469 #[error("error reporting extract status")]
1471 ReporterIo(std::io::Error),
1472}
1473
1474#[derive(Debug, Error)]
1476#[non_exhaustive]
1477pub enum WriteEventError {
1478 #[error("error writing to output")]
1480 Io(#[source] std::io::Error),
1481
1482 #[error("error operating on path {file}")]
1484 Fs {
1485 file: Utf8PathBuf,
1487
1488 #[source]
1490 error: std::io::Error,
1491 },
1492
1493 #[error("error writing JUnit output to {file}")]
1495 Junit {
1496 file: Utf8PathBuf,
1498
1499 #[source]
1501 error: quick_junit::SerializeError,
1502 },
1503}
1504
1505#[derive(Debug, Error)]
1508#[non_exhaustive]
1509pub enum CargoConfigError {
1510 #[error("failed to retrieve current directory")]
1512 GetCurrentDir(#[source] std::io::Error),
1513
1514 #[error("current directory is invalid UTF-8")]
1516 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1517
1518 #[error("failed to parse --config argument `{config_str}` as TOML")]
1520 CliConfigParseError {
1521 config_str: String,
1523
1524 #[source]
1526 error: toml_edit::TomlError,
1527 },
1528
1529 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1531 CliConfigDeError {
1532 config_str: String,
1534
1535 #[source]
1537 error: toml_edit::de::Error,
1538 },
1539
1540 #[error(
1542 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1543 )]
1544 InvalidCliConfig {
1545 config_str: String,
1547
1548 #[source]
1550 reason: InvalidCargoCliConfigReason,
1551 },
1552
1553 #[error("non-UTF-8 path encountered")]
1555 NonUtf8Path(#[source] FromPathBufError),
1556
1557 #[error("failed to retrieve the Cargo home directory")]
1559 GetCargoHome(#[source] std::io::Error),
1560
1561 #[error("failed to canonicalize path `{path}")]
1563 FailedPathCanonicalization {
1564 path: Utf8PathBuf,
1566
1567 #[source]
1569 error: std::io::Error,
1570 },
1571
1572 #[error("failed to read config at `{path}`")]
1574 ConfigReadError {
1575 path: Utf8PathBuf,
1577
1578 #[source]
1580 error: std::io::Error,
1581 },
1582
1583 #[error(transparent)]
1585 ConfigParseError(#[from] Box<CargoConfigParseError>),
1586}
1587
1588#[derive(Debug, Error)]
1592#[error("failed to parse config at `{path}`")]
1593pub struct CargoConfigParseError {
1594 pub path: Utf8PathBuf,
1596
1597 #[source]
1599 pub error: toml::de::Error,
1600}
1601
1602#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1606#[non_exhaustive]
1607pub enum InvalidCargoCliConfigReason {
1608 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1610 NotDottedKv,
1611
1612 #[error("includes non-whitespace decoration")]
1614 IncludesNonWhitespaceDecoration,
1615
1616 #[error("sets a value to an inline table, which is not accepted")]
1618 SetsValueToInlineTable,
1619
1620 #[error("sets a value to an array of tables, which is not accepted")]
1622 SetsValueToArrayOfTables,
1623
1624 #[error("doesn't provide a value")]
1626 DoesntProvideValue,
1627}
1628
1629#[derive(Debug, Error)]
1631pub enum HostPlatformDetectError {
1632 #[error(
1635 "error spawning `rustc -vV`, and detecting the build \
1636 target failed as well\n\
1637 - rustc spawn error: {}\n\
1638 - build target error: {}\n",
1639 DisplayErrorChain::new_with_initial_indent(" ", error),
1640 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1641 )]
1642 RustcVvSpawnError {
1643 error: std::io::Error,
1645
1646 build_target_error: Box<target_spec::Error>,
1648 },
1649
1650 #[error(
1653 "`rustc -vV` failed with {}, and detecting the \
1654 build target failed as well\n\
1655 - `rustc -vV` stdout:\n{}\n\
1656 - `rustc -vV` stderr:\n{}\n\
1657 - build target error:\n{}\n",
1658 status,
1659 DisplayIndented { item: String::from_utf8_lossy(stdout), indent: " " },
1660 DisplayIndented { item: String::from_utf8_lossy(stderr), indent: " " },
1661 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1662 )]
1663 RustcVvFailed {
1664 status: ExitStatus,
1666
1667 stdout: Vec<u8>,
1669
1670 stderr: Vec<u8>,
1672
1673 build_target_error: Box<target_spec::Error>,
1675 },
1676
1677 #[error(
1680 "parsing `rustc -vV` output failed, and detecting the build target \
1681 failed as well\n\
1682 - host platform error:\n{}\n\
1683 - build target error:\n{}\n",
1684 DisplayErrorChain::new_with_initial_indent(" ", host_platform_error),
1685 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1686 )]
1687 HostPlatformParseError {
1688 host_platform_error: Box<target_spec::Error>,
1690
1691 build_target_error: Box<target_spec::Error>,
1693 },
1694
1695 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1698 BuildTargetError {
1699 #[source]
1701 build_target_error: Box<target_spec::Error>,
1702 },
1703}
1704
1705#[derive(Debug, Error)]
1707pub enum TargetTripleError {
1708 #[error(
1710 "environment variable '{}' contained non-UTF-8 data",
1711 TargetTriple::CARGO_BUILD_TARGET_ENV
1712 )]
1713 InvalidEnvironmentVar,
1714
1715 #[error("error deserializing target triple from {source}")]
1717 TargetSpecError {
1718 source: TargetTripleSource,
1720
1721 #[source]
1723 error: target_spec::Error,
1724 },
1725
1726 #[error("target path `{path}` is not a valid file")]
1728 TargetPathReadError {
1729 source: TargetTripleSource,
1731
1732 path: Utf8PathBuf,
1734
1735 #[source]
1737 error: std::io::Error,
1738 },
1739
1740 #[error(
1742 "for custom platform obtained from {source}, \
1743 failed to create temporary directory for custom platform"
1744 )]
1745 CustomPlatformTempDirError {
1746 source: TargetTripleSource,
1748
1749 #[source]
1751 error: std::io::Error,
1752 },
1753
1754 #[error(
1756 "for custom platform obtained from {source}, \
1757 failed to write JSON to temporary path `{path}`"
1758 )]
1759 CustomPlatformWriteError {
1760 source: TargetTripleSource,
1762
1763 path: Utf8PathBuf,
1765
1766 #[source]
1768 error: std::io::Error,
1769 },
1770
1771 #[error(
1773 "for custom platform obtained from {source}, \
1774 failed to close temporary directory `{dir_path}`"
1775 )]
1776 CustomPlatformCloseError {
1777 source: TargetTripleSource,
1779
1780 dir_path: Utf8PathBuf,
1782
1783 #[source]
1785 error: std::io::Error,
1786 },
1787}
1788
1789impl TargetTripleError {
1790 pub fn source_report(&self) -> Option<miette::Report> {
1795 match self {
1796 Self::TargetSpecError { error, .. } => {
1797 Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1798 }
1799 TargetTripleError::InvalidEnvironmentVar
1801 | TargetTripleError::TargetPathReadError { .. }
1802 | TargetTripleError::CustomPlatformTempDirError { .. }
1803 | TargetTripleError::CustomPlatformWriteError { .. }
1804 | TargetTripleError::CustomPlatformCloseError { .. } => None,
1805 }
1806 }
1807}
1808
1809#[derive(Debug, Error)]
1811pub enum TargetRunnerError {
1812 #[error("environment variable '{0}' contained non-UTF-8 data")]
1814 InvalidEnvironmentVar(String),
1815
1816 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1819 BinaryNotSpecified {
1820 key: PlatformRunnerSource,
1822
1823 value: String,
1825 },
1826}
1827
1828#[derive(Debug, Error)]
1830#[error("error setting up signal handler")]
1831pub struct SignalHandlerSetupError(#[from] std::io::Error);
1832
1833#[derive(Debug, Error)]
1835pub enum ShowTestGroupsError {
1836 #[error(
1838 "unknown test groups specified: {}\n(known groups: {})",
1839 unknown_groups.iter().join(", "),
1840 known_groups.iter().join(", "),
1841 )]
1842 UnknownGroups {
1843 unknown_groups: BTreeSet<TestGroup>,
1845
1846 known_groups: BTreeSet<TestGroup>,
1848 },
1849}
1850
1851#[derive(Debug, Error, PartialEq, Eq, Hash)]
1853pub enum InheritsError {
1854 #[error("the {} profile should not inherit from other profiles", .0)]
1856 DefaultProfileInheritance(String),
1857 #[error("profile {} inherits from an unknown profile {}", .0, .1)]
1859 UnknownInheritance(String, String),
1860 #[error("a self referential inheritance is detected from profile: {}", .0)]
1862 SelfReferentialInheritance(String),
1863 #[error("inheritance cycle detected in profile configuration from: {}", .0.iter().map(|scc| {
1865 format!("[{}]", scc.iter().join(", "))
1866 }).join(", "))]
1867 InheritanceCycle(Vec<Vec<String>>),
1868}
1869
1870#[cfg(feature = "self-update")]
1871mod self_update_errors {
1872 use super::*;
1873 use mukti_metadata::ReleaseStatus;
1874 use semver::{Version, VersionReq};
1875
1876 #[cfg(feature = "self-update")]
1880 #[derive(Debug, Error)]
1881 #[non_exhaustive]
1882 pub enum UpdateError {
1883 #[error("failed to read release metadata from `{path}`")]
1885 ReadLocalMetadata {
1886 path: Utf8PathBuf,
1888
1889 #[source]
1891 error: std::io::Error,
1892 },
1893
1894 #[error("self-update failed")]
1896 SelfUpdate(#[source] self_update::errors::Error),
1897
1898 #[error("deserializing release metadata failed")]
1900 ReleaseMetadataDe(#[source] serde_json::Error),
1901
1902 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1904 VersionNotFound {
1905 version: Version,
1907
1908 known: Vec<(Version, ReleaseStatus)>,
1910 },
1911
1912 #[error("no version found matching requirement `{req}`")]
1914 NoMatchForVersionReq {
1915 req: VersionReq,
1917 },
1918
1919 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1921 MuktiProjectNotFound {
1922 not_found: String,
1924
1925 known: Vec<String>,
1927 },
1928
1929 #[error(
1931 "for version {version}, no release information found for target `{triple}` \
1932 (known targets: {})",
1933 known_triples.iter().join(", ")
1934 )]
1935 NoTargetData {
1936 version: Version,
1938
1939 triple: String,
1941
1942 known_triples: BTreeSet<String>,
1944 },
1945
1946 #[error("the current executable's path could not be determined")]
1948 CurrentExe(#[source] std::io::Error),
1949
1950 #[error("temporary directory could not be created at `{location}`")]
1952 TempDirCreate {
1953 location: Utf8PathBuf,
1955
1956 #[source]
1958 error: std::io::Error,
1959 },
1960
1961 #[error("temporary archive could not be created at `{archive_path}`")]
1963 TempArchiveCreate {
1964 archive_path: Utf8PathBuf,
1966
1967 #[source]
1969 error: std::io::Error,
1970 },
1971
1972 #[error("error writing to temporary archive at `{archive_path}`")]
1974 TempArchiveWrite {
1975 archive_path: Utf8PathBuf,
1977
1978 #[source]
1980 error: std::io::Error,
1981 },
1982
1983 #[error("error reading from temporary archive at `{archive_path}`")]
1985 TempArchiveRead {
1986 archive_path: Utf8PathBuf,
1988
1989 #[source]
1991 error: std::io::Error,
1992 },
1993
1994 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1996 ChecksumMismatch {
1997 expected: String,
1999
2000 actual: String,
2002 },
2003
2004 #[error("error renaming `{source}` to `{dest}`")]
2006 FsRename {
2007 source: Utf8PathBuf,
2009
2010 dest: Utf8PathBuf,
2012
2013 #[source]
2015 error: std::io::Error,
2016 },
2017
2018 #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
2020 SelfSetup(#[source] std::io::Error),
2021 }
2022
2023 fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
2024 use std::fmt::Write;
2025
2026 const DISPLAY_COUNT: usize = 4;
2028
2029 let display_versions: Vec<_> = versions
2030 .iter()
2031 .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
2032 .map(|(v, _)| v.to_string())
2033 .take(DISPLAY_COUNT)
2034 .collect();
2035 let mut display_str = display_versions.join(", ");
2036 if versions.len() > display_versions.len() {
2037 write!(
2038 display_str,
2039 " and {} others",
2040 versions.len() - display_versions.len()
2041 )
2042 .unwrap();
2043 }
2044
2045 display_str
2046 }
2047
2048 #[cfg(feature = "self-update")]
2049 #[derive(Debug, Error)]
2051 pub enum UpdateVersionParseError {
2052 #[error("version string is empty")]
2054 EmptyString,
2055
2056 #[error(
2058 "`{input}` is not a valid semver requirement\n\
2059 (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
2060 )]
2061 InvalidVersionReq {
2062 input: String,
2064
2065 #[source]
2067 error: semver::Error,
2068 },
2069
2070 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2072 InvalidVersion {
2073 input: String,
2075
2076 #[source]
2078 error: semver::Error,
2079 },
2080 }
2081
2082 fn extra_semver_output(input: &str) -> String {
2083 if input.parse::<VersionReq>().is_ok() {
2086 format!(
2087 "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2088 )
2089 } else {
2090 "".to_owned()
2091 }
2092 }
2093}
2094
2095#[cfg(feature = "self-update")]
2096pub use self_update_errors::*;
2097
2098#[cfg(test)]
2099mod tests {
2100 use super::*;
2101
2102 #[test]
2103 fn display_error_chain() {
2104 let err1 = StringError::new("err1", None);
2105
2106 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2107
2108 let err2 = StringError::new("err2", Some(err1));
2109 let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2110
2111 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2112 err3
2113 err3 line 2
2114 caused by:
2115 - err2
2116 - err1
2117 ");
2118 }
2119
2120 #[test]
2121 fn display_error_list() {
2122 let err1 = StringError::new("err1", None);
2123
2124 let error_list =
2125 ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2126 .expect(">= 1 error");
2127 insta::assert_snapshot!(format!("{}", error_list), @"err1");
2128 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2129
2130 let err2 = StringError::new("err2", Some(err1));
2131 let err3 = StringError::new("err3", Some(err2));
2132
2133 let error_list =
2134 ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2135 .expect(">= 1 error");
2136 insta::assert_snapshot!(format!("{}", error_list), @"err3");
2137 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2138 err3
2139 caused by:
2140 - err2
2141 - err1
2142 ");
2143
2144 let err4 = StringError::new("err4", None);
2145 let err5 = StringError::new("err5", Some(err4));
2146 let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2147
2148 let error_list = ErrorList::<StringError>::new(
2149 "waiting for the heat death of the universe",
2150 vec![err3, err6],
2151 )
2152 .expect(">= 1 error");
2153
2154 insta::assert_snapshot!(format!("{}", error_list), @r"
2155 2 errors occurred waiting for the heat death of the universe:
2156 * err3
2157 caused by:
2158 - err2
2159 - err1
2160 * err6
2161 err6 line 2
2162 caused by:
2163 - err5
2164 - err4
2165 ");
2166 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2167 2 errors occurred waiting for the heat death of the universe:
2168 * err3
2169 caused by:
2170 - err2
2171 - err1
2172 * err6
2173 err6 line 2
2174 caused by:
2175 - err5
2176 - err4
2177 ");
2178 }
2179
2180 #[derive(Clone, Debug, Error)]
2181 struct StringError {
2182 message: String,
2183 #[source]
2184 source: Option<Box<StringError>>,
2185 }
2186
2187 impl StringError {
2188 fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2189 Self {
2190 message: message.into(),
2191 source: source.map(Box::new),
2192 }
2193 }
2194 }
2195
2196 impl fmt::Display for StringError {
2197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2198 write!(f, "{}", self.message)
2199 }
2200 }
2201}