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/// Error returned while parsing a [`MaxFail`](crate::config::elements::MaxFail) input.
712#[derive(Clone, Debug, Error)]
713#[error("unrecognized value for max-fail: {reason}")]
714pub struct MaxFailParseError {
715    /// The reason parsing failed.
716    pub reason: String,
717}
718
719impl MaxFailParseError {
720    pub(crate) fn new(reason: impl Into<String>) -> Self {
721        Self {
722            reason: reason.into(),
723        }
724    }
725}
726
727/// Error returned while parsing a [`StressCount`](crate::runner::StressCount) input.
728#[derive(Clone, Debug, Error)]
729#[error(
730    "unrecognized value for stress-count: {input}\n\
731     (hint: expected either a positive integer or \"infinite\")"
732)]
733pub struct StressCountParseError {
734    /// The input that failed to parse.
735    pub input: String,
736}
737
738impl StressCountParseError {
739    pub(crate) fn new(input: impl Into<String>) -> Self {
740        Self {
741            input: input.into(),
742        }
743    }
744}
745
746/// An error that occurred while parsing a debugger command.
747#[derive(Clone, Debug, Error)]
748#[non_exhaustive]
749pub enum DebuggerCommandParseError {
750    /// The command string could not be parsed as shell words.
751    #[error(transparent)]
752    ShellWordsParse(shell_words::ParseError),
753
754    /// The command was empty.
755    #[error("debugger command cannot be empty")]
756    EmptyCommand,
757}
758
759/// An error that occurred while parsing a tracer command.
760#[derive(Clone, Debug, Error)]
761#[non_exhaustive]
762pub enum TracerCommandParseError {
763    /// The command string could not be parsed as shell words.
764    #[error(transparent)]
765    ShellWordsParse(shell_words::ParseError),
766
767    /// The command was empty.
768    #[error("tracer command cannot be empty")]
769    EmptyCommand,
770}
771
772/// Error returned while parsing a [`TestThreads`](crate::config::elements::TestThreads) value.
773#[derive(Clone, Debug, Error)]
774#[error(
775    "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
776)]
777pub struct TestThreadsParseError {
778    /// The input that failed to parse.
779    pub input: String,
780}
781
782impl TestThreadsParseError {
783    pub(crate) fn new(input: impl Into<String>) -> Self {
784        Self {
785            input: input.into(),
786        }
787    }
788}
789
790/// An error that occurs while parsing a
791/// [`PartitionerBuilder`](crate::partition::PartitionerBuilder) input.
792#[derive(Clone, Debug, Error)]
793pub struct PartitionerBuilderParseError {
794    expected_format: Option<&'static str>,
795    message: Cow<'static, str>,
796}
797
798impl PartitionerBuilderParseError {
799    pub(crate) fn new(
800        expected_format: Option<&'static str>,
801        message: impl Into<Cow<'static, str>>,
802    ) -> Self {
803        Self {
804            expected_format,
805            message: message.into(),
806        }
807    }
808}
809
810impl fmt::Display for PartitionerBuilderParseError {
811    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
812        match self.expected_format {
813            Some(format) => {
814                write!(
815                    f,
816                    "partition must be in the format \"{}\":\n{}",
817                    format, self.message
818                )
819            }
820            None => write!(f, "{}", self.message),
821        }
822    }
823}
824
825/// An error that occurs while operating on a
826/// [`TestFilterBuilder`](crate::test_filter::TestFilterBuilder).
827#[derive(Clone, Debug, Error)]
828pub enum TestFilterBuilderError {
829    /// An error that occurred while constructing test filters.
830    #[error("error constructing test filters")]
831    Construct {
832        /// The underlying error.
833        #[from]
834        error: aho_corasick::BuildError,
835    },
836}
837
838/// An error occurred in [`PathMapper::new`](crate::reuse_build::PathMapper::new).
839#[derive(Debug, Error)]
840pub enum PathMapperConstructError {
841    /// An error occurred while canonicalizing a directory.
842    #[error("{kind} `{input}` failed to canonicalize")]
843    Canonicalization {
844        /// The directory that failed to be canonicalized.
845        kind: PathMapperConstructKind,
846
847        /// The input provided.
848        input: Utf8PathBuf,
849
850        /// The error that occurred.
851        #[source]
852        err: std::io::Error,
853    },
854    /// The canonicalized path isn't valid UTF-8.
855    #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
856    NonUtf8Path {
857        /// The directory that failed to be canonicalized.
858        kind: PathMapperConstructKind,
859
860        /// The input provided.
861        input: Utf8PathBuf,
862
863        /// The underlying error.
864        #[source]
865        err: FromPathBufError,
866    },
867    /// A provided input is not a directory.
868    #[error("{kind} `{canonicalized_path}` is not a directory")]
869    NotADirectory {
870        /// The directory that failed to be canonicalized.
871        kind: PathMapperConstructKind,
872
873        /// The input provided.
874        input: Utf8PathBuf,
875
876        /// The canonicalized path that wasn't a directory.
877        canonicalized_path: Utf8PathBuf,
878    },
879}
880
881impl PathMapperConstructError {
882    /// The kind of directory.
883    pub fn kind(&self) -> PathMapperConstructKind {
884        match self {
885            Self::Canonicalization { kind, .. }
886            | Self::NonUtf8Path { kind, .. }
887            | Self::NotADirectory { kind, .. } => *kind,
888        }
889    }
890
891    /// The input path that failed.
892    pub fn input(&self) -> &Utf8Path {
893        match self {
894            Self::Canonicalization { input, .. }
895            | Self::NonUtf8Path { input, .. }
896            | Self::NotADirectory { input, .. } => input,
897        }
898    }
899}
900
901/// The kind of directory that failed to be read in
902/// [`PathMapper::new`](crate::reuse_build::PathMapper::new).
903///
904/// Returned as part of [`PathMapperConstructError`].
905#[derive(Copy, Clone, Debug, PartialEq, Eq)]
906pub enum PathMapperConstructKind {
907    /// The workspace root.
908    WorkspaceRoot,
909
910    /// The target directory.
911    TargetDir,
912}
913
914impl fmt::Display for PathMapperConstructKind {
915    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
916        match self {
917            Self::WorkspaceRoot => write!(f, "remapped workspace root"),
918            Self::TargetDir => write!(f, "remapped target directory"),
919        }
920    }
921}
922
923/// An error that occurs while parsing Rust build metadata from a summary.
924#[derive(Debug, Error)]
925pub enum RustBuildMetaParseError {
926    /// An error occurred while deserializing the platform.
927    #[error("error deserializing platform from build metadata")]
928    PlatformDeserializeError(#[from] target_spec::Error),
929
930    /// The host platform could not be determined.
931    #[error("the host platform could not be determined")]
932    DetectBuildTargetError(#[source] target_spec::Error),
933
934    /// The build metadata includes features unsupported.
935    #[error("unsupported features in the build metadata: {message}")]
936    Unsupported {
937        /// The detailed error message.
938        message: String,
939    },
940}
941
942/// Error returned when a user-supplied format version fails to be parsed to a
943/// valid and supported version.
944#[derive(Clone, Debug, thiserror::Error)]
945#[error("invalid format version: {input}")]
946pub struct FormatVersionError {
947    /// The input that failed to parse.
948    pub input: String,
949    /// The underlying error.
950    #[source]
951    pub error: FormatVersionErrorInner,
952}
953
954/// The different errors that can occur when parsing and validating a format version.
955#[derive(Clone, Debug, thiserror::Error)]
956pub enum FormatVersionErrorInner {
957    /// The input did not have a valid syntax.
958    #[error("expected format version in form of `{expected}`")]
959    InvalidFormat {
960        /// The expected pseudo format.
961        expected: &'static str,
962    },
963    /// A decimal integer was expected but could not be parsed.
964    #[error("version component `{which}` could not be parsed as an integer")]
965    InvalidInteger {
966        /// Which component was invalid.
967        which: &'static str,
968        /// The parse failure.
969        #[source]
970        err: std::num::ParseIntError,
971    },
972    /// The version component was not within the expected range.
973    #[error("version component `{which}` value {value} is out of range {range:?}")]
974    InvalidValue {
975        /// The component which was out of range.
976        which: &'static str,
977        /// The value that was parsed.
978        value: u8,
979        /// The range of valid values for the component.
980        range: std::ops::Range<u8>,
981    },
982}
983
984/// An error that occurs in [`BinaryList::from_messages`](crate::list::BinaryList::from_messages) or
985/// [`RustTestArtifact::from_binary_list`](crate::list::RustTestArtifact::from_binary_list).
986#[derive(Debug, Error)]
987#[non_exhaustive]
988pub enum FromMessagesError {
989    /// An error occurred while reading Cargo's JSON messages.
990    #[error("error reading Cargo JSON messages")]
991    ReadMessages(#[source] std::io::Error),
992
993    /// An error occurred while querying the package graph.
994    #[error("error querying package graph")]
995    PackageGraph(#[source] guppy::Error),
996
997    /// A target in the package graph was missing `kind` information.
998    #[error("missing kind for target {binary_name} in package {package_name}")]
999    MissingTargetKind {
1000        /// The name of the malformed package.
1001        package_name: String,
1002        /// The name of the malformed target within the package.
1003        binary_name: String,
1004    },
1005}
1006
1007/// An error that occurs while parsing test list output.
1008#[derive(Debug, Error)]
1009#[non_exhaustive]
1010pub enum CreateTestListError {
1011    /// The proposed cwd for a process is not a directory.
1012    #[error(
1013        "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
1014         (hint: ensure project source is available at this location)"
1015    )]
1016    CwdIsNotDir {
1017        /// The binary ID for which the current directory wasn't found.
1018        binary_id: RustBinaryId,
1019
1020        /// The current directory that wasn't found.
1021        cwd: Utf8PathBuf,
1022    },
1023
1024    /// Running a command to gather the list of tests failed to execute.
1025    #[error(
1026        "for `{binary_id}`, running command `{}` failed to execute",
1027        shell_words::join(command)
1028    )]
1029    CommandExecFail {
1030        /// The binary ID for which gathering the list of tests failed.
1031        binary_id: RustBinaryId,
1032
1033        /// The command that was run.
1034        command: Vec<String>,
1035
1036        /// The underlying error.
1037        #[source]
1038        error: std::io::Error,
1039    },
1040
1041    /// Running a command to gather the list of tests failed failed with a non-zero exit code.
1042    #[error(
1043        "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1044        shell_words::join(command),
1045        display_exited_with(*exit_status),
1046        String::from_utf8_lossy(stdout),
1047        String::from_utf8_lossy(stderr),
1048    )]
1049    CommandFail {
1050        /// The binary ID for which gathering the list of tests failed.
1051        binary_id: RustBinaryId,
1052
1053        /// The command that was run.
1054        command: Vec<String>,
1055
1056        /// The exit status with which the command failed.
1057        exit_status: ExitStatus,
1058
1059        /// Standard output for the command.
1060        stdout: Vec<u8>,
1061
1062        /// Standard error for the command.
1063        stderr: Vec<u8>,
1064    },
1065
1066    /// Running a command to gather the list of tests produced a non-UTF-8 standard output.
1067    #[error(
1068        "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1069        shell_words::join(command),
1070        String::from_utf8_lossy(stdout),
1071        String::from_utf8_lossy(stderr)
1072    )]
1073    CommandNonUtf8 {
1074        /// The binary ID for which gathering the list of tests failed.
1075        binary_id: RustBinaryId,
1076
1077        /// The command that was run.
1078        command: Vec<String>,
1079
1080        /// Standard output for the command.
1081        stdout: Vec<u8>,
1082
1083        /// Standard error for the command.
1084        stderr: Vec<u8>,
1085    },
1086
1087    /// An error occurred while parsing a line in the test output.
1088    #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1089    ParseLine {
1090        /// The binary ID for which parsing the list of tests failed.
1091        binary_id: RustBinaryId,
1092
1093        /// A descriptive message.
1094        message: Cow<'static, str>,
1095
1096        /// The full output.
1097        full_output: String,
1098    },
1099
1100    /// An error occurred while joining paths for dynamic libraries.
1101    #[error(
1102        "error joining dynamic library paths for {}: [{}]",
1103        dylib_path_envvar(),
1104        itertools::join(.new_paths, ", ")
1105    )]
1106    DylibJoinPaths {
1107        /// New paths attempted to be added to the dynamic library environment variable.
1108        new_paths: Vec<Utf8PathBuf>,
1109
1110        /// The underlying error.
1111        #[source]
1112        error: JoinPathsError,
1113    },
1114
1115    /// Creating a Tokio runtime failed.
1116    #[error("error creating Tokio runtime")]
1117    TokioRuntimeCreate(#[source] std::io::Error),
1118}
1119
1120impl CreateTestListError {
1121    pub(crate) fn parse_line(
1122        binary_id: RustBinaryId,
1123        message: impl Into<Cow<'static, str>>,
1124        full_output: impl Into<String>,
1125    ) -> Self {
1126        Self::ParseLine {
1127            binary_id,
1128            message: message.into(),
1129            full_output: full_output.into(),
1130        }
1131    }
1132
1133    pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1134        Self::DylibJoinPaths { new_paths, error }
1135    }
1136}
1137
1138/// An error that occurs while writing list output.
1139#[derive(Debug, Error)]
1140#[non_exhaustive]
1141pub enum WriteTestListError {
1142    /// An error occurred while writing the list to the provided output.
1143    #[error("error writing to output")]
1144    Io(#[source] std::io::Error),
1145
1146    /// An error occurred while serializing JSON, or while writing it to the provided output.
1147    #[error("error serializing to JSON")]
1148    Json(#[source] serde_json::Error),
1149}
1150
1151/// An error occurred while configuring handles.
1152///
1153/// Only relevant on Windows.
1154#[derive(Debug, Error)]
1155pub enum ConfigureHandleInheritanceError {
1156    /// An error occurred. This can only happen on Windows.
1157    #[cfg(windows)]
1158    #[error("error configuring handle inheritance")]
1159    WindowsError(#[from] std::io::Error),
1160}
1161
1162/// An error that occurs while building the test runner.
1163#[derive(Debug, Error)]
1164#[non_exhaustive]
1165pub enum TestRunnerBuildError {
1166    /// An error occurred while creating the Tokio runtime.
1167    #[error("error creating Tokio runtime")]
1168    TokioRuntimeCreate(#[source] std::io::Error),
1169
1170    /// An error occurred while setting up signals.
1171    #[error("error setting up signals")]
1172    SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1173}
1174
1175/// Errors that occurred while managing test runner Tokio tasks.
1176#[derive(Debug, Error)]
1177pub struct TestRunnerExecuteErrors<E> {
1178    /// An error that occurred while reporting results to the reporter callback.
1179    pub report_error: Option<E>,
1180
1181    /// Join errors (typically panics) that occurred while running the test
1182    /// runner.
1183    pub join_errors: Vec<tokio::task::JoinError>,
1184}
1185
1186impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1188        if let Some(report_error) = &self.report_error {
1189            write!(f, "error reporting results: {report_error}")?;
1190        }
1191
1192        if !self.join_errors.is_empty() {
1193            if self.report_error.is_some() {
1194                write!(f, "; ")?;
1195            }
1196
1197            write!(f, "errors joining tasks: ")?;
1198
1199            for (i, join_error) in self.join_errors.iter().enumerate() {
1200                if i > 0 {
1201                    write!(f, ", ")?;
1202                }
1203
1204                write!(f, "{join_error}")?;
1205            }
1206        }
1207
1208        Ok(())
1209    }
1210}
1211
1212/// Represents an unknown archive format.
1213///
1214/// Returned by [`ArchiveFormat::autodetect`].
1215#[derive(Debug, Error)]
1216#[error(
1217    "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1218    supported_extensions()
1219)]
1220pub struct UnknownArchiveFormat {
1221    /// The name of the archive file without any leading components.
1222    pub file_name: String,
1223}
1224
1225fn supported_extensions() -> String {
1226    ArchiveFormat::SUPPORTED_FORMATS
1227        .iter()
1228        .map(|(extension, _)| *extension)
1229        .join(", ")
1230}
1231
1232/// An error that occurs while archiving data.
1233#[derive(Debug, Error)]
1234#[non_exhaustive]
1235pub enum ArchiveCreateError {
1236    /// An error occurred while creating the binary list to be written.
1237    #[error("error creating binary list")]
1238    CreateBinaryList(#[source] WriteTestListError),
1239
1240    /// An extra path was missing.
1241    #[error("extra path `{}` not found", .redactor.redact_path(path))]
1242    MissingExtraPath {
1243        /// The path that was missing.
1244        path: Utf8PathBuf,
1245
1246        /// A redactor for the path.
1247        ///
1248        /// (This should eventually move to being a field for a wrapper struct, but it's okay for
1249        /// now.)
1250        redactor: Redactor,
1251    },
1252
1253    /// An error occurred while reading data from a file on disk.
1254    #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1255    InputFileRead {
1256        /// The step that the archive errored at.
1257        step: ArchiveStep,
1258
1259        /// The name of the file that could not be read.
1260        path: Utf8PathBuf,
1261
1262        /// Whether this is a directory. `None` means the status was unknown.
1263        is_dir: Option<bool>,
1264
1265        /// The error that occurred.
1266        #[source]
1267        error: std::io::Error,
1268    },
1269
1270    /// An error occurred while reading entries from a directory on disk.
1271    #[error("error reading directory entry from `{path}")]
1272    DirEntryRead {
1273        /// The name of the directory from which entries couldn't be read.
1274        path: Utf8PathBuf,
1275
1276        /// The error that occurred.
1277        #[source]
1278        error: std::io::Error,
1279    },
1280
1281    /// An error occurred while writing data to the output file.
1282    #[error("error writing to archive")]
1283    OutputArchiveIo(#[source] std::io::Error),
1284
1285    /// An error occurred in the reporter.
1286    #[error("error reporting archive status")]
1287    ReporterIo(#[source] std::io::Error),
1288}
1289
1290fn kind_str(is_dir: Option<bool>) -> &'static str {
1291    match is_dir {
1292        Some(true) => "directory",
1293        Some(false) => "file",
1294        None => "path",
1295    }
1296}
1297
1298/// An error occurred while materializing a metadata path.
1299#[derive(Debug, Error)]
1300pub enum MetadataMaterializeError {
1301    /// An I/O error occurred while reading the metadata file.
1302    #[error("I/O error reading metadata file `{path}`")]
1303    Read {
1304        /// The path that was being read.
1305        path: Utf8PathBuf,
1306
1307        /// The error that occurred.
1308        #[source]
1309        error: std::io::Error,
1310    },
1311
1312    /// A JSON deserialization error occurred while reading the metadata file.
1313    #[error("error deserializing metadata file `{path}`")]
1314    Deserialize {
1315        /// The path that was being read.
1316        path: Utf8PathBuf,
1317
1318        /// The error that occurred.
1319        #[source]
1320        error: serde_json::Error,
1321    },
1322
1323    /// An error occurred while parsing Rust build metadata.
1324    #[error("error parsing Rust build metadata from `{path}`")]
1325    RustBuildMeta {
1326        /// The path that was deserialized.
1327        path: Utf8PathBuf,
1328
1329        /// The error that occurred.
1330        #[source]
1331        error: RustBuildMetaParseError,
1332    },
1333
1334    /// An error occurred converting data into a `PackageGraph`.
1335    #[error("error building package graph from `{path}`")]
1336    PackageGraphConstruct {
1337        /// The path that was deserialized.
1338        path: Utf8PathBuf,
1339
1340        /// The error that occurred.
1341        #[source]
1342        error: guppy::Error,
1343    },
1344}
1345
1346/// An error occurred while reading a file.
1347///
1348/// Returned as part of both [`ArchiveCreateError`] and [`ArchiveExtractError`].
1349#[derive(Debug, Error)]
1350#[non_exhaustive]
1351pub enum ArchiveReadError {
1352    /// An I/O error occurred while reading the archive.
1353    #[error("I/O error reading archive")]
1354    Io(#[source] std::io::Error),
1355
1356    /// A path wasn't valid UTF-8.
1357    #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1358    NonUtf8Path(Vec<u8>),
1359
1360    /// A file path within the archive didn't begin with "target/".
1361    #[error("path in archive `{0}` doesn't start with `target/`")]
1362    NoTargetPrefix(Utf8PathBuf),
1363
1364    /// A file path within the archive had an invalid component within it.
1365    #[error("path in archive `{path}` contains an invalid component `{component}`")]
1366    InvalidComponent {
1367        /// The path that had an invalid component.
1368        path: Utf8PathBuf,
1369
1370        /// The invalid component.
1371        component: String,
1372    },
1373
1374    /// An error occurred while reading a checksum.
1375    #[error("corrupted archive: checksum read error for path `{path}`")]
1376    ChecksumRead {
1377        /// The path for which there was a checksum read error.
1378        path: Utf8PathBuf,
1379
1380        /// The error that occurred.
1381        #[source]
1382        error: std::io::Error,
1383    },
1384
1385    /// An entry had an invalid checksum.
1386    #[error("corrupted archive: invalid checksum for path `{path}`")]
1387    InvalidChecksum {
1388        /// The path that had an invalid checksum.
1389        path: Utf8PathBuf,
1390
1391        /// The expected checksum.
1392        expected: u32,
1393
1394        /// The actual checksum.
1395        actual: u32,
1396    },
1397
1398    /// A metadata file wasn't found.
1399    #[error("metadata file `{0}` not found in archive")]
1400    MetadataFileNotFound(&'static Utf8Path),
1401
1402    /// An error occurred while deserializing a metadata file.
1403    #[error("error deserializing metadata file `{path}` in archive")]
1404    MetadataDeserializeError {
1405        /// The name of the metadata file.
1406        path: &'static Utf8Path,
1407
1408        /// The deserialize error.
1409        #[source]
1410        error: serde_json::Error,
1411    },
1412
1413    /// An error occurred while building a `PackageGraph`.
1414    #[error("error building package graph from `{path}` in archive")]
1415    PackageGraphConstructError {
1416        /// The name of the metadata file.
1417        path: &'static Utf8Path,
1418
1419        /// The error.
1420        #[source]
1421        error: guppy::Error,
1422    },
1423}
1424
1425/// An error occurred while extracting a file.
1426///
1427/// Returned by [`extract_archive`](crate::reuse_build::ReuseBuildInfo::extract_archive).
1428#[derive(Debug, Error)]
1429#[non_exhaustive]
1430pub enum ArchiveExtractError {
1431    /// An error occurred while creating a temporary directory.
1432    #[error("error creating temporary directory")]
1433    TempDirCreate(#[source] std::io::Error),
1434
1435    /// An error occurred while canonicalizing the destination directory.
1436    #[error("error canonicalizing destination directory `{dir}`")]
1437    DestDirCanonicalization {
1438        /// The directory that failed to canonicalize.
1439        dir: Utf8PathBuf,
1440
1441        /// The error that occurred.
1442        #[source]
1443        error: std::io::Error,
1444    },
1445
1446    /// The destination already exists and `--overwrite` was not passed in.
1447    #[error("destination `{0}` already exists")]
1448    DestinationExists(Utf8PathBuf),
1449
1450    /// An error occurred while reading the archive.
1451    #[error("error reading archive")]
1452    Read(#[source] ArchiveReadError),
1453
1454    /// An error occurred while deserializing Rust build metadata.
1455    #[error("error deserializing Rust build metadata")]
1456    RustBuildMeta(#[from] RustBuildMetaParseError),
1457
1458    /// An error occurred while writing out a file to the destination directory.
1459    #[error("error writing file `{path}` to disk")]
1460    WriteFile {
1461        /// The path that we couldn't write out.
1462        path: Utf8PathBuf,
1463
1464        /// The error that occurred.
1465        #[source]
1466        error: std::io::Error,
1467    },
1468
1469    /// An error occurred while reporting the extraction status.
1470    #[error("error reporting extract status")]
1471    ReporterIo(std::io::Error),
1472}
1473
1474/// An error that occurs while writing an event.
1475#[derive(Debug, Error)]
1476#[non_exhaustive]
1477pub enum WriteEventError {
1478    /// An error occurred while writing the event to the provided output.
1479    #[error("error writing to output")]
1480    Io(#[source] std::io::Error),
1481
1482    /// An error occurred while operating on the file system.
1483    #[error("error operating on path {file}")]
1484    Fs {
1485        /// The file being operated on.
1486        file: Utf8PathBuf,
1487
1488        /// The underlying IO error.
1489        #[source]
1490        error: std::io::Error,
1491    },
1492
1493    /// An error occurred while producing JUnit XML.
1494    #[error("error writing JUnit output to {file}")]
1495    Junit {
1496        /// The output file.
1497        file: Utf8PathBuf,
1498
1499        /// The underlying error.
1500        #[source]
1501        error: quick_junit::SerializeError,
1502    },
1503}
1504
1505/// An error occurred while constructing a [`CargoConfigs`](crate::cargo_config::CargoConfigs)
1506/// instance.
1507#[derive(Debug, Error)]
1508#[non_exhaustive]
1509pub enum CargoConfigError {
1510    /// Failed to retrieve the current directory.
1511    #[error("failed to retrieve current directory")]
1512    GetCurrentDir(#[source] std::io::Error),
1513
1514    /// The current directory was invalid UTF-8.
1515    #[error("current directory is invalid UTF-8")]
1516    CurrentDirInvalidUtf8(#[source] FromPathBufError),
1517
1518    /// Parsing a CLI config option failed.
1519    #[error("failed to parse --config argument `{config_str}` as TOML")]
1520    CliConfigParseError {
1521        /// The CLI config option.
1522        config_str: String,
1523
1524        /// The error that occurred trying to parse the config.
1525        #[source]
1526        error: toml_edit::TomlError,
1527    },
1528
1529    /// Deserializing a CLI config option into domain types failed.
1530    #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1531    CliConfigDeError {
1532        /// The CLI config option.
1533        config_str: String,
1534
1535        /// The error that occurred trying to deserialize the config.
1536        #[source]
1537        error: toml_edit::de::Error,
1538    },
1539
1540    /// A CLI config option is not in the dotted key format.
1541    #[error(
1542        "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1543    )]
1544    InvalidCliConfig {
1545        /// The CLI config option.
1546        config_str: String,
1547
1548        /// The reason why this Cargo CLI config is invalid.
1549        #[source]
1550        reason: InvalidCargoCliConfigReason,
1551    },
1552
1553    /// A non-UTF-8 path was encountered.
1554    #[error("non-UTF-8 path encountered")]
1555    NonUtf8Path(#[source] FromPathBufError),
1556
1557    /// Failed to retrieve the Cargo home directory.
1558    #[error("failed to retrieve the Cargo home directory")]
1559    GetCargoHome(#[source] std::io::Error),
1560
1561    /// Failed to canonicalize a path
1562    #[error("failed to canonicalize path `{path}")]
1563    FailedPathCanonicalization {
1564        /// The path that failed to canonicalize
1565        path: Utf8PathBuf,
1566
1567        /// The error the occurred during canonicalization
1568        #[source]
1569        error: std::io::Error,
1570    },
1571
1572    /// Failed to read config file
1573    #[error("failed to read config at `{path}`")]
1574    ConfigReadError {
1575        /// The path of the config file
1576        path: Utf8PathBuf,
1577
1578        /// The error that occurred trying to read the config file
1579        #[source]
1580        error: std::io::Error,
1581    },
1582
1583    /// Failed to deserialize config file
1584    #[error(transparent)]
1585    ConfigParseError(#[from] Box<CargoConfigParseError>),
1586}
1587
1588/// Failed to deserialize config file
1589///
1590/// We introduce this extra indirection, because of the `clippy::result_large_err` rule on Windows.
1591#[derive(Debug, Error)]
1592#[error("failed to parse config at `{path}`")]
1593pub struct CargoConfigParseError {
1594    /// The path of the config file
1595    pub path: Utf8PathBuf,
1596
1597    /// The error that occurred trying to deserialize the config file
1598    #[source]
1599    pub error: toml::de::Error,
1600}
1601
1602/// The reason an invalid CLI config failed.
1603///
1604/// Part of [`CargoConfigError::InvalidCliConfig`].
1605#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1606#[non_exhaustive]
1607pub enum InvalidCargoCliConfigReason {
1608    /// The argument is not a TOML dotted key expression.
1609    #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1610    NotDottedKv,
1611
1612    /// The argument includes non-whitespace decoration.
1613    #[error("includes non-whitespace decoration")]
1614    IncludesNonWhitespaceDecoration,
1615
1616    /// The argument sets a value to an inline table.
1617    #[error("sets a value to an inline table, which is not accepted")]
1618    SetsValueToInlineTable,
1619
1620    /// The argument sets a value to an array of tables.
1621    #[error("sets a value to an array of tables, which is not accepted")]
1622    SetsValueToArrayOfTables,
1623
1624    /// The argument doesn't provide a value.
1625    #[error("doesn't provide a value")]
1626    DoesntProvideValue,
1627}
1628
1629/// The host platform couldn't be detected.
1630#[derive(Debug, Error)]
1631pub enum HostPlatformDetectError {
1632    /// Spawning `rustc -vV` failed, and detecting the build target failed as
1633    /// well.
1634    #[error(
1635        "error spawning `rustc -vV`, and detecting the build \
1636         target failed as well\n\
1637         - rustc spawn error: {}\n\
1638         - build target error: {}\n",
1639        DisplayErrorChain::new_with_initial_indent("  ", error),
1640        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1641    )]
1642    RustcVvSpawnError {
1643        /// The error.
1644        error: std::io::Error,
1645
1646        /// The error that occurred while detecting the build target.
1647        build_target_error: Box<target_spec::Error>,
1648    },
1649
1650    /// `rustc -vV` exited with a non-zero code, and detecting the build target
1651    /// failed as well.
1652    #[error(
1653        "`rustc -vV` failed with {}, and detecting the \
1654         build target failed as well\n\
1655         - `rustc -vV` stdout:\n{}\n\
1656         - `rustc -vV` stderr:\n{}\n\
1657         - build target error:\n{}\n",
1658        status,
1659        DisplayIndented { item: String::from_utf8_lossy(stdout), indent: "  " },
1660        DisplayIndented { item: String::from_utf8_lossy(stderr), indent: "  " },
1661        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1662    )]
1663    RustcVvFailed {
1664        /// The status.
1665        status: ExitStatus,
1666
1667        /// The standard output from `rustc -vV`.
1668        stdout: Vec<u8>,
1669
1670        /// The standard error from `rustc -vV`.
1671        stderr: Vec<u8>,
1672
1673        /// The error that occurred while detecting the build target.
1674        build_target_error: Box<target_spec::Error>,
1675    },
1676
1677    /// Parsing the host platform failed, and detecting the build target failed
1678    /// as well.
1679    #[error(
1680        "parsing `rustc -vV` output failed, and detecting the build target \
1681         failed as well\n\
1682         - host platform error:\n{}\n\
1683         - build target error:\n{}\n",
1684        DisplayErrorChain::new_with_initial_indent("  ", host_platform_error),
1685        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1686    )]
1687    HostPlatformParseError {
1688        /// The error that occurred while parsing the host platform.
1689        host_platform_error: Box<target_spec::Error>,
1690
1691        /// The error that occurred while detecting the build target.
1692        build_target_error: Box<target_spec::Error>,
1693    },
1694
1695    /// Test-only code: `rustc -vV` was not queried, and detecting the build
1696    /// target failed as well.
1697    #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1698    BuildTargetError {
1699        /// The error that occurred while detecting the build target.
1700        #[source]
1701        build_target_error: Box<target_spec::Error>,
1702    },
1703}
1704
1705/// An error occurred while determining the cross-compiling target triple.
1706#[derive(Debug, Error)]
1707pub enum TargetTripleError {
1708    /// The environment variable contained non-utf8 content
1709    #[error(
1710        "environment variable '{}' contained non-UTF-8 data",
1711        TargetTriple::CARGO_BUILD_TARGET_ENV
1712    )]
1713    InvalidEnvironmentVar,
1714
1715    /// An error occurred while deserializing the platform.
1716    #[error("error deserializing target triple from {source}")]
1717    TargetSpecError {
1718        /// The source from which the triple couldn't be parsed.
1719        source: TargetTripleSource,
1720
1721        /// The error that occurred parsing the triple.
1722        #[source]
1723        error: target_spec::Error,
1724    },
1725
1726    /// For a custom platform, reading the target path failed.
1727    #[error("target path `{path}` is not a valid file")]
1728    TargetPathReadError {
1729        /// The source from which the triple couldn't be parsed.
1730        source: TargetTripleSource,
1731
1732        /// The path that we tried to read.
1733        path: Utf8PathBuf,
1734
1735        /// The error that occurred parsing the triple.
1736        #[source]
1737        error: std::io::Error,
1738    },
1739
1740    /// Failed to create a temporary directory for a custom platform.
1741    #[error(
1742        "for custom platform obtained from {source}, \
1743         failed to create temporary directory for custom platform"
1744    )]
1745    CustomPlatformTempDirError {
1746        /// The source of the target triple.
1747        source: TargetTripleSource,
1748
1749        /// The error that occurred during the create.
1750        #[source]
1751        error: std::io::Error,
1752    },
1753
1754    /// Failed to write a custom platform to disk.
1755    #[error(
1756        "for custom platform obtained from {source}, \
1757         failed to write JSON to temporary path `{path}`"
1758    )]
1759    CustomPlatformWriteError {
1760        /// The source of the target triple.
1761        source: TargetTripleSource,
1762
1763        /// The path that we tried to write to.
1764        path: Utf8PathBuf,
1765
1766        /// The error that occurred during the write.
1767        #[source]
1768        error: std::io::Error,
1769    },
1770
1771    /// Failed to close a temporary directory for an extracted custom platform.
1772    #[error(
1773        "for custom platform obtained from {source}, \
1774         failed to close temporary directory `{dir_path}`"
1775    )]
1776    CustomPlatformCloseError {
1777        /// The source of the target triple.
1778        source: TargetTripleSource,
1779
1780        /// The directory that we tried to delete.
1781        dir_path: Utf8PathBuf,
1782
1783        /// The error that occurred during the close.
1784        #[source]
1785        error: std::io::Error,
1786    },
1787}
1788
1789impl TargetTripleError {
1790    /// Returns a [`miette::Report`] for the source, if available.
1791    ///
1792    /// This should be preferred over [`std::error::Error::source`] if
1793    /// available.
1794    pub fn source_report(&self) -> Option<miette::Report> {
1795        match self {
1796            Self::TargetSpecError { error, .. } => {
1797                Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1798            }
1799            // The remaining types are covered via the error source path.
1800            TargetTripleError::InvalidEnvironmentVar
1801            | TargetTripleError::TargetPathReadError { .. }
1802            | TargetTripleError::CustomPlatformTempDirError { .. }
1803            | TargetTripleError::CustomPlatformWriteError { .. }
1804            | TargetTripleError::CustomPlatformCloseError { .. } => None,
1805        }
1806    }
1807}
1808
1809/// An error occurred determining the target runner
1810#[derive(Debug, Error)]
1811pub enum TargetRunnerError {
1812    /// An environment variable contained non-utf8 content
1813    #[error("environment variable '{0}' contained non-UTF-8 data")]
1814    InvalidEnvironmentVar(String),
1815
1816    /// An environment variable or config key was found that matches the target
1817    /// triple, but it didn't actually contain a binary
1818    #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1819    BinaryNotSpecified {
1820        /// The source under consideration.
1821        key: PlatformRunnerSource,
1822
1823        /// The value that was read from the key
1824        value: String,
1825    },
1826}
1827
1828/// An error that occurred while setting up the signal handler.
1829#[derive(Debug, Error)]
1830#[error("error setting up signal handler")]
1831pub struct SignalHandlerSetupError(#[from] std::io::Error);
1832
1833/// An error occurred while showing test groups.
1834#[derive(Debug, Error)]
1835pub enum ShowTestGroupsError {
1836    /// Unknown test groups were specified.
1837    #[error(
1838        "unknown test groups specified: {}\n(known groups: {})",
1839        unknown_groups.iter().join(", "),
1840        known_groups.iter().join(", "),
1841    )]
1842    UnknownGroups {
1843        /// The unknown test groups.
1844        unknown_groups: BTreeSet<TestGroup>,
1845
1846        /// All known test groups.
1847        known_groups: BTreeSet<TestGroup>,
1848    },
1849}
1850
1851/// An error occurred while processing profile's inherits setting
1852#[derive(Debug, Error, PartialEq, Eq, Hash)]
1853pub enum InheritsError {
1854    /// The default profile should not be able to inherit from other profiles
1855    #[error("the {} profile should not inherit from other profiles", .0)]
1856    DefaultProfileInheritance(String),
1857    /// An unknown/unfound profile was detected to inherit from in profile configuration
1858    #[error("profile {} inherits from an unknown profile {}", .0, .1)]
1859    UnknownInheritance(String, String),
1860    /// A self referential inheritance is detected from this profile
1861    #[error("a self referential inheritance is detected from profile: {}", .0)]
1862    SelfReferentialInheritance(String),
1863    /// An inheritance cycle was detected in the profile configuration.
1864    #[error("inheritance cycle detected in profile configuration from: {}", .0.iter().map(|scc| {
1865        format!("[{}]", scc.iter().join(", "))
1866    }).join(", "))]
1867    InheritanceCycle(Vec<Vec<String>>),
1868}
1869
1870#[cfg(feature = "self-update")]
1871mod self_update_errors {
1872    use super::*;
1873    use mukti_metadata::ReleaseStatus;
1874    use semver::{Version, VersionReq};
1875
1876    /// An error that occurs while performing a self-update.
1877    ///
1878    /// Returned by methods in the [`update`](crate::update) module.
1879    #[cfg(feature = "self-update")]
1880    #[derive(Debug, Error)]
1881    #[non_exhaustive]
1882    pub enum UpdateError {
1883        /// Failed to read release metadata from a local path on disk.
1884        #[error("failed to read release metadata from `{path}`")]
1885        ReadLocalMetadata {
1886            /// The path that was read.
1887            path: Utf8PathBuf,
1888
1889            /// The error that occurred.
1890            #[source]
1891            error: std::io::Error,
1892        },
1893
1894        /// An error was generated by `self_update`.
1895        #[error("self-update failed")]
1896        SelfUpdate(#[source] self_update::errors::Error),
1897
1898        /// Deserializing release metadata failed.
1899        #[error("deserializing release metadata failed")]
1900        ReleaseMetadataDe(#[source] serde_json::Error),
1901
1902        /// This version was not found.
1903        #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1904        VersionNotFound {
1905            /// The version that wasn't found.
1906            version: Version,
1907
1908            /// A list of all known versions.
1909            known: Vec<(Version, ReleaseStatus)>,
1910        },
1911
1912        /// No version was found matching a requirement.
1913        #[error("no version found matching requirement `{req}`")]
1914        NoMatchForVersionReq {
1915            /// The version requirement that had no matches.
1916            req: VersionReq,
1917        },
1918
1919        /// The specified mukti project was not found.
1920        #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1921        MuktiProjectNotFound {
1922            /// The project that was not found.
1923            not_found: String,
1924
1925            /// Known projects.
1926            known: Vec<String>,
1927        },
1928
1929        /// No release information was found for the given target triple.
1930        #[error(
1931            "for version {version}, no release information found for target `{triple}` \
1932            (known targets: {})",
1933            known_triples.iter().join(", ")
1934        )]
1935        NoTargetData {
1936            /// The version that was fetched.
1937            version: Version,
1938
1939            /// The target triple.
1940            triple: String,
1941
1942            /// The triples that were found.
1943            known_triples: BTreeSet<String>,
1944        },
1945
1946        /// The current executable could not be determined.
1947        #[error("the current executable's path could not be determined")]
1948        CurrentExe(#[source] std::io::Error),
1949
1950        /// A temporary directory could not be created.
1951        #[error("temporary directory could not be created at `{location}`")]
1952        TempDirCreate {
1953            /// The location where the temporary directory could not be created.
1954            location: Utf8PathBuf,
1955
1956            /// The error that occurred.
1957            #[source]
1958            error: std::io::Error,
1959        },
1960
1961        /// The temporary archive could not be created.
1962        #[error("temporary archive could not be created at `{archive_path}`")]
1963        TempArchiveCreate {
1964            /// The archive file that couldn't be created.
1965            archive_path: Utf8PathBuf,
1966
1967            /// The error that occurred.
1968            #[source]
1969            error: std::io::Error,
1970        },
1971
1972        /// An error occurred while writing to a temporary archive.
1973        #[error("error writing to temporary archive at `{archive_path}`")]
1974        TempArchiveWrite {
1975            /// The archive path for which there was an error.
1976            archive_path: Utf8PathBuf,
1977
1978            /// The error that occurred.
1979            #[source]
1980            error: std::io::Error,
1981        },
1982
1983        /// An error occurred while reading from a temporary archive.
1984        #[error("error reading from temporary archive at `{archive_path}`")]
1985        TempArchiveRead {
1986            /// The archive path for which there was an error.
1987            archive_path: Utf8PathBuf,
1988
1989            /// The error that occurred.
1990            #[source]
1991            error: std::io::Error,
1992        },
1993
1994        /// A checksum mismatch occurred. (Currently, the SHA-256 checksum is checked.)
1995        #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1996        ChecksumMismatch {
1997            /// The expected checksum.
1998            expected: String,
1999
2000            /// The actual checksum.
2001            actual: String,
2002        },
2003
2004        /// An error occurred while renaming a file.
2005        #[error("error renaming `{source}` to `{dest}`")]
2006        FsRename {
2007            /// The rename source.
2008            source: Utf8PathBuf,
2009
2010            /// The rename destination.
2011            dest: Utf8PathBuf,
2012
2013            /// The error that occurred.
2014            #[source]
2015            error: std::io::Error,
2016        },
2017
2018        /// An error occurred while running `cargo nextest self setup`.
2019        #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
2020        SelfSetup(#[source] std::io::Error),
2021    }
2022
2023    fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
2024        use std::fmt::Write;
2025
2026        // Take the first few versions here.
2027        const DISPLAY_COUNT: usize = 4;
2028
2029        let display_versions: Vec<_> = versions
2030            .iter()
2031            .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
2032            .map(|(v, _)| v.to_string())
2033            .take(DISPLAY_COUNT)
2034            .collect();
2035        let mut display_str = display_versions.join(", ");
2036        if versions.len() > display_versions.len() {
2037            write!(
2038                display_str,
2039                " and {} others",
2040                versions.len() - display_versions.len()
2041            )
2042            .unwrap();
2043        }
2044
2045        display_str
2046    }
2047
2048    #[cfg(feature = "self-update")]
2049    /// An error occurred while parsing an [`UpdateVersion`](crate::update::UpdateVersion).
2050    #[derive(Debug, Error)]
2051    pub enum UpdateVersionParseError {
2052        /// The version string is empty.
2053        #[error("version string is empty")]
2054        EmptyString,
2055
2056        /// The input is not a valid version requirement.
2057        #[error(
2058            "`{input}` is not a valid semver requirement\n\
2059                (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
2060        )]
2061        InvalidVersionReq {
2062            /// The input that was provided.
2063            input: String,
2064
2065            /// The error.
2066            #[source]
2067            error: semver::Error,
2068        },
2069
2070        /// The version is not a valid semver.
2071        #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2072        InvalidVersion {
2073            /// The input that was provided.
2074            input: String,
2075
2076            /// The error.
2077            #[source]
2078            error: semver::Error,
2079        },
2080    }
2081
2082    fn extra_semver_output(input: &str) -> String {
2083        // If it is not a valid version but it is a valid version
2084        // requirement, add a note to the warning
2085        if input.parse::<VersionReq>().is_ok() {
2086            format!(
2087                "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2088            )
2089        } else {
2090            "".to_owned()
2091        }
2092    }
2093}
2094
2095#[cfg(feature = "self-update")]
2096pub use self_update_errors::*;
2097
2098#[cfg(test)]
2099mod tests {
2100    use super::*;
2101
2102    #[test]
2103    fn display_error_chain() {
2104        let err1 = StringError::new("err1", None);
2105
2106        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2107
2108        let err2 = StringError::new("err2", Some(err1));
2109        let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2110
2111        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2112        err3
2113        err3 line 2
2114          caused by:
2115          - err2
2116          - err1
2117        ");
2118    }
2119
2120    #[test]
2121    fn display_error_list() {
2122        let err1 = StringError::new("err1", None);
2123
2124        let error_list =
2125            ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2126                .expect(">= 1 error");
2127        insta::assert_snapshot!(format!("{}", error_list), @"err1");
2128        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2129
2130        let err2 = StringError::new("err2", Some(err1));
2131        let err3 = StringError::new("err3", Some(err2));
2132
2133        let error_list =
2134            ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2135                .expect(">= 1 error");
2136        insta::assert_snapshot!(format!("{}", error_list), @"err3");
2137        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2138        err3
2139          caused by:
2140          - err2
2141          - err1
2142        ");
2143
2144        let err4 = StringError::new("err4", None);
2145        let err5 = StringError::new("err5", Some(err4));
2146        let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2147
2148        let error_list = ErrorList::<StringError>::new(
2149            "waiting for the heat death of the universe",
2150            vec![err3, err6],
2151        )
2152        .expect(">= 1 error");
2153
2154        insta::assert_snapshot!(format!("{}", error_list), @r"
2155        2 errors occurred waiting for the heat death of the universe:
2156        * err3
2157            caused by:
2158            - err2
2159            - err1
2160        * err6
2161          err6 line 2
2162            caused by:
2163            - err5
2164            - err4
2165        ");
2166        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2167        2 errors occurred waiting for the heat death of the universe:
2168        * err3
2169            caused by:
2170            - err2
2171            - err1
2172        * err6
2173          err6 line 2
2174            caused by:
2175            - err5
2176            - err4
2177        ");
2178    }
2179
2180    #[derive(Clone, Debug, Error)]
2181    struct StringError {
2182        message: String,
2183        #[source]
2184        source: Option<Box<StringError>>,
2185    }
2186
2187    impl StringError {
2188        fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2189            Self {
2190                message: message.into(),
2191                source: source.map(Box::new),
2192            }
2193        }
2194    }
2195
2196    impl fmt::Display for StringError {
2197        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2198            write!(f, "{}", self.message)
2199        }
2200    }
2201}