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(Debug, Error)]
713#[non_exhaustive]
714pub enum UserConfigError {
715 #[error("failed to read user config at {path}")]
717 Read {
718 path: Utf8PathBuf,
720 #[source]
722 error: std::io::Error,
723 },
724
725 #[error("failed to parse user config at {path}")]
727 Parse {
728 path: Utf8PathBuf,
730 #[source]
732 error: toml::de::Error,
733 },
734
735 #[error("user config path contains non-UTF-8 characters")]
737 NonUtf8Path {
738 #[source]
740 error: FromPathBufError,
741 },
742}
743
744#[derive(Clone, Debug, Error)]
746#[error("unrecognized value for max-fail: {reason}")]
747pub struct MaxFailParseError {
748 pub reason: String,
750}
751
752impl MaxFailParseError {
753 pub(crate) fn new(reason: impl Into<String>) -> Self {
754 Self {
755 reason: reason.into(),
756 }
757 }
758}
759
760#[derive(Clone, Debug, Error)]
762#[error(
763 "unrecognized value for stress-count: {input}\n\
764 (hint: expected either a positive integer or \"infinite\")"
765)]
766pub struct StressCountParseError {
767 pub input: String,
769}
770
771impl StressCountParseError {
772 pub(crate) fn new(input: impl Into<String>) -> Self {
773 Self {
774 input: input.into(),
775 }
776 }
777}
778
779#[derive(Clone, Debug, Error)]
781#[non_exhaustive]
782pub enum DebuggerCommandParseError {
783 #[error(transparent)]
785 ShellWordsParse(shell_words::ParseError),
786
787 #[error("debugger command cannot be empty")]
789 EmptyCommand,
790}
791
792#[derive(Clone, Debug, Error)]
794#[non_exhaustive]
795pub enum TracerCommandParseError {
796 #[error(transparent)]
798 ShellWordsParse(shell_words::ParseError),
799
800 #[error("tracer command cannot be empty")]
802 EmptyCommand,
803}
804
805#[derive(Clone, Debug, Error)]
807#[error(
808 "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
809)]
810pub struct TestThreadsParseError {
811 pub input: String,
813}
814
815impl TestThreadsParseError {
816 pub(crate) fn new(input: impl Into<String>) -> Self {
817 Self {
818 input: input.into(),
819 }
820 }
821}
822
823#[derive(Clone, Debug, Error)]
826pub struct PartitionerBuilderParseError {
827 expected_format: Option<&'static str>,
828 message: Cow<'static, str>,
829}
830
831impl PartitionerBuilderParseError {
832 pub(crate) fn new(
833 expected_format: Option<&'static str>,
834 message: impl Into<Cow<'static, str>>,
835 ) -> Self {
836 Self {
837 expected_format,
838 message: message.into(),
839 }
840 }
841}
842
843impl fmt::Display for PartitionerBuilderParseError {
844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
845 match self.expected_format {
846 Some(format) => {
847 write!(
848 f,
849 "partition must be in the format \"{}\":\n{}",
850 format, self.message
851 )
852 }
853 None => write!(f, "{}", self.message),
854 }
855 }
856}
857
858#[derive(Clone, Debug, Error)]
861pub enum TestFilterBuilderError {
862 #[error("error constructing test filters")]
864 Construct {
865 #[from]
867 error: aho_corasick::BuildError,
868 },
869}
870
871#[derive(Debug, Error)]
873pub enum PathMapperConstructError {
874 #[error("{kind} `{input}` failed to canonicalize")]
876 Canonicalization {
877 kind: PathMapperConstructKind,
879
880 input: Utf8PathBuf,
882
883 #[source]
885 err: std::io::Error,
886 },
887 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
889 NonUtf8Path {
890 kind: PathMapperConstructKind,
892
893 input: Utf8PathBuf,
895
896 #[source]
898 err: FromPathBufError,
899 },
900 #[error("{kind} `{canonicalized_path}` is not a directory")]
902 NotADirectory {
903 kind: PathMapperConstructKind,
905
906 input: Utf8PathBuf,
908
909 canonicalized_path: Utf8PathBuf,
911 },
912}
913
914impl PathMapperConstructError {
915 pub fn kind(&self) -> PathMapperConstructKind {
917 match self {
918 Self::Canonicalization { kind, .. }
919 | Self::NonUtf8Path { kind, .. }
920 | Self::NotADirectory { kind, .. } => *kind,
921 }
922 }
923
924 pub fn input(&self) -> &Utf8Path {
926 match self {
927 Self::Canonicalization { input, .. }
928 | Self::NonUtf8Path { input, .. }
929 | Self::NotADirectory { input, .. } => input,
930 }
931 }
932}
933
934#[derive(Copy, Clone, Debug, PartialEq, Eq)]
939pub enum PathMapperConstructKind {
940 WorkspaceRoot,
942
943 TargetDir,
945}
946
947impl fmt::Display for PathMapperConstructKind {
948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
949 match self {
950 Self::WorkspaceRoot => write!(f, "remapped workspace root"),
951 Self::TargetDir => write!(f, "remapped target directory"),
952 }
953 }
954}
955
956#[derive(Debug, Error)]
958pub enum RustBuildMetaParseError {
959 #[error("error deserializing platform from build metadata")]
961 PlatformDeserializeError(#[from] target_spec::Error),
962
963 #[error("the host platform could not be determined")]
965 DetectBuildTargetError(#[source] target_spec::Error),
966
967 #[error("unsupported features in the build metadata: {message}")]
969 Unsupported {
970 message: String,
972 },
973}
974
975#[derive(Clone, Debug, thiserror::Error)]
978#[error("invalid format version: {input}")]
979pub struct FormatVersionError {
980 pub input: String,
982 #[source]
984 pub error: FormatVersionErrorInner,
985}
986
987#[derive(Clone, Debug, thiserror::Error)]
989pub enum FormatVersionErrorInner {
990 #[error("expected format version in form of `{expected}`")]
992 InvalidFormat {
993 expected: &'static str,
995 },
996 #[error("version component `{which}` could not be parsed as an integer")]
998 InvalidInteger {
999 which: &'static str,
1001 #[source]
1003 err: std::num::ParseIntError,
1004 },
1005 #[error("version component `{which}` value {value} is out of range {range:?}")]
1007 InvalidValue {
1008 which: &'static str,
1010 value: u8,
1012 range: std::ops::Range<u8>,
1014 },
1015}
1016
1017#[derive(Debug, Error)]
1020#[non_exhaustive]
1021pub enum FromMessagesError {
1022 #[error("error reading Cargo JSON messages")]
1024 ReadMessages(#[source] std::io::Error),
1025
1026 #[error("error querying package graph")]
1028 PackageGraph(#[source] guppy::Error),
1029
1030 #[error("missing kind for target {binary_name} in package {package_name}")]
1032 MissingTargetKind {
1033 package_name: String,
1035 binary_name: String,
1037 },
1038}
1039
1040#[derive(Debug, Error)]
1042#[non_exhaustive]
1043pub enum CreateTestListError {
1044 #[error(
1046 "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
1047 (hint: ensure project source is available at this location)"
1048 )]
1049 CwdIsNotDir {
1050 binary_id: RustBinaryId,
1052
1053 cwd: Utf8PathBuf,
1055 },
1056
1057 #[error(
1059 "for `{binary_id}`, running command `{}` failed to execute",
1060 shell_words::join(command)
1061 )]
1062 CommandExecFail {
1063 binary_id: RustBinaryId,
1065
1066 command: Vec<String>,
1068
1069 #[source]
1071 error: std::io::Error,
1072 },
1073
1074 #[error(
1076 "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1077 shell_words::join(command),
1078 display_exited_with(*exit_status),
1079 String::from_utf8_lossy(stdout),
1080 String::from_utf8_lossy(stderr),
1081 )]
1082 CommandFail {
1083 binary_id: RustBinaryId,
1085
1086 command: Vec<String>,
1088
1089 exit_status: ExitStatus,
1091
1092 stdout: Vec<u8>,
1094
1095 stderr: Vec<u8>,
1097 },
1098
1099 #[error(
1101 "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1102 shell_words::join(command),
1103 String::from_utf8_lossy(stdout),
1104 String::from_utf8_lossy(stderr)
1105 )]
1106 CommandNonUtf8 {
1107 binary_id: RustBinaryId,
1109
1110 command: Vec<String>,
1112
1113 stdout: Vec<u8>,
1115
1116 stderr: Vec<u8>,
1118 },
1119
1120 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1122 ParseLine {
1123 binary_id: RustBinaryId,
1125
1126 message: Cow<'static, str>,
1128
1129 full_output: String,
1131 },
1132
1133 #[error(
1135 "error joining dynamic library paths for {}: [{}]",
1136 dylib_path_envvar(),
1137 itertools::join(.new_paths, ", ")
1138 )]
1139 DylibJoinPaths {
1140 new_paths: Vec<Utf8PathBuf>,
1142
1143 #[source]
1145 error: JoinPathsError,
1146 },
1147
1148 #[error("error creating Tokio runtime")]
1150 TokioRuntimeCreate(#[source] std::io::Error),
1151}
1152
1153impl CreateTestListError {
1154 pub(crate) fn parse_line(
1155 binary_id: RustBinaryId,
1156 message: impl Into<Cow<'static, str>>,
1157 full_output: impl Into<String>,
1158 ) -> Self {
1159 Self::ParseLine {
1160 binary_id,
1161 message: message.into(),
1162 full_output: full_output.into(),
1163 }
1164 }
1165
1166 pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1167 Self::DylibJoinPaths { new_paths, error }
1168 }
1169}
1170
1171#[derive(Debug, Error)]
1173#[non_exhaustive]
1174pub enum WriteTestListError {
1175 #[error("error writing to output")]
1177 Io(#[source] std::io::Error),
1178
1179 #[error("error serializing to JSON")]
1181 Json(#[source] serde_json::Error),
1182}
1183
1184#[derive(Debug, Error)]
1188pub enum ConfigureHandleInheritanceError {
1189 #[cfg(windows)]
1191 #[error("error configuring handle inheritance")]
1192 WindowsError(#[from] std::io::Error),
1193}
1194
1195#[derive(Debug, Error)]
1197#[non_exhaustive]
1198pub enum TestRunnerBuildError {
1199 #[error("error creating Tokio runtime")]
1201 TokioRuntimeCreate(#[source] std::io::Error),
1202
1203 #[error("error setting up signals")]
1205 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1206}
1207
1208#[derive(Debug, Error)]
1210pub struct TestRunnerExecuteErrors<E> {
1211 pub report_error: Option<E>,
1213
1214 pub join_errors: Vec<tokio::task::JoinError>,
1217}
1218
1219impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 if let Some(report_error) = &self.report_error {
1222 write!(f, "error reporting results: {report_error}")?;
1223 }
1224
1225 if !self.join_errors.is_empty() {
1226 if self.report_error.is_some() {
1227 write!(f, "; ")?;
1228 }
1229
1230 write!(f, "errors joining tasks: ")?;
1231
1232 for (i, join_error) in self.join_errors.iter().enumerate() {
1233 if i > 0 {
1234 write!(f, ", ")?;
1235 }
1236
1237 write!(f, "{join_error}")?;
1238 }
1239 }
1240
1241 Ok(())
1242 }
1243}
1244
1245#[derive(Debug, Error)]
1249#[error(
1250 "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1251 supported_extensions()
1252)]
1253pub struct UnknownArchiveFormat {
1254 pub file_name: String,
1256}
1257
1258fn supported_extensions() -> String {
1259 ArchiveFormat::SUPPORTED_FORMATS
1260 .iter()
1261 .map(|(extension, _)| *extension)
1262 .join(", ")
1263}
1264
1265#[derive(Debug, Error)]
1267#[non_exhaustive]
1268pub enum ArchiveCreateError {
1269 #[error("error creating binary list")]
1271 CreateBinaryList(#[source] WriteTestListError),
1272
1273 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1275 MissingExtraPath {
1276 path: Utf8PathBuf,
1278
1279 redactor: Redactor,
1284 },
1285
1286 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1288 InputFileRead {
1289 step: ArchiveStep,
1291
1292 path: Utf8PathBuf,
1294
1295 is_dir: Option<bool>,
1297
1298 #[source]
1300 error: std::io::Error,
1301 },
1302
1303 #[error("error reading directory entry from `{path}")]
1305 DirEntryRead {
1306 path: Utf8PathBuf,
1308
1309 #[source]
1311 error: std::io::Error,
1312 },
1313
1314 #[error("error writing to archive")]
1316 OutputArchiveIo(#[source] std::io::Error),
1317
1318 #[error("error reporting archive status")]
1320 ReporterIo(#[source] std::io::Error),
1321}
1322
1323fn kind_str(is_dir: Option<bool>) -> &'static str {
1324 match is_dir {
1325 Some(true) => "directory",
1326 Some(false) => "file",
1327 None => "path",
1328 }
1329}
1330
1331#[derive(Debug, Error)]
1333pub enum MetadataMaterializeError {
1334 #[error("I/O error reading metadata file `{path}`")]
1336 Read {
1337 path: Utf8PathBuf,
1339
1340 #[source]
1342 error: std::io::Error,
1343 },
1344
1345 #[error("error deserializing metadata file `{path}`")]
1347 Deserialize {
1348 path: Utf8PathBuf,
1350
1351 #[source]
1353 error: serde_json::Error,
1354 },
1355
1356 #[error("error parsing Rust build metadata from `{path}`")]
1358 RustBuildMeta {
1359 path: Utf8PathBuf,
1361
1362 #[source]
1364 error: RustBuildMetaParseError,
1365 },
1366
1367 #[error("error building package graph from `{path}`")]
1369 PackageGraphConstruct {
1370 path: Utf8PathBuf,
1372
1373 #[source]
1375 error: guppy::Error,
1376 },
1377}
1378
1379#[derive(Debug, Error)]
1383#[non_exhaustive]
1384pub enum ArchiveReadError {
1385 #[error("I/O error reading archive")]
1387 Io(#[source] std::io::Error),
1388
1389 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1391 NonUtf8Path(Vec<u8>),
1392
1393 #[error("path in archive `{0}` doesn't start with `target/`")]
1395 NoTargetPrefix(Utf8PathBuf),
1396
1397 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1399 InvalidComponent {
1400 path: Utf8PathBuf,
1402
1403 component: String,
1405 },
1406
1407 #[error("corrupted archive: checksum read error for path `{path}`")]
1409 ChecksumRead {
1410 path: Utf8PathBuf,
1412
1413 #[source]
1415 error: std::io::Error,
1416 },
1417
1418 #[error("corrupted archive: invalid checksum for path `{path}`")]
1420 InvalidChecksum {
1421 path: Utf8PathBuf,
1423
1424 expected: u32,
1426
1427 actual: u32,
1429 },
1430
1431 #[error("metadata file `{0}` not found in archive")]
1433 MetadataFileNotFound(&'static Utf8Path),
1434
1435 #[error("error deserializing metadata file `{path}` in archive")]
1437 MetadataDeserializeError {
1438 path: &'static Utf8Path,
1440
1441 #[source]
1443 error: serde_json::Error,
1444 },
1445
1446 #[error("error building package graph from `{path}` in archive")]
1448 PackageGraphConstructError {
1449 path: &'static Utf8Path,
1451
1452 #[source]
1454 error: guppy::Error,
1455 },
1456}
1457
1458#[derive(Debug, Error)]
1462#[non_exhaustive]
1463pub enum ArchiveExtractError {
1464 #[error("error creating temporary directory")]
1466 TempDirCreate(#[source] std::io::Error),
1467
1468 #[error("error canonicalizing destination directory `{dir}`")]
1470 DestDirCanonicalization {
1471 dir: Utf8PathBuf,
1473
1474 #[source]
1476 error: std::io::Error,
1477 },
1478
1479 #[error("destination `{0}` already exists")]
1481 DestinationExists(Utf8PathBuf),
1482
1483 #[error("error reading archive")]
1485 Read(#[source] ArchiveReadError),
1486
1487 #[error("error deserializing Rust build metadata")]
1489 RustBuildMeta(#[from] RustBuildMetaParseError),
1490
1491 #[error("error writing file `{path}` to disk")]
1493 WriteFile {
1494 path: Utf8PathBuf,
1496
1497 #[source]
1499 error: std::io::Error,
1500 },
1501
1502 #[error("error reporting extract status")]
1504 ReporterIo(std::io::Error),
1505}
1506
1507#[derive(Debug, Error)]
1509#[non_exhaustive]
1510pub enum WriteEventError {
1511 #[error("error writing to output")]
1513 Io(#[source] std::io::Error),
1514
1515 #[error("error operating on path {file}")]
1517 Fs {
1518 file: Utf8PathBuf,
1520
1521 #[source]
1523 error: std::io::Error,
1524 },
1525
1526 #[error("error writing JUnit output to {file}")]
1528 Junit {
1529 file: Utf8PathBuf,
1531
1532 #[source]
1534 error: quick_junit::SerializeError,
1535 },
1536}
1537
1538#[derive(Debug, Error)]
1541#[non_exhaustive]
1542pub enum CargoConfigError {
1543 #[error("failed to retrieve current directory")]
1545 GetCurrentDir(#[source] std::io::Error),
1546
1547 #[error("current directory is invalid UTF-8")]
1549 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1550
1551 #[error("failed to parse --config argument `{config_str}` as TOML")]
1553 CliConfigParseError {
1554 config_str: String,
1556
1557 #[source]
1559 error: toml_edit::TomlError,
1560 },
1561
1562 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1564 CliConfigDeError {
1565 config_str: String,
1567
1568 #[source]
1570 error: toml_edit::de::Error,
1571 },
1572
1573 #[error(
1575 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1576 )]
1577 InvalidCliConfig {
1578 config_str: String,
1580
1581 #[source]
1583 reason: InvalidCargoCliConfigReason,
1584 },
1585
1586 #[error("non-UTF-8 path encountered")]
1588 NonUtf8Path(#[source] FromPathBufError),
1589
1590 #[error("failed to retrieve the Cargo home directory")]
1592 GetCargoHome(#[source] std::io::Error),
1593
1594 #[error("failed to canonicalize path `{path}")]
1596 FailedPathCanonicalization {
1597 path: Utf8PathBuf,
1599
1600 #[source]
1602 error: std::io::Error,
1603 },
1604
1605 #[error("failed to read config at `{path}`")]
1607 ConfigReadError {
1608 path: Utf8PathBuf,
1610
1611 #[source]
1613 error: std::io::Error,
1614 },
1615
1616 #[error(transparent)]
1618 ConfigParseError(#[from] Box<CargoConfigParseError>),
1619}
1620
1621#[derive(Debug, Error)]
1625#[error("failed to parse config at `{path}`")]
1626pub struct CargoConfigParseError {
1627 pub path: Utf8PathBuf,
1629
1630 #[source]
1632 pub error: toml::de::Error,
1633}
1634
1635#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1639#[non_exhaustive]
1640pub enum InvalidCargoCliConfigReason {
1641 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1643 NotDottedKv,
1644
1645 #[error("includes non-whitespace decoration")]
1647 IncludesNonWhitespaceDecoration,
1648
1649 #[error("sets a value to an inline table, which is not accepted")]
1651 SetsValueToInlineTable,
1652
1653 #[error("sets a value to an array of tables, which is not accepted")]
1655 SetsValueToArrayOfTables,
1656
1657 #[error("doesn't provide a value")]
1659 DoesntProvideValue,
1660}
1661
1662#[derive(Debug, Error)]
1664pub enum HostPlatformDetectError {
1665 #[error(
1668 "error spawning `rustc -vV`, and detecting the build \
1669 target failed as well\n\
1670 - rustc spawn error: {}\n\
1671 - build target error: {}\n",
1672 DisplayErrorChain::new_with_initial_indent(" ", error),
1673 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1674 )]
1675 RustcVvSpawnError {
1676 error: std::io::Error,
1678
1679 build_target_error: Box<target_spec::Error>,
1681 },
1682
1683 #[error(
1686 "`rustc -vV` failed with {}, and detecting the \
1687 build target failed as well\n\
1688 - `rustc -vV` stdout:\n{}\n\
1689 - `rustc -vV` stderr:\n{}\n\
1690 - build target error:\n{}\n",
1691 status,
1692 DisplayIndented { item: String::from_utf8_lossy(stdout), indent: " " },
1693 DisplayIndented { item: String::from_utf8_lossy(stderr), indent: " " },
1694 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1695 )]
1696 RustcVvFailed {
1697 status: ExitStatus,
1699
1700 stdout: Vec<u8>,
1702
1703 stderr: Vec<u8>,
1705
1706 build_target_error: Box<target_spec::Error>,
1708 },
1709
1710 #[error(
1713 "parsing `rustc -vV` output failed, and detecting the build target \
1714 failed as well\n\
1715 - host platform error:\n{}\n\
1716 - build target error:\n{}\n",
1717 DisplayErrorChain::new_with_initial_indent(" ", host_platform_error),
1718 DisplayErrorChain::new_with_initial_indent(" ", build_target_error)
1719 )]
1720 HostPlatformParseError {
1721 host_platform_error: Box<target_spec::Error>,
1723
1724 build_target_error: Box<target_spec::Error>,
1726 },
1727
1728 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1731 BuildTargetError {
1732 #[source]
1734 build_target_error: Box<target_spec::Error>,
1735 },
1736}
1737
1738#[derive(Debug, Error)]
1740pub enum TargetTripleError {
1741 #[error(
1743 "environment variable '{}' contained non-UTF-8 data",
1744 TargetTriple::CARGO_BUILD_TARGET_ENV
1745 )]
1746 InvalidEnvironmentVar,
1747
1748 #[error("error deserializing target triple from {source}")]
1750 TargetSpecError {
1751 source: TargetTripleSource,
1753
1754 #[source]
1756 error: target_spec::Error,
1757 },
1758
1759 #[error("target path `{path}` is not a valid file")]
1761 TargetPathReadError {
1762 source: TargetTripleSource,
1764
1765 path: Utf8PathBuf,
1767
1768 #[source]
1770 error: std::io::Error,
1771 },
1772
1773 #[error(
1775 "for custom platform obtained from {source}, \
1776 failed to create temporary directory for custom platform"
1777 )]
1778 CustomPlatformTempDirError {
1779 source: TargetTripleSource,
1781
1782 #[source]
1784 error: std::io::Error,
1785 },
1786
1787 #[error(
1789 "for custom platform obtained from {source}, \
1790 failed to write JSON to temporary path `{path}`"
1791 )]
1792 CustomPlatformWriteError {
1793 source: TargetTripleSource,
1795
1796 path: Utf8PathBuf,
1798
1799 #[source]
1801 error: std::io::Error,
1802 },
1803
1804 #[error(
1806 "for custom platform obtained from {source}, \
1807 failed to close temporary directory `{dir_path}`"
1808 )]
1809 CustomPlatformCloseError {
1810 source: TargetTripleSource,
1812
1813 dir_path: Utf8PathBuf,
1815
1816 #[source]
1818 error: std::io::Error,
1819 },
1820}
1821
1822impl TargetTripleError {
1823 pub fn source_report(&self) -> Option<miette::Report> {
1828 match self {
1829 Self::TargetSpecError { error, .. } => {
1830 Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1831 }
1832 TargetTripleError::InvalidEnvironmentVar
1834 | TargetTripleError::TargetPathReadError { .. }
1835 | TargetTripleError::CustomPlatformTempDirError { .. }
1836 | TargetTripleError::CustomPlatformWriteError { .. }
1837 | TargetTripleError::CustomPlatformCloseError { .. } => None,
1838 }
1839 }
1840}
1841
1842#[derive(Debug, Error)]
1844pub enum TargetRunnerError {
1845 #[error("environment variable '{0}' contained non-UTF-8 data")]
1847 InvalidEnvironmentVar(String),
1848
1849 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1852 BinaryNotSpecified {
1853 key: PlatformRunnerSource,
1855
1856 value: String,
1858 },
1859}
1860
1861#[derive(Debug, Error)]
1863#[error("error setting up signal handler")]
1864pub struct SignalHandlerSetupError(#[from] std::io::Error);
1865
1866#[derive(Debug, Error)]
1868pub enum ShowTestGroupsError {
1869 #[error(
1871 "unknown test groups specified: {}\n(known groups: {})",
1872 unknown_groups.iter().join(", "),
1873 known_groups.iter().join(", "),
1874 )]
1875 UnknownGroups {
1876 unknown_groups: BTreeSet<TestGroup>,
1878
1879 known_groups: BTreeSet<TestGroup>,
1881 },
1882}
1883
1884#[derive(Debug, Error, PartialEq, Eq, Hash)]
1886pub enum InheritsError {
1887 #[error("the {} profile should not inherit from other profiles", .0)]
1889 DefaultProfileInheritance(String),
1890 #[error("profile {} inherits from an unknown profile {}", .0, .1)]
1892 UnknownInheritance(String, String),
1893 #[error("a self referential inheritance is detected from profile: {}", .0)]
1895 SelfReferentialInheritance(String),
1896 #[error("inheritance cycle detected in profile configuration from: {}", .0.iter().map(|scc| {
1898 format!("[{}]", scc.iter().join(", "))
1899 }).join(", "))]
1900 InheritanceCycle(Vec<Vec<String>>),
1901}
1902
1903#[cfg(feature = "self-update")]
1904mod self_update_errors {
1905 use super::*;
1906 use mukti_metadata::ReleaseStatus;
1907 use semver::{Version, VersionReq};
1908
1909 #[cfg(feature = "self-update")]
1913 #[derive(Debug, Error)]
1914 #[non_exhaustive]
1915 pub enum UpdateError {
1916 #[error("failed to read release metadata from `{path}`")]
1918 ReadLocalMetadata {
1919 path: Utf8PathBuf,
1921
1922 #[source]
1924 error: std::io::Error,
1925 },
1926
1927 #[error("self-update failed")]
1929 SelfUpdate(#[source] self_update::errors::Error),
1930
1931 #[error("deserializing release metadata failed")]
1933 ReleaseMetadataDe(#[source] serde_json::Error),
1934
1935 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1937 VersionNotFound {
1938 version: Version,
1940
1941 known: Vec<(Version, ReleaseStatus)>,
1943 },
1944
1945 #[error("no version found matching requirement `{req}`")]
1947 NoMatchForVersionReq {
1948 req: VersionReq,
1950 },
1951
1952 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1954 MuktiProjectNotFound {
1955 not_found: String,
1957
1958 known: Vec<String>,
1960 },
1961
1962 #[error(
1964 "for version {version}, no release information found for target `{triple}` \
1965 (known targets: {})",
1966 known_triples.iter().join(", ")
1967 )]
1968 NoTargetData {
1969 version: Version,
1971
1972 triple: String,
1974
1975 known_triples: BTreeSet<String>,
1977 },
1978
1979 #[error("the current executable's path could not be determined")]
1981 CurrentExe(#[source] std::io::Error),
1982
1983 #[error("temporary directory could not be created at `{location}`")]
1985 TempDirCreate {
1986 location: Utf8PathBuf,
1988
1989 #[source]
1991 error: std::io::Error,
1992 },
1993
1994 #[error("temporary archive could not be created at `{archive_path}`")]
1996 TempArchiveCreate {
1997 archive_path: Utf8PathBuf,
1999
2000 #[source]
2002 error: std::io::Error,
2003 },
2004
2005 #[error("error writing to temporary archive at `{archive_path}`")]
2007 TempArchiveWrite {
2008 archive_path: Utf8PathBuf,
2010
2011 #[source]
2013 error: std::io::Error,
2014 },
2015
2016 #[error("error reading from temporary archive at `{archive_path}`")]
2018 TempArchiveRead {
2019 archive_path: Utf8PathBuf,
2021
2022 #[source]
2024 error: std::io::Error,
2025 },
2026
2027 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
2029 ChecksumMismatch {
2030 expected: String,
2032
2033 actual: String,
2035 },
2036
2037 #[error("error renaming `{source}` to `{dest}`")]
2039 FsRename {
2040 source: Utf8PathBuf,
2042
2043 dest: Utf8PathBuf,
2045
2046 #[source]
2048 error: std::io::Error,
2049 },
2050
2051 #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
2053 SelfSetup(#[source] std::io::Error),
2054 }
2055
2056 fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
2057 use std::fmt::Write;
2058
2059 const DISPLAY_COUNT: usize = 4;
2061
2062 let display_versions: Vec<_> = versions
2063 .iter()
2064 .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
2065 .map(|(v, _)| v.to_string())
2066 .take(DISPLAY_COUNT)
2067 .collect();
2068 let mut display_str = display_versions.join(", ");
2069 if versions.len() > display_versions.len() {
2070 write!(
2071 display_str,
2072 " and {} others",
2073 versions.len() - display_versions.len()
2074 )
2075 .unwrap();
2076 }
2077
2078 display_str
2079 }
2080
2081 #[cfg(feature = "self-update")]
2082 #[derive(Debug, Error)]
2084 pub enum UpdateVersionParseError {
2085 #[error("version string is empty")]
2087 EmptyString,
2088
2089 #[error(
2091 "`{input}` is not a valid semver requirement\n\
2092 (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
2093 )]
2094 InvalidVersionReq {
2095 input: String,
2097
2098 #[source]
2100 error: semver::Error,
2101 },
2102
2103 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2105 InvalidVersion {
2106 input: String,
2108
2109 #[source]
2111 error: semver::Error,
2112 },
2113 }
2114
2115 fn extra_semver_output(input: &str) -> String {
2116 if input.parse::<VersionReq>().is_ok() {
2119 format!(
2120 "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2121 )
2122 } else {
2123 "".to_owned()
2124 }
2125 }
2126}
2127
2128#[cfg(feature = "self-update")]
2129pub use self_update_errors::*;
2130
2131#[cfg(test)]
2132mod tests {
2133 use super::*;
2134
2135 #[test]
2136 fn display_error_chain() {
2137 let err1 = StringError::new("err1", None);
2138
2139 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2140
2141 let err2 = StringError::new("err2", Some(err1));
2142 let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2143
2144 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2145 err3
2146 err3 line 2
2147 caused by:
2148 - err2
2149 - err1
2150 ");
2151 }
2152
2153 #[test]
2154 fn display_error_list() {
2155 let err1 = StringError::new("err1", None);
2156
2157 let error_list =
2158 ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2159 .expect(">= 1 error");
2160 insta::assert_snapshot!(format!("{}", error_list), @"err1");
2161 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2162
2163 let err2 = StringError::new("err2", Some(err1));
2164 let err3 = StringError::new("err3", Some(err2));
2165
2166 let error_list =
2167 ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2168 .expect(">= 1 error");
2169 insta::assert_snapshot!(format!("{}", error_list), @"err3");
2170 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2171 err3
2172 caused by:
2173 - err2
2174 - err1
2175 ");
2176
2177 let err4 = StringError::new("err4", None);
2178 let err5 = StringError::new("err5", Some(err4));
2179 let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2180
2181 let error_list = ErrorList::<StringError>::new(
2182 "waiting for the heat death of the universe",
2183 vec![err3, err6],
2184 )
2185 .expect(">= 1 error");
2186
2187 insta::assert_snapshot!(format!("{}", error_list), @r"
2188 2 errors occurred waiting for the heat death of the universe:
2189 * err3
2190 caused by:
2191 - err2
2192 - err1
2193 * err6
2194 err6 line 2
2195 caused by:
2196 - err5
2197 - err4
2198 ");
2199 insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2200 2 errors occurred waiting for the heat death of the universe:
2201 * err3
2202 caused by:
2203 - err2
2204 - err1
2205 * err6
2206 err6 line 2
2207 caused by:
2208 - err5
2209 - err4
2210 ");
2211 }
2212
2213 #[derive(Clone, Debug, Error)]
2214 struct StringError {
2215 message: String,
2216 #[source]
2217 source: Option<Box<StringError>>,
2218 }
2219
2220 impl StringError {
2221 fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2222 Self {
2223 message: message.into(),
2224 source: source.map(Box::new),
2225 }
2226 }
2227 }
2228
2229 impl fmt::Display for StringError {
2230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2231 write!(f, "{}", self.message)
2232 }
2233 }
2234}