nextest_runner/
errors.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Errors produced by nextest.
5
6use 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/// An error that occurred while parsing the config.
37#[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    /// Returns the config file for this error.
64    pub fn config_file(&self) -> &Utf8Path {
65        &self.config_file
66    }
67
68    /// Returns the tool name associated with this error.
69    pub fn tool(&self) -> Option<&ToolName> {
70        self.tool.as_ref()
71    }
72
73    /// Returns the kind of error this is.
74    pub fn kind(&self) -> &ConfigParseErrorKind {
75        &self.kind
76    }
77}
78
79/// Returns the string ` provided by tool <tool>`, if `tool` is `Some`.
80pub 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/// The kind of error that occurred while parsing a config.
88///
89/// Returned by [`ConfigParseError::kind`].
90#[derive(Debug, Error)]
91#[non_exhaustive]
92pub enum ConfigParseErrorKind {
93    /// An error occurred while building the config.
94    #[error(transparent)]
95    BuildError(Box<ConfigError>),
96    /// An error occurred while parsing the config into a table.
97    #[error(transparent)]
98    TomlParseError(Box<toml::de::Error>),
99    #[error(transparent)]
100    /// An error occurred while deserializing the config.
101    DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
102    /// An error occurred while reading the config file (version only).
103    #[error(transparent)]
104    VersionOnlyReadError(std::io::Error),
105    /// An error occurred while deserializing the config (version only).
106    #[error(transparent)]
107    VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
108    /// Errors occurred while compiling configuration strings.
109    #[error("error parsing compiled data (destructure this variant for more details)")]
110    CompileErrors(Vec<ConfigCompileError>),
111    /// An invalid set of test groups was defined by the user.
112    #[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    /// An invalid set of test groups was defined by a tool config file.
115    #[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    /// Some test groups were unknown.
119    #[error("unknown test groups specified by config (destructure this variant for more details)")]
120    UnknownTestGroups {
121        /// The list of errors that occurred.
122        errors: Vec<UnknownTestGroupError>,
123
124        /// Known groups up to this point.
125        known_groups: BTreeSet<TestGroup>,
126    },
127    /// Both `[script.*]` and `[scripts.*]` were defined.
128    #[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    /// An invalid set of config scripts was defined by the user.
134    #[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    /// An invalid set of config scripts was defined by a tool config file.
137    #[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    /// The same config script name was used across config script types.
141    #[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    /// Errors occurred while parsing `[[profile.<profile-name>.scripts]]`.
147    #[error(
148        "errors in profile-specific config scripts (destructure this variant for more details)"
149    )]
150    ProfileScriptErrors {
151        /// The errors that occurred.
152        errors: Box<ProfileScriptErrors>,
153
154        /// Known scripts up to this point.
155        known_scripts: BTreeSet<ScriptId>,
156    },
157    /// An unknown experimental feature or features were defined.
158    #[error("unknown experimental features defined (destructure this variant for more details)")]
159    UnknownExperimentalFeatures {
160        /// The set of unknown features.
161        unknown: BTreeSet<String>,
162
163        /// The set of known features.
164        known: BTreeSet<ConfigExperimental>,
165    },
166    /// A tool specified an experimental feature.
167    ///
168    /// Tools are not allowed to specify experimental features.
169    #[error(
170        "tool config file specifies experimental features `{}` \
171         -- only repository config files can do so",
172        .features.iter().join(", "),
173    )]
174    ExperimentalFeaturesInToolConfig {
175        /// The name of the experimental feature.
176        features: BTreeSet<String>,
177    },
178    /// Experimental features were used but not enabled.
179    #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
180    ExperimentalFeaturesNotEnabled {
181        /// The features that were not enabled.
182        missing_features: BTreeSet<ConfigExperimental>,
183    },
184    /// An inheritance cycle was detected in the profile configuration.
185    #[error("inheritance error(s) detected: {}", .0.iter().join(", "))]
186    InheritanceErrors(Vec<InheritsError>),
187}
188
189/// An error that occurred while compiling overrides or scripts specified in
190/// configuration.
191#[derive(Debug)]
192#[non_exhaustive]
193pub struct ConfigCompileError {
194    /// The name of the profile under which the data was found.
195    pub profile_name: String,
196
197    /// The section within the profile where the error occurred.
198    pub section: ConfigCompileSection,
199
200    /// The kind of error that occurred.
201    pub kind: ConfigCompileErrorKind,
202}
203
204/// For a [`ConfigCompileError`], the section within the profile where the error
205/// occurred.
206#[derive(Debug)]
207pub enum ConfigCompileSection {
208    /// `profile.<profile-name>.default-filter`.
209    DefaultFilter,
210
211    /// `[[profile.<profile-name>.overrides]]` at the corresponding index.
212    Override(usize),
213
214    /// `[[profile.<profile-name>.scripts]]` at the corresponding index.
215    Script(usize),
216}
217
218/// The kind of error that occurred while parsing config overrides.
219#[derive(Debug)]
220#[non_exhaustive]
221pub enum ConfigCompileErrorKind {
222    /// Neither `platform` nor `filter` were specified.
223    ConstraintsNotSpecified {
224        /// Whether `default-filter` was specified.
225        ///
226        /// If default-filter is specified, then specifying `filter` is not
227        /// allowed -- so we show a different message in that case.
228        default_filter_specified: bool,
229    },
230
231    /// Both `filter` and `default-filter` were specified.
232    ///
233    /// It only makes sense to specify one of the two.
234    FilterAndDefaultFilterSpecified,
235
236    /// One or more errors occured while parsing expressions.
237    Parse {
238        /// A potential error that occurred while parsing the host platform expression.
239        host_parse_error: Option<target_spec::Error>,
240
241        /// A potential error that occurred while parsing the target platform expression.
242        target_parse_error: Option<target_spec::Error>,
243
244        /// Filterset or default filter parse errors.
245        filter_parse_errors: Vec<FiltersetParseErrors>,
246    },
247}
248
249impl ConfigCompileErrorKind {
250    /// Returns [`miette::Report`]s for each error recorded by self.
251    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/// A test priority specified was out of range.
299#[derive(Clone, Debug, Error)]
300#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
301pub struct TestPriorityOutOfRange {
302    /// The priority that was out of range.
303    pub priority: i8,
304}
305
306/// An execution error occurred while attempting to start a test.
307#[derive(Clone, Debug, Error)]
308pub enum ChildStartError {
309    /// An error occurred while creating a temporary path for a setup script.
310    #[error("error creating temporary path for setup script")]
311    TempPath(#[source] Arc<std::io::Error>),
312
313    /// An error occurred while spawning the child process.
314    #[error("error spawning child process")]
315    Spawn(#[source] Arc<std::io::Error>),
316}
317
318/// An error that occurred while reading the output of a setup script.
319#[derive(Clone, Debug, Error)]
320pub enum SetupScriptOutputError {
321    /// An error occurred while opening the setup script environment file.
322    #[error("error opening environment file `{path}`")]
323    EnvFileOpen {
324        /// The path to the environment file.
325        path: Utf8PathBuf,
326
327        /// The underlying error.
328        #[source]
329        error: Arc<std::io::Error>,
330    },
331
332    /// An error occurred while reading the setup script environment file.
333    #[error("error reading environment file `{path}`")]
334    EnvFileRead {
335        /// The path to the environment file.
336        path: Utf8PathBuf,
337
338        /// The underlying error.
339        #[source]
340        error: Arc<std::io::Error>,
341    },
342
343    /// An error occurred while parsing the setup script environment file.
344    #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
345    EnvFileParse {
346        /// The path to the environment file.
347        path: Utf8PathBuf,
348        /// The line at issue.
349        line: String,
350    },
351
352    /// An environment variable key was reserved.
353    #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
354    EnvFileReservedKey {
355        /// The environment variable name.
356        key: String,
357    },
358}
359
360/// A list of errors that implements `Error`.
361///
362/// In the future, we'll likely want to replace this with a `miette::Diagnostic`-based error, since
363/// that supports multiple causes via "related".
364#[derive(Clone, Debug)]
365pub struct ErrorList<T> {
366    // A description of what the errors are.
367    description: &'static str,
368    // Invariant: this list is non-empty.
369    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    /// Returns a short summary of the error list.
388    pub(crate) fn short_message(&self) -> String {
389        let string = self.to_string();
390        match string.lines().next() {
391            // Remove a trailing colon if it exists for a better UX.
392            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 a single error occurred, pretend that this is just that.
405        if self.inner.len() == 1 {
406            return write!(f, "{}", self.inner[0]);
407        }
408
409        // Otherwise, list all errors.
410        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            // More than one error occurred, so we can't return a single error here. Instead, we
431            // return `None` and display the chain of causes in `fmt::Display`.
432            None
433        }
434    }
435}
436
437/// A wrapper type to display a chain of errors with internal indentation.
438///
439/// This is similar to the display-error-chain crate, but uses IndentWriter
440/// internally to ensure that subsequent lines are also nested.
441pub(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            // Wrap the existing writer to accumulate indentation.
479            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/// An error was returned while managing a child process or reading its output.
492#[derive(Clone, Debug, Error)]
493pub enum ChildError {
494    /// An error occurred while reading from a child file descriptor.
495    #[error(transparent)]
496    Fd(#[from] ChildFdError),
497
498    /// An error occurred while reading the output of a setup script.
499    #[error(transparent)]
500    SetupScriptOutput(#[from] SetupScriptOutputError),
501}
502
503/// An error was returned while reading from child a file descriptor.
504#[derive(Clone, Debug, Error)]
505pub enum ChildFdError {
506    /// An error occurred while reading standard output.
507    #[error("error reading standard output")]
508    ReadStdout(#[source] Arc<std::io::Error>),
509
510    /// An error occurred while reading standard error.
511    #[error("error reading standard error")]
512    ReadStderr(#[source] Arc<std::io::Error>),
513
514    /// An error occurred while reading a combined stream.
515    #[error("error reading combined stream")]
516    ReadCombined(#[source] Arc<std::io::Error>),
517
518    /// An error occurred while waiting for the child process to exit.
519    #[error("error waiting for child process to exit")]
520    Wait(#[source] Arc<std::io::Error>),
521}
522
523/// An unknown test group was specified in the config.
524#[derive(Clone, Debug, Eq, PartialEq)]
525#[non_exhaustive]
526pub struct UnknownTestGroupError {
527    /// The name of the profile under which the unknown test group was found.
528    pub profile_name: String,
529
530    /// The name of the unknown test group.
531    pub name: TestGroup,
532}
533
534/// While parsing profile-specific config scripts, an unknown script was
535/// encountered.
536#[derive(Clone, Debug, Eq, PartialEq)]
537pub struct ProfileUnknownScriptError {
538    /// The name of the profile under which the errors occurred.
539    pub profile_name: String,
540
541    /// The name of the unknown script.
542    pub name: ScriptId,
543}
544
545/// While parsing profile-specific config scripts, a script of the wrong type
546/// was encountered.
547#[derive(Clone, Debug, Eq, PartialEq)]
548pub struct ProfileWrongConfigScriptTypeError {
549    /// The name of the profile under which the errors occurred.
550    pub profile_name: String,
551
552    /// The name of the config script.
553    pub name: ScriptId,
554
555    /// The script type that the user attempted to use the script as.
556    pub attempted: ProfileScriptType,
557
558    /// The script type that the script actually is.
559    pub actual: ScriptType,
560}
561
562/// While parsing profile-specific config scripts, a list-time-enabled script
563/// used a filter that can only be used at test run time.
564#[derive(Clone, Debug, Eq, PartialEq)]
565pub struct ProfileListScriptUsesRunFiltersError {
566    /// The name of the profile under which the errors occurred.
567    pub profile_name: String,
568
569    /// The name of the config script.
570    pub name: ScriptId,
571
572    /// The script type.
573    pub script_type: ProfileScriptType,
574
575    /// The filters that were used.
576    pub filters: BTreeSet<String>,
577}
578
579/// Errors that occurred while parsing `[[profile.*.scripts]]`.
580#[derive(Clone, Debug, Default)]
581pub struct ProfileScriptErrors {
582    /// The list of unknown script errors.
583    pub unknown_scripts: Vec<ProfileUnknownScriptError>,
584
585    /// The list of wrong script type errors.
586    pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
587
588    /// The list of list-time-enabled scripts that used a run-time filter.
589    pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
590}
591
592impl ProfileScriptErrors {
593    /// Returns true if there are no errors recorded.
594    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/// An error which indicates that a profile was requested but not known to nextest.
602#[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/// An identifier is invalid.
624#[derive(Clone, Debug, Error, Eq, PartialEq)]
625pub enum InvalidIdentifier {
626    /// The identifier is empty.
627    #[error("identifier is empty")]
628    Empty,
629
630    /// The identifier is not in the correct Unicode format.
631    #[error("invalid identifier `{0}`")]
632    InvalidXid(SmolStr),
633
634    /// This tool identifier doesn't match the expected pattern.
635    #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
636    ToolIdentifierInvalidFormat(SmolStr),
637
638    /// One of the components of this tool identifier is empty.
639    #[error("tool identifier has empty component: `{0}`")]
640    ToolComponentEmpty(SmolStr),
641
642    /// The tool identifier is not in the correct Unicode format.
643    #[error("invalid tool identifier `{0}`")]
644    ToolIdentifierInvalidXid(SmolStr),
645}
646
647/// A tool name is invalid.
648#[derive(Clone, Debug, Error, Eq, PartialEq)]
649pub enum InvalidToolName {
650    /// The tool name is empty.
651    #[error("tool name is empty")]
652    Empty,
653
654    /// The tool name is not in the correct Unicode format.
655    #[error("invalid tool name `{0}`")]
656    InvalidXid(SmolStr),
657
658    /// The tool name starts with "@tool", which is reserved for tool identifiers.
659    #[error("tool name cannot start with \"@tool\": `{0}`")]
660    StartsWithToolPrefix(SmolStr),
661}
662
663/// The name of a test group is invalid (not a valid identifier).
664#[derive(Clone, Debug, Error)]
665#[error("invalid custom test group name: {0}")]
666pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
667
668/// The name of a configuration script is invalid (not a valid identifier).
669#[derive(Clone, Debug, Error)]
670#[error("invalid configuration script name: {0}")]
671pub struct InvalidConfigScriptName(pub InvalidIdentifier);
672
673/// Error returned while parsing a [`ToolConfigFile`](crate::config::core::ToolConfigFile) value.
674#[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    /// The input was not in the format "tool:path".
680    InvalidFormat {
681        /// The input that failed to parse.
682        input: String,
683    },
684
685    /// The tool name was invalid.
686    #[error("tool-config-file has invalid tool name: {input}")]
687    InvalidToolName {
688        /// The input that failed to parse.
689        input: String,
690
691        /// The error that occurred.
692        #[source]
693        error: InvalidToolName,
694    },
695
696    /// The config file path was empty.
697    #[error("tool-config-file has empty config file path: {input}")]
698    EmptyConfigFile {
699        /// The input that failed to parse.
700        input: String,
701    },
702
703    /// The config file was not an absolute path.
704    #[error("tool-config-file is not an absolute path: {config_file}")]
705    ConfigFileNotAbsolute {
706        /// The file name that wasn't absolute.
707        config_file: Utf8PathBuf,
708    },
709}
710
711/// Errors that can occur while loading user config.
712#[derive(Debug, Error)]
713#[non_exhaustive]
714pub enum UserConfigError {
715    /// Failed to read the user config file.
716    #[error("failed to read user config at {path}")]
717    Read {
718        /// The path to the config file.
719        path: Utf8PathBuf,
720        /// The underlying I/O error.
721        #[source]
722        error: std::io::Error,
723    },
724
725    /// Failed to parse the user config file.
726    #[error("failed to parse user config at {path}")]
727    Parse {
728        /// The path to the config file.
729        path: Utf8PathBuf,
730        /// The underlying TOML parse error.
731        #[source]
732        error: toml::de::Error,
733    },
734
735    /// The user config path contains non-UTF-8 characters.
736    #[error("user config path contains non-UTF-8 characters")]
737    NonUtf8Path {
738        /// The underlying error from path conversion.
739        #[source]
740        error: FromPathBufError,
741    },
742}
743
744/// Error returned while parsing a [`MaxFail`](crate::config::elements::MaxFail) input.
745#[derive(Clone, Debug, Error)]
746#[error("unrecognized value for max-fail: {reason}")]
747pub struct MaxFailParseError {
748    /// The reason parsing failed.
749    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/// Error returned while parsing a [`StressCount`](crate::runner::StressCount) input.
761#[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    /// The input that failed to parse.
768    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/// An error that occurred while parsing a debugger command.
780#[derive(Clone, Debug, Error)]
781#[non_exhaustive]
782pub enum DebuggerCommandParseError {
783    /// The command string could not be parsed as shell words.
784    #[error(transparent)]
785    ShellWordsParse(shell_words::ParseError),
786
787    /// The command was empty.
788    #[error("debugger command cannot be empty")]
789    EmptyCommand,
790}
791
792/// An error that occurred while parsing a tracer command.
793#[derive(Clone, Debug, Error)]
794#[non_exhaustive]
795pub enum TracerCommandParseError {
796    /// The command string could not be parsed as shell words.
797    #[error(transparent)]
798    ShellWordsParse(shell_words::ParseError),
799
800    /// The command was empty.
801    #[error("tracer command cannot be empty")]
802    EmptyCommand,
803}
804
805/// Error returned while parsing a [`TestThreads`](crate::config::elements::TestThreads) value.
806#[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    /// The input that failed to parse.
812    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/// An error that occurs while parsing a
824/// [`PartitionerBuilder`](crate::partition::PartitionerBuilder) input.
825#[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/// An error that occurs while operating on a
859/// [`TestFilterBuilder`](crate::test_filter::TestFilterBuilder).
860#[derive(Clone, Debug, Error)]
861pub enum TestFilterBuilderError {
862    /// An error that occurred while constructing test filters.
863    #[error("error constructing test filters")]
864    Construct {
865        /// The underlying error.
866        #[from]
867        error: aho_corasick::BuildError,
868    },
869}
870
871/// An error occurred in [`PathMapper::new`](crate::reuse_build::PathMapper::new).
872#[derive(Debug, Error)]
873pub enum PathMapperConstructError {
874    /// An error occurred while canonicalizing a directory.
875    #[error("{kind} `{input}` failed to canonicalize")]
876    Canonicalization {
877        /// The directory that failed to be canonicalized.
878        kind: PathMapperConstructKind,
879
880        /// The input provided.
881        input: Utf8PathBuf,
882
883        /// The error that occurred.
884        #[source]
885        err: std::io::Error,
886    },
887    /// The canonicalized path isn't valid UTF-8.
888    #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
889    NonUtf8Path {
890        /// The directory that failed to be canonicalized.
891        kind: PathMapperConstructKind,
892
893        /// The input provided.
894        input: Utf8PathBuf,
895
896        /// The underlying error.
897        #[source]
898        err: FromPathBufError,
899    },
900    /// A provided input is not a directory.
901    #[error("{kind} `{canonicalized_path}` is not a directory")]
902    NotADirectory {
903        /// The directory that failed to be canonicalized.
904        kind: PathMapperConstructKind,
905
906        /// The input provided.
907        input: Utf8PathBuf,
908
909        /// The canonicalized path that wasn't a directory.
910        canonicalized_path: Utf8PathBuf,
911    },
912}
913
914impl PathMapperConstructError {
915    /// The kind of directory.
916    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    /// The input path that failed.
925    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/// The kind of directory that failed to be read in
935/// [`PathMapper::new`](crate::reuse_build::PathMapper::new).
936///
937/// Returned as part of [`PathMapperConstructError`].
938#[derive(Copy, Clone, Debug, PartialEq, Eq)]
939pub enum PathMapperConstructKind {
940    /// The workspace root.
941    WorkspaceRoot,
942
943    /// The target directory.
944    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/// An error that occurs while parsing Rust build metadata from a summary.
957#[derive(Debug, Error)]
958pub enum RustBuildMetaParseError {
959    /// An error occurred while deserializing the platform.
960    #[error("error deserializing platform from build metadata")]
961    PlatformDeserializeError(#[from] target_spec::Error),
962
963    /// The host platform could not be determined.
964    #[error("the host platform could not be determined")]
965    DetectBuildTargetError(#[source] target_spec::Error),
966
967    /// The build metadata includes features unsupported.
968    #[error("unsupported features in the build metadata: {message}")]
969    Unsupported {
970        /// The detailed error message.
971        message: String,
972    },
973}
974
975/// Error returned when a user-supplied format version fails to be parsed to a
976/// valid and supported version.
977#[derive(Clone, Debug, thiserror::Error)]
978#[error("invalid format version: {input}")]
979pub struct FormatVersionError {
980    /// The input that failed to parse.
981    pub input: String,
982    /// The underlying error.
983    #[source]
984    pub error: FormatVersionErrorInner,
985}
986
987/// The different errors that can occur when parsing and validating a format version.
988#[derive(Clone, Debug, thiserror::Error)]
989pub enum FormatVersionErrorInner {
990    /// The input did not have a valid syntax.
991    #[error("expected format version in form of `{expected}`")]
992    InvalidFormat {
993        /// The expected pseudo format.
994        expected: &'static str,
995    },
996    /// A decimal integer was expected but could not be parsed.
997    #[error("version component `{which}` could not be parsed as an integer")]
998    InvalidInteger {
999        /// Which component was invalid.
1000        which: &'static str,
1001        /// The parse failure.
1002        #[source]
1003        err: std::num::ParseIntError,
1004    },
1005    /// The version component was not within the expected range.
1006    #[error("version component `{which}` value {value} is out of range {range:?}")]
1007    InvalidValue {
1008        /// The component which was out of range.
1009        which: &'static str,
1010        /// The value that was parsed.
1011        value: u8,
1012        /// The range of valid values for the component.
1013        range: std::ops::Range<u8>,
1014    },
1015}
1016
1017/// An error that occurs in [`BinaryList::from_messages`](crate::list::BinaryList::from_messages) or
1018/// [`RustTestArtifact::from_binary_list`](crate::list::RustTestArtifact::from_binary_list).
1019#[derive(Debug, Error)]
1020#[non_exhaustive]
1021pub enum FromMessagesError {
1022    /// An error occurred while reading Cargo's JSON messages.
1023    #[error("error reading Cargo JSON messages")]
1024    ReadMessages(#[source] std::io::Error),
1025
1026    /// An error occurred while querying the package graph.
1027    #[error("error querying package graph")]
1028    PackageGraph(#[source] guppy::Error),
1029
1030    /// A target in the package graph was missing `kind` information.
1031    #[error("missing kind for target {binary_name} in package {package_name}")]
1032    MissingTargetKind {
1033        /// The name of the malformed package.
1034        package_name: String,
1035        /// The name of the malformed target within the package.
1036        binary_name: String,
1037    },
1038}
1039
1040/// An error that occurs while parsing test list output.
1041#[derive(Debug, Error)]
1042#[non_exhaustive]
1043pub enum CreateTestListError {
1044    /// The proposed cwd for a process is not a directory.
1045    #[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        /// The binary ID for which the current directory wasn't found.
1051        binary_id: RustBinaryId,
1052
1053        /// The current directory that wasn't found.
1054        cwd: Utf8PathBuf,
1055    },
1056
1057    /// Running a command to gather the list of tests failed to execute.
1058    #[error(
1059        "for `{binary_id}`, running command `{}` failed to execute",
1060        shell_words::join(command)
1061    )]
1062    CommandExecFail {
1063        /// The binary ID for which gathering the list of tests failed.
1064        binary_id: RustBinaryId,
1065
1066        /// The command that was run.
1067        command: Vec<String>,
1068
1069        /// The underlying error.
1070        #[source]
1071        error: std::io::Error,
1072    },
1073
1074    /// Running a command to gather the list of tests failed failed with a non-zero exit code.
1075    #[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        /// The binary ID for which gathering the list of tests failed.
1084        binary_id: RustBinaryId,
1085
1086        /// The command that was run.
1087        command: Vec<String>,
1088
1089        /// The exit status with which the command failed.
1090        exit_status: ExitStatus,
1091
1092        /// Standard output for the command.
1093        stdout: Vec<u8>,
1094
1095        /// Standard error for the command.
1096        stderr: Vec<u8>,
1097    },
1098
1099    /// Running a command to gather the list of tests produced a non-UTF-8 standard output.
1100    #[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        /// The binary ID for which gathering the list of tests failed.
1108        binary_id: RustBinaryId,
1109
1110        /// The command that was run.
1111        command: Vec<String>,
1112
1113        /// Standard output for the command.
1114        stdout: Vec<u8>,
1115
1116        /// Standard error for the command.
1117        stderr: Vec<u8>,
1118    },
1119
1120    /// An error occurred while parsing a line in the test output.
1121    #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1122    ParseLine {
1123        /// The binary ID for which parsing the list of tests failed.
1124        binary_id: RustBinaryId,
1125
1126        /// A descriptive message.
1127        message: Cow<'static, str>,
1128
1129        /// The full output.
1130        full_output: String,
1131    },
1132
1133    /// An error occurred while joining paths for dynamic libraries.
1134    #[error(
1135        "error joining dynamic library paths for {}: [{}]",
1136        dylib_path_envvar(),
1137        itertools::join(.new_paths, ", ")
1138    )]
1139    DylibJoinPaths {
1140        /// New paths attempted to be added to the dynamic library environment variable.
1141        new_paths: Vec<Utf8PathBuf>,
1142
1143        /// The underlying error.
1144        #[source]
1145        error: JoinPathsError,
1146    },
1147
1148    /// Creating a Tokio runtime failed.
1149    #[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/// An error that occurs while writing list output.
1172#[derive(Debug, Error)]
1173#[non_exhaustive]
1174pub enum WriteTestListError {
1175    /// An error occurred while writing the list to the provided output.
1176    #[error("error writing to output")]
1177    Io(#[source] std::io::Error),
1178
1179    /// An error occurred while serializing JSON, or while writing it to the provided output.
1180    #[error("error serializing to JSON")]
1181    Json(#[source] serde_json::Error),
1182}
1183
1184/// An error occurred while configuring handles.
1185///
1186/// Only relevant on Windows.
1187#[derive(Debug, Error)]
1188pub enum ConfigureHandleInheritanceError {
1189    /// An error occurred. This can only happen on Windows.
1190    #[cfg(windows)]
1191    #[error("error configuring handle inheritance")]
1192    WindowsError(#[from] std::io::Error),
1193}
1194
1195/// An error that occurs while building the test runner.
1196#[derive(Debug, Error)]
1197#[non_exhaustive]
1198pub enum TestRunnerBuildError {
1199    /// An error occurred while creating the Tokio runtime.
1200    #[error("error creating Tokio runtime")]
1201    TokioRuntimeCreate(#[source] std::io::Error),
1202
1203    /// An error occurred while setting up signals.
1204    #[error("error setting up signals")]
1205    SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1206}
1207
1208/// Errors that occurred while managing test runner Tokio tasks.
1209#[derive(Debug, Error)]
1210pub struct TestRunnerExecuteErrors<E> {
1211    /// An error that occurred while reporting results to the reporter callback.
1212    pub report_error: Option<E>,
1213
1214    /// Join errors (typically panics) that occurred while running the test
1215    /// runner.
1216    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/// Represents an unknown archive format.
1246///
1247/// Returned by [`ArchiveFormat::autodetect`].
1248#[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    /// The name of the archive file without any leading components.
1255    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/// An error that occurs while archiving data.
1266#[derive(Debug, Error)]
1267#[non_exhaustive]
1268pub enum ArchiveCreateError {
1269    /// An error occurred while creating the binary list to be written.
1270    #[error("error creating binary list")]
1271    CreateBinaryList(#[source] WriteTestListError),
1272
1273    /// An extra path was missing.
1274    #[error("extra path `{}` not found", .redactor.redact_path(path))]
1275    MissingExtraPath {
1276        /// The path that was missing.
1277        path: Utf8PathBuf,
1278
1279        /// A redactor for the path.
1280        ///
1281        /// (This should eventually move to being a field for a wrapper struct, but it's okay for
1282        /// now.)
1283        redactor: Redactor,
1284    },
1285
1286    /// An error occurred while reading data from a file on disk.
1287    #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1288    InputFileRead {
1289        /// The step that the archive errored at.
1290        step: ArchiveStep,
1291
1292        /// The name of the file that could not be read.
1293        path: Utf8PathBuf,
1294
1295        /// Whether this is a directory. `None` means the status was unknown.
1296        is_dir: Option<bool>,
1297
1298        /// The error that occurred.
1299        #[source]
1300        error: std::io::Error,
1301    },
1302
1303    /// An error occurred while reading entries from a directory on disk.
1304    #[error("error reading directory entry from `{path}")]
1305    DirEntryRead {
1306        /// The name of the directory from which entries couldn't be read.
1307        path: Utf8PathBuf,
1308
1309        /// The error that occurred.
1310        #[source]
1311        error: std::io::Error,
1312    },
1313
1314    /// An error occurred while writing data to the output file.
1315    #[error("error writing to archive")]
1316    OutputArchiveIo(#[source] std::io::Error),
1317
1318    /// An error occurred in the reporter.
1319    #[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/// An error occurred while materializing a metadata path.
1332#[derive(Debug, Error)]
1333pub enum MetadataMaterializeError {
1334    /// An I/O error occurred while reading the metadata file.
1335    #[error("I/O error reading metadata file `{path}`")]
1336    Read {
1337        /// The path that was being read.
1338        path: Utf8PathBuf,
1339
1340        /// The error that occurred.
1341        #[source]
1342        error: std::io::Error,
1343    },
1344
1345    /// A JSON deserialization error occurred while reading the metadata file.
1346    #[error("error deserializing metadata file `{path}`")]
1347    Deserialize {
1348        /// The path that was being read.
1349        path: Utf8PathBuf,
1350
1351        /// The error that occurred.
1352        #[source]
1353        error: serde_json::Error,
1354    },
1355
1356    /// An error occurred while parsing Rust build metadata.
1357    #[error("error parsing Rust build metadata from `{path}`")]
1358    RustBuildMeta {
1359        /// The path that was deserialized.
1360        path: Utf8PathBuf,
1361
1362        /// The error that occurred.
1363        #[source]
1364        error: RustBuildMetaParseError,
1365    },
1366
1367    /// An error occurred converting data into a `PackageGraph`.
1368    #[error("error building package graph from `{path}`")]
1369    PackageGraphConstruct {
1370        /// The path that was deserialized.
1371        path: Utf8PathBuf,
1372
1373        /// The error that occurred.
1374        #[source]
1375        error: guppy::Error,
1376    },
1377}
1378
1379/// An error occurred while reading a file.
1380///
1381/// Returned as part of both [`ArchiveCreateError`] and [`ArchiveExtractError`].
1382#[derive(Debug, Error)]
1383#[non_exhaustive]
1384pub enum ArchiveReadError {
1385    /// An I/O error occurred while reading the archive.
1386    #[error("I/O error reading archive")]
1387    Io(#[source] std::io::Error),
1388
1389    /// A path wasn't valid UTF-8.
1390    #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1391    NonUtf8Path(Vec<u8>),
1392
1393    /// A file path within the archive didn't begin with "target/".
1394    #[error("path in archive `{0}` doesn't start with `target/`")]
1395    NoTargetPrefix(Utf8PathBuf),
1396
1397    /// A file path within the archive had an invalid component within it.
1398    #[error("path in archive `{path}` contains an invalid component `{component}`")]
1399    InvalidComponent {
1400        /// The path that had an invalid component.
1401        path: Utf8PathBuf,
1402
1403        /// The invalid component.
1404        component: String,
1405    },
1406
1407    /// An error occurred while reading a checksum.
1408    #[error("corrupted archive: checksum read error for path `{path}`")]
1409    ChecksumRead {
1410        /// The path for which there was a checksum read error.
1411        path: Utf8PathBuf,
1412
1413        /// The error that occurred.
1414        #[source]
1415        error: std::io::Error,
1416    },
1417
1418    /// An entry had an invalid checksum.
1419    #[error("corrupted archive: invalid checksum for path `{path}`")]
1420    InvalidChecksum {
1421        /// The path that had an invalid checksum.
1422        path: Utf8PathBuf,
1423
1424        /// The expected checksum.
1425        expected: u32,
1426
1427        /// The actual checksum.
1428        actual: u32,
1429    },
1430
1431    /// A metadata file wasn't found.
1432    #[error("metadata file `{0}` not found in archive")]
1433    MetadataFileNotFound(&'static Utf8Path),
1434
1435    /// An error occurred while deserializing a metadata file.
1436    #[error("error deserializing metadata file `{path}` in archive")]
1437    MetadataDeserializeError {
1438        /// The name of the metadata file.
1439        path: &'static Utf8Path,
1440
1441        /// The deserialize error.
1442        #[source]
1443        error: serde_json::Error,
1444    },
1445
1446    /// An error occurred while building a `PackageGraph`.
1447    #[error("error building package graph from `{path}` in archive")]
1448    PackageGraphConstructError {
1449        /// The name of the metadata file.
1450        path: &'static Utf8Path,
1451
1452        /// The error.
1453        #[source]
1454        error: guppy::Error,
1455    },
1456}
1457
1458/// An error occurred while extracting a file.
1459///
1460/// Returned by [`extract_archive`](crate::reuse_build::ReuseBuildInfo::extract_archive).
1461#[derive(Debug, Error)]
1462#[non_exhaustive]
1463pub enum ArchiveExtractError {
1464    /// An error occurred while creating a temporary directory.
1465    #[error("error creating temporary directory")]
1466    TempDirCreate(#[source] std::io::Error),
1467
1468    /// An error occurred while canonicalizing the destination directory.
1469    #[error("error canonicalizing destination directory `{dir}`")]
1470    DestDirCanonicalization {
1471        /// The directory that failed to canonicalize.
1472        dir: Utf8PathBuf,
1473
1474        /// The error that occurred.
1475        #[source]
1476        error: std::io::Error,
1477    },
1478
1479    /// The destination already exists and `--overwrite` was not passed in.
1480    #[error("destination `{0}` already exists")]
1481    DestinationExists(Utf8PathBuf),
1482
1483    /// An error occurred while reading the archive.
1484    #[error("error reading archive")]
1485    Read(#[source] ArchiveReadError),
1486
1487    /// An error occurred while deserializing Rust build metadata.
1488    #[error("error deserializing Rust build metadata")]
1489    RustBuildMeta(#[from] RustBuildMetaParseError),
1490
1491    /// An error occurred while writing out a file to the destination directory.
1492    #[error("error writing file `{path}` to disk")]
1493    WriteFile {
1494        /// The path that we couldn't write out.
1495        path: Utf8PathBuf,
1496
1497        /// The error that occurred.
1498        #[source]
1499        error: std::io::Error,
1500    },
1501
1502    /// An error occurred while reporting the extraction status.
1503    #[error("error reporting extract status")]
1504    ReporterIo(std::io::Error),
1505}
1506
1507/// An error that occurs while writing an event.
1508#[derive(Debug, Error)]
1509#[non_exhaustive]
1510pub enum WriteEventError {
1511    /// An error occurred while writing the event to the provided output.
1512    #[error("error writing to output")]
1513    Io(#[source] std::io::Error),
1514
1515    /// An error occurred while operating on the file system.
1516    #[error("error operating on path {file}")]
1517    Fs {
1518        /// The file being operated on.
1519        file: Utf8PathBuf,
1520
1521        /// The underlying IO error.
1522        #[source]
1523        error: std::io::Error,
1524    },
1525
1526    /// An error occurred while producing JUnit XML.
1527    #[error("error writing JUnit output to {file}")]
1528    Junit {
1529        /// The output file.
1530        file: Utf8PathBuf,
1531
1532        /// The underlying error.
1533        #[source]
1534        error: quick_junit::SerializeError,
1535    },
1536}
1537
1538/// An error occurred while constructing a [`CargoConfigs`](crate::cargo_config::CargoConfigs)
1539/// instance.
1540#[derive(Debug, Error)]
1541#[non_exhaustive]
1542pub enum CargoConfigError {
1543    /// Failed to retrieve the current directory.
1544    #[error("failed to retrieve current directory")]
1545    GetCurrentDir(#[source] std::io::Error),
1546
1547    /// The current directory was invalid UTF-8.
1548    #[error("current directory is invalid UTF-8")]
1549    CurrentDirInvalidUtf8(#[source] FromPathBufError),
1550
1551    /// Parsing a CLI config option failed.
1552    #[error("failed to parse --config argument `{config_str}` as TOML")]
1553    CliConfigParseError {
1554        /// The CLI config option.
1555        config_str: String,
1556
1557        /// The error that occurred trying to parse the config.
1558        #[source]
1559        error: toml_edit::TomlError,
1560    },
1561
1562    /// Deserializing a CLI config option into domain types failed.
1563    #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1564    CliConfigDeError {
1565        /// The CLI config option.
1566        config_str: String,
1567
1568        /// The error that occurred trying to deserialize the config.
1569        #[source]
1570        error: toml_edit::de::Error,
1571    },
1572
1573    /// A CLI config option is not in the dotted key format.
1574    #[error(
1575        "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1576    )]
1577    InvalidCliConfig {
1578        /// The CLI config option.
1579        config_str: String,
1580
1581        /// The reason why this Cargo CLI config is invalid.
1582        #[source]
1583        reason: InvalidCargoCliConfigReason,
1584    },
1585
1586    /// A non-UTF-8 path was encountered.
1587    #[error("non-UTF-8 path encountered")]
1588    NonUtf8Path(#[source] FromPathBufError),
1589
1590    /// Failed to retrieve the Cargo home directory.
1591    #[error("failed to retrieve the Cargo home directory")]
1592    GetCargoHome(#[source] std::io::Error),
1593
1594    /// Failed to canonicalize a path
1595    #[error("failed to canonicalize path `{path}")]
1596    FailedPathCanonicalization {
1597        /// The path that failed to canonicalize
1598        path: Utf8PathBuf,
1599
1600        /// The error the occurred during canonicalization
1601        #[source]
1602        error: std::io::Error,
1603    },
1604
1605    /// Failed to read config file
1606    #[error("failed to read config at `{path}`")]
1607    ConfigReadError {
1608        /// The path of the config file
1609        path: Utf8PathBuf,
1610
1611        /// The error that occurred trying to read the config file
1612        #[source]
1613        error: std::io::Error,
1614    },
1615
1616    /// Failed to deserialize config file
1617    #[error(transparent)]
1618    ConfigParseError(#[from] Box<CargoConfigParseError>),
1619}
1620
1621/// Failed to deserialize config file
1622///
1623/// We introduce this extra indirection, because of the `clippy::result_large_err` rule on Windows.
1624#[derive(Debug, Error)]
1625#[error("failed to parse config at `{path}`")]
1626pub struct CargoConfigParseError {
1627    /// The path of the config file
1628    pub path: Utf8PathBuf,
1629
1630    /// The error that occurred trying to deserialize the config file
1631    #[source]
1632    pub error: toml::de::Error,
1633}
1634
1635/// The reason an invalid CLI config failed.
1636///
1637/// Part of [`CargoConfigError::InvalidCliConfig`].
1638#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1639#[non_exhaustive]
1640pub enum InvalidCargoCliConfigReason {
1641    /// The argument is not a TOML dotted key expression.
1642    #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1643    NotDottedKv,
1644
1645    /// The argument includes non-whitespace decoration.
1646    #[error("includes non-whitespace decoration")]
1647    IncludesNonWhitespaceDecoration,
1648
1649    /// The argument sets a value to an inline table.
1650    #[error("sets a value to an inline table, which is not accepted")]
1651    SetsValueToInlineTable,
1652
1653    /// The argument sets a value to an array of tables.
1654    #[error("sets a value to an array of tables, which is not accepted")]
1655    SetsValueToArrayOfTables,
1656
1657    /// The argument doesn't provide a value.
1658    #[error("doesn't provide a value")]
1659    DoesntProvideValue,
1660}
1661
1662/// The host platform couldn't be detected.
1663#[derive(Debug, Error)]
1664pub enum HostPlatformDetectError {
1665    /// Spawning `rustc -vV` failed, and detecting the build target failed as
1666    /// well.
1667    #[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        /// The error.
1677        error: std::io::Error,
1678
1679        /// The error that occurred while detecting the build target.
1680        build_target_error: Box<target_spec::Error>,
1681    },
1682
1683    /// `rustc -vV` exited with a non-zero code, and detecting the build target
1684    /// failed as well.
1685    #[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        /// The status.
1698        status: ExitStatus,
1699
1700        /// The standard output from `rustc -vV`.
1701        stdout: Vec<u8>,
1702
1703        /// The standard error from `rustc -vV`.
1704        stderr: Vec<u8>,
1705
1706        /// The error that occurred while detecting the build target.
1707        build_target_error: Box<target_spec::Error>,
1708    },
1709
1710    /// Parsing the host platform failed, and detecting the build target failed
1711    /// as well.
1712    #[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        /// The error that occurred while parsing the host platform.
1722        host_platform_error: Box<target_spec::Error>,
1723
1724        /// The error that occurred while detecting the build target.
1725        build_target_error: Box<target_spec::Error>,
1726    },
1727
1728    /// Test-only code: `rustc -vV` was not queried, and detecting the build
1729    /// target failed as well.
1730    #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1731    BuildTargetError {
1732        /// The error that occurred while detecting the build target.
1733        #[source]
1734        build_target_error: Box<target_spec::Error>,
1735    },
1736}
1737
1738/// An error occurred while determining the cross-compiling target triple.
1739#[derive(Debug, Error)]
1740pub enum TargetTripleError {
1741    /// The environment variable contained non-utf8 content
1742    #[error(
1743        "environment variable '{}' contained non-UTF-8 data",
1744        TargetTriple::CARGO_BUILD_TARGET_ENV
1745    )]
1746    InvalidEnvironmentVar,
1747
1748    /// An error occurred while deserializing the platform.
1749    #[error("error deserializing target triple from {source}")]
1750    TargetSpecError {
1751        /// The source from which the triple couldn't be parsed.
1752        source: TargetTripleSource,
1753
1754        /// The error that occurred parsing the triple.
1755        #[source]
1756        error: target_spec::Error,
1757    },
1758
1759    /// For a custom platform, reading the target path failed.
1760    #[error("target path `{path}` is not a valid file")]
1761    TargetPathReadError {
1762        /// The source from which the triple couldn't be parsed.
1763        source: TargetTripleSource,
1764
1765        /// The path that we tried to read.
1766        path: Utf8PathBuf,
1767
1768        /// The error that occurred parsing the triple.
1769        #[source]
1770        error: std::io::Error,
1771    },
1772
1773    /// Failed to create a temporary directory for a custom platform.
1774    #[error(
1775        "for custom platform obtained from {source}, \
1776         failed to create temporary directory for custom platform"
1777    )]
1778    CustomPlatformTempDirError {
1779        /// The source of the target triple.
1780        source: TargetTripleSource,
1781
1782        /// The error that occurred during the create.
1783        #[source]
1784        error: std::io::Error,
1785    },
1786
1787    /// Failed to write a custom platform to disk.
1788    #[error(
1789        "for custom platform obtained from {source}, \
1790         failed to write JSON to temporary path `{path}`"
1791    )]
1792    CustomPlatformWriteError {
1793        /// The source of the target triple.
1794        source: TargetTripleSource,
1795
1796        /// The path that we tried to write to.
1797        path: Utf8PathBuf,
1798
1799        /// The error that occurred during the write.
1800        #[source]
1801        error: std::io::Error,
1802    },
1803
1804    /// Failed to close a temporary directory for an extracted custom platform.
1805    #[error(
1806        "for custom platform obtained from {source}, \
1807         failed to close temporary directory `{dir_path}`"
1808    )]
1809    CustomPlatformCloseError {
1810        /// The source of the target triple.
1811        source: TargetTripleSource,
1812
1813        /// The directory that we tried to delete.
1814        dir_path: Utf8PathBuf,
1815
1816        /// The error that occurred during the close.
1817        #[source]
1818        error: std::io::Error,
1819    },
1820}
1821
1822impl TargetTripleError {
1823    /// Returns a [`miette::Report`] for the source, if available.
1824    ///
1825    /// This should be preferred over [`std::error::Error::source`] if
1826    /// available.
1827    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            // The remaining types are covered via the error source path.
1833            TargetTripleError::InvalidEnvironmentVar
1834            | TargetTripleError::TargetPathReadError { .. }
1835            | TargetTripleError::CustomPlatformTempDirError { .. }
1836            | TargetTripleError::CustomPlatformWriteError { .. }
1837            | TargetTripleError::CustomPlatformCloseError { .. } => None,
1838        }
1839    }
1840}
1841
1842/// An error occurred determining the target runner
1843#[derive(Debug, Error)]
1844pub enum TargetRunnerError {
1845    /// An environment variable contained non-utf8 content
1846    #[error("environment variable '{0}' contained non-UTF-8 data")]
1847    InvalidEnvironmentVar(String),
1848
1849    /// An environment variable or config key was found that matches the target
1850    /// triple, but it didn't actually contain a binary
1851    #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1852    BinaryNotSpecified {
1853        /// The source under consideration.
1854        key: PlatformRunnerSource,
1855
1856        /// The value that was read from the key
1857        value: String,
1858    },
1859}
1860
1861/// An error that occurred while setting up the signal handler.
1862#[derive(Debug, Error)]
1863#[error("error setting up signal handler")]
1864pub struct SignalHandlerSetupError(#[from] std::io::Error);
1865
1866/// An error occurred while showing test groups.
1867#[derive(Debug, Error)]
1868pub enum ShowTestGroupsError {
1869    /// Unknown test groups were specified.
1870    #[error(
1871        "unknown test groups specified: {}\n(known groups: {})",
1872        unknown_groups.iter().join(", "),
1873        known_groups.iter().join(", "),
1874    )]
1875    UnknownGroups {
1876        /// The unknown test groups.
1877        unknown_groups: BTreeSet<TestGroup>,
1878
1879        /// All known test groups.
1880        known_groups: BTreeSet<TestGroup>,
1881    },
1882}
1883
1884/// An error occurred while processing profile's inherits setting
1885#[derive(Debug, Error, PartialEq, Eq, Hash)]
1886pub enum InheritsError {
1887    /// The default profile should not be able to inherit from other profiles
1888    #[error("the {} profile should not inherit from other profiles", .0)]
1889    DefaultProfileInheritance(String),
1890    /// An unknown/unfound profile was detected to inherit from in profile configuration
1891    #[error("profile {} inherits from an unknown profile {}", .0, .1)]
1892    UnknownInheritance(String, String),
1893    /// A self referential inheritance is detected from this profile
1894    #[error("a self referential inheritance is detected from profile: {}", .0)]
1895    SelfReferentialInheritance(String),
1896    /// An inheritance cycle was detected in the profile configuration.
1897    #[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    /// An error that occurs while performing a self-update.
1910    ///
1911    /// Returned by methods in the [`update`](crate::update) module.
1912    #[cfg(feature = "self-update")]
1913    #[derive(Debug, Error)]
1914    #[non_exhaustive]
1915    pub enum UpdateError {
1916        /// Failed to read release metadata from a local path on disk.
1917        #[error("failed to read release metadata from `{path}`")]
1918        ReadLocalMetadata {
1919            /// The path that was read.
1920            path: Utf8PathBuf,
1921
1922            /// The error that occurred.
1923            #[source]
1924            error: std::io::Error,
1925        },
1926
1927        /// An error was generated by `self_update`.
1928        #[error("self-update failed")]
1929        SelfUpdate(#[source] self_update::errors::Error),
1930
1931        /// Deserializing release metadata failed.
1932        #[error("deserializing release metadata failed")]
1933        ReleaseMetadataDe(#[source] serde_json::Error),
1934
1935        /// This version was not found.
1936        #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1937        VersionNotFound {
1938            /// The version that wasn't found.
1939            version: Version,
1940
1941            /// A list of all known versions.
1942            known: Vec<(Version, ReleaseStatus)>,
1943        },
1944
1945        /// No version was found matching a requirement.
1946        #[error("no version found matching requirement `{req}`")]
1947        NoMatchForVersionReq {
1948            /// The version requirement that had no matches.
1949            req: VersionReq,
1950        },
1951
1952        /// The specified mukti project was not found.
1953        #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1954        MuktiProjectNotFound {
1955            /// The project that was not found.
1956            not_found: String,
1957
1958            /// Known projects.
1959            known: Vec<String>,
1960        },
1961
1962        /// No release information was found for the given target triple.
1963        #[error(
1964            "for version {version}, no release information found for target `{triple}` \
1965            (known targets: {})",
1966            known_triples.iter().join(", ")
1967        )]
1968        NoTargetData {
1969            /// The version that was fetched.
1970            version: Version,
1971
1972            /// The target triple.
1973            triple: String,
1974
1975            /// The triples that were found.
1976            known_triples: BTreeSet<String>,
1977        },
1978
1979        /// The current executable could not be determined.
1980        #[error("the current executable's path could not be determined")]
1981        CurrentExe(#[source] std::io::Error),
1982
1983        /// A temporary directory could not be created.
1984        #[error("temporary directory could not be created at `{location}`")]
1985        TempDirCreate {
1986            /// The location where the temporary directory could not be created.
1987            location: Utf8PathBuf,
1988
1989            /// The error that occurred.
1990            #[source]
1991            error: std::io::Error,
1992        },
1993
1994        /// The temporary archive could not be created.
1995        #[error("temporary archive could not be created at `{archive_path}`")]
1996        TempArchiveCreate {
1997            /// The archive file that couldn't be created.
1998            archive_path: Utf8PathBuf,
1999
2000            /// The error that occurred.
2001            #[source]
2002            error: std::io::Error,
2003        },
2004
2005        /// An error occurred while writing to a temporary archive.
2006        #[error("error writing to temporary archive at `{archive_path}`")]
2007        TempArchiveWrite {
2008            /// The archive path for which there was an error.
2009            archive_path: Utf8PathBuf,
2010
2011            /// The error that occurred.
2012            #[source]
2013            error: std::io::Error,
2014        },
2015
2016        /// An error occurred while reading from a temporary archive.
2017        #[error("error reading from temporary archive at `{archive_path}`")]
2018        TempArchiveRead {
2019            /// The archive path for which there was an error.
2020            archive_path: Utf8PathBuf,
2021
2022            /// The error that occurred.
2023            #[source]
2024            error: std::io::Error,
2025        },
2026
2027        /// A checksum mismatch occurred. (Currently, the SHA-256 checksum is checked.)
2028        #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
2029        ChecksumMismatch {
2030            /// The expected checksum.
2031            expected: String,
2032
2033            /// The actual checksum.
2034            actual: String,
2035        },
2036
2037        /// An error occurred while renaming a file.
2038        #[error("error renaming `{source}` to `{dest}`")]
2039        FsRename {
2040            /// The rename source.
2041            source: Utf8PathBuf,
2042
2043            /// The rename destination.
2044            dest: Utf8PathBuf,
2045
2046            /// The error that occurred.
2047            #[source]
2048            error: std::io::Error,
2049        },
2050
2051        /// An error occurred while running `cargo nextest self setup`.
2052        #[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        // Take the first few versions here.
2060        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    /// An error occurred while parsing an [`UpdateVersion`](crate::update::UpdateVersion).
2083    #[derive(Debug, Error)]
2084    pub enum UpdateVersionParseError {
2085        /// The version string is empty.
2086        #[error("version string is empty")]
2087        EmptyString,
2088
2089        /// The input is not a valid version requirement.
2090        #[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            /// The input that was provided.
2096            input: String,
2097
2098            /// The error.
2099            #[source]
2100            error: semver::Error,
2101        },
2102
2103        /// The version is not a valid semver.
2104        #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2105        InvalidVersion {
2106            /// The input that was provided.
2107            input: String,
2108
2109            /// The error.
2110            #[source]
2111            error: semver::Error,
2112        },
2113    }
2114
2115    fn extra_semver_output(input: &str) -> String {
2116        // If it is not a valid version but it is a valid version
2117        // requirement, add a note to the warning
2118        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}