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,
10        elements::{CustomTestGroup, TestGroup},
11        scripts::{ProfileScriptType, ScriptId, ScriptType},
12    },
13    helpers::{display_exited_with, dylib_path_envvar},
14    redact::Redactor,
15    reuse_build::{ArchiveFormat, ArchiveStep},
16    target_runner::PlatformRunnerSource,
17};
18use camino::{FromPathBufError, Utf8Path, Utf8PathBuf};
19use config::ConfigError;
20use indent_write::{fmt::IndentWriter, indentable::Indented};
21use itertools::{Either, Itertools};
22use nextest_filtering::errors::FiltersetParseErrors;
23use nextest_metadata::RustBinaryId;
24use smol_str::SmolStr;
25use std::{
26    borrow::Cow,
27    collections::BTreeSet,
28    env::JoinPathsError,
29    fmt::{self, Write as _},
30    process::ExitStatus,
31    sync::Arc,
32};
33use target_spec_miette::IntoMietteDiagnostic;
34use thiserror::Error;
35
36/// 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_deref())
41)]
42#[non_exhaustive]
43pub struct ConfigParseError {
44    config_file: Utf8PathBuf,
45    tool: Option<String>,
46    #[source]
47    kind: ConfigParseErrorKind,
48}
49
50impl ConfigParseError {
51    pub(crate) fn new(
52        config_file: impl Into<Utf8PathBuf>,
53        tool: Option<&str>,
54        kind: ConfigParseErrorKind,
55    ) -> Self {
56        Self {
57            config_file: config_file.into(),
58            tool: tool.map(|s| s.to_owned()),
59            kind,
60        }
61    }
62
63    /// 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<&str> {
70        self.tool.as_deref()
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<&str>) -> 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    #[error(transparent)]
97    /// An error occurred while deserializing the config.
98    DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
99    /// An error occurred while reading the config file (version only).
100    #[error(transparent)]
101    VersionOnlyReadError(std::io::Error),
102    /// An error occurred while deserializing the config (version only).
103    #[error(transparent)]
104    VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
105    /// Errors occurred while compiling configuration strings.
106    #[error("error parsing compiled data (destructure this variant for more details)")]
107    CompileErrors(Vec<ConfigCompileError>),
108    /// An invalid set of test groups was defined by the user.
109    #[error("invalid test groups defined: {}\n(test groups cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
110    InvalidTestGroupsDefined(BTreeSet<CustomTestGroup>),
111    /// An invalid set of test groups was defined by a tool config file.
112    #[error(
113        "invalid test groups defined by tool: {}\n(test groups must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
114    InvalidTestGroupsDefinedByTool(BTreeSet<CustomTestGroup>),
115    /// Some test groups were unknown.
116    #[error("unknown test groups specified by config (destructure this variant for more details)")]
117    UnknownTestGroups {
118        /// The list of errors that occurred.
119        errors: Vec<UnknownTestGroupError>,
120
121        /// Known groups up to this point.
122        known_groups: BTreeSet<TestGroup>,
123    },
124    /// Both `[script.*]` and `[scripts.*]` were defined.
125    #[error(
126        "both `[script.*]` and `[scripts.*]` defined\n\
127         (hint: [script.*] will be removed in the future: switch to [scripts.setup.*])"
128    )]
129    BothScriptAndScriptsDefined,
130    /// An invalid set of config scripts was defined by the user.
131    #[error("invalid config scripts defined: {}\n(config scripts cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
132    InvalidConfigScriptsDefined(BTreeSet<ScriptId>),
133    /// An invalid set of config scripts was defined by a tool config file.
134    #[error(
135        "invalid config scripts defined by tool: {}\n(config scripts must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
136    InvalidConfigScriptsDefinedByTool(BTreeSet<ScriptId>),
137    /// The same config script name was used across config script types.
138    #[error(
139        "config script names used more than once: {}\n\
140         (config script names must be unique across all script types)", .0.iter().join(", ")
141    )]
142    DuplicateConfigScriptNames(BTreeSet<ScriptId>),
143    /// Errors occurred while parsing `[[profile.<profile-name>.scripts]]`.
144    #[error(
145        "errors in profile-specific config scripts (destructure this variant for more details)"
146    )]
147    ProfileScriptErrors {
148        /// The errors that occurred.
149        errors: Box<ProfileScriptErrors>,
150
151        /// Known scripts up to this point.
152        known_scripts: BTreeSet<ScriptId>,
153    },
154    /// An unknown experimental feature or features were defined.
155    #[error("unknown experimental features defined (destructure this variant for more details)")]
156    UnknownExperimentalFeatures {
157        /// The set of unknown features.
158        unknown: BTreeSet<String>,
159
160        /// The set of known features.
161        known: BTreeSet<ConfigExperimental>,
162    },
163    /// A tool specified an experimental feature.
164    ///
165    /// Tools are not allowed to specify experimental features.
166    #[error(
167        "tool config file specifies experimental features `{}` \
168         -- only repository config files can do so",
169        .features.iter().join(", "),
170    )]
171    ExperimentalFeaturesInToolConfig {
172        /// The name of the experimental feature.
173        features: BTreeSet<String>,
174    },
175    /// Experimental features were used but not enabled.
176    #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
177    ExperimentalFeaturesNotEnabled {
178        /// The features that were not enabled.
179        missing_features: BTreeSet<ConfigExperimental>,
180    },
181}
182
183/// An error that occurred while compiling overrides or scripts specified in
184/// configuration.
185#[derive(Debug)]
186#[non_exhaustive]
187pub struct ConfigCompileError {
188    /// The name of the profile under which the data was found.
189    pub profile_name: String,
190
191    /// The section within the profile where the error occurred.
192    pub section: ConfigCompileSection,
193
194    /// The kind of error that occurred.
195    pub kind: ConfigCompileErrorKind,
196}
197
198/// For a [`ConfigCompileError`], the section within the profile where the error
199/// occurred.
200#[derive(Debug)]
201pub enum ConfigCompileSection {
202    /// `profile.<profile-name>.default-filter`.
203    DefaultFilter,
204
205    /// `[[profile.<profile-name>.overrides]]` at the corresponding index.
206    Override(usize),
207
208    /// `[[profile.<profile-name>.scripts]]` at the corresponding index.
209    Script(usize),
210}
211
212/// The kind of error that occurred while parsing config overrides.
213#[derive(Debug)]
214#[non_exhaustive]
215pub enum ConfigCompileErrorKind {
216    /// Neither `platform` nor `filter` were specified.
217    ConstraintsNotSpecified {
218        /// Whether `default-filter` was specified.
219        ///
220        /// If default-filter is specified, then specifying `filter` is not
221        /// allowed -- so we show a different message in that case.
222        default_filter_specified: bool,
223    },
224
225    /// Both `filter` and `default-filter` were specified.
226    ///
227    /// It only makes sense to specify one of the two.
228    FilterAndDefaultFilterSpecified,
229
230    /// One or more errors occured while parsing expressions.
231    Parse {
232        /// A potential error that occurred while parsing the host platform expression.
233        host_parse_error: Option<target_spec::Error>,
234
235        /// A potential error that occurred while parsing the target platform expression.
236        target_parse_error: Option<target_spec::Error>,
237
238        /// Filterset or default filter parse errors.
239        filter_parse_errors: Vec<FiltersetParseErrors>,
240    },
241}
242
243impl ConfigCompileErrorKind {
244    /// Returns [`miette::Report`]s for each error recorded by self.
245    pub fn reports(&self) -> impl Iterator<Item = miette::Report> + '_ {
246        match self {
247            Self::ConstraintsNotSpecified {
248                default_filter_specified,
249            } => {
250                let message = if *default_filter_specified {
251                    "for override with `default-filter`, `platform` must also be specified"
252                } else {
253                    "at least one of `platform` and `filter` must be specified"
254                };
255                Either::Left(std::iter::once(miette::Report::msg(message)))
256            }
257            Self::FilterAndDefaultFilterSpecified => {
258                Either::Left(std::iter::once(miette::Report::msg(
259                    "at most one of `filter` and `default-filter` must be specified",
260                )))
261            }
262            Self::Parse {
263                host_parse_error,
264                target_parse_error,
265                filter_parse_errors,
266            } => {
267                let host_parse_report = host_parse_error
268                    .as_ref()
269                    .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
270                let target_parse_report = target_parse_error
271                    .as_ref()
272                    .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
273                let filter_parse_reports =
274                    filter_parse_errors.iter().flat_map(|filter_parse_errors| {
275                        filter_parse_errors.errors.iter().map(|single_error| {
276                            miette::Report::new(single_error.clone())
277                                .with_source_code(filter_parse_errors.input.to_owned())
278                        })
279                    });
280
281                Either::Right(
282                    host_parse_report
283                        .into_iter()
284                        .chain(target_parse_report)
285                        .chain(filter_parse_reports),
286                )
287            }
288        }
289    }
290}
291
292/// A test priority specified was out of range.
293#[derive(Clone, Debug, Error)]
294#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
295pub struct TestPriorityOutOfRange {
296    /// The priority that was out of range.
297    pub priority: i8,
298}
299
300/// An execution error occurred while attempting to start a test.
301#[derive(Clone, Debug, Error)]
302pub enum ChildStartError {
303    /// An error occurred while creating a temporary path for a setup script.
304    #[error("error creating temporary path for setup script")]
305    TempPath(#[source] Arc<std::io::Error>),
306
307    /// An error occurred while spawning the child process.
308    #[error("error spawning child process")]
309    Spawn(#[source] Arc<std::io::Error>),
310}
311
312/// An error that occurred while reading the output of a setup script.
313#[derive(Clone, Debug, Error)]
314pub enum SetupScriptOutputError {
315    /// An error occurred while opening the setup script environment file.
316    #[error("error opening environment file `{path}`")]
317    EnvFileOpen {
318        /// The path to the environment file.
319        path: Utf8PathBuf,
320
321        /// The underlying error.
322        #[source]
323        error: Arc<std::io::Error>,
324    },
325
326    /// An error occurred while reading the setup script environment file.
327    #[error("error reading environment file `{path}`")]
328    EnvFileRead {
329        /// The path to the environment file.
330        path: Utf8PathBuf,
331
332        /// The underlying error.
333        #[source]
334        error: Arc<std::io::Error>,
335    },
336
337    /// An error occurred while parsing the setup script environment file.
338    #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
339    EnvFileParse {
340        /// The path to the environment file.
341        path: Utf8PathBuf,
342        /// The line at issue.
343        line: String,
344    },
345
346    /// An environment variable key was reserved.
347    #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
348    EnvFileReservedKey {
349        /// The environment variable name.
350        key: String,
351    },
352}
353
354/// A list of errors that implements `Error`.
355///
356/// In the future, we'll likely want to replace this with a `miette::Diagnostic`-based error, since
357/// that supports multiple causes via "related".
358#[derive(Clone, Debug)]
359pub struct ErrorList<T> {
360    // A description of what the errors are.
361    description: &'static str,
362    // Invariant: this list is non-empty.
363    inner: Vec<T>,
364}
365
366impl<T: std::error::Error> ErrorList<T> {
367    pub(crate) fn new<U>(description: &'static str, errors: Vec<U>) -> Option<Self>
368    where
369        T: From<U>,
370    {
371        if errors.is_empty() {
372            None
373        } else {
374            Some(Self {
375                description,
376                inner: errors.into_iter().map(T::from).collect(),
377            })
378        }
379    }
380
381    /// Returns a short summary of the error list.
382    pub(crate) fn short_message(&self) -> String {
383        let string = self.to_string();
384        match string.lines().next() {
385            // Remove a trailing colon if it exists for a better UX.
386            Some(first_line) => first_line.trim_end_matches(':').to_string(),
387            None => String::new(),
388        }
389    }
390
391    pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
392        self.inner.iter()
393    }
394}
395
396impl<T: std::error::Error> fmt::Display for ErrorList<T> {
397    fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
398        // If a single error occurred, pretend that this is just that.
399        if self.inner.len() == 1 {
400            return write!(f, "{}", self.inner[0]);
401        }
402
403        // Otherwise, list all errors.
404        writeln!(
405            f,
406            "{} errors occurred {}:",
407            self.inner.len(),
408            self.description,
409        )?;
410        for error in &self.inner {
411            let mut indent = IndentWriter::new_skip_initial("  ", f);
412            writeln!(indent, "* {}", DisplayErrorChain::new(error))?;
413            f = indent.into_inner();
414        }
415        Ok(())
416    }
417}
418
419impl<T: std::error::Error> std::error::Error for ErrorList<T> {
420    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
421        if self.inner.len() == 1 {
422            self.inner[0].source()
423        } else {
424            // More than one error occurred, so we can't return a single error here. Instead, we
425            // return `None` and display the chain of causes in `fmt::Display`.
426            None
427        }
428    }
429}
430
431/// A wrapper type to display a chain of errors with internal indentation.
432///
433/// This is similar to the display-error-chain crate, but uses IndentWriter
434/// internally to ensure that subsequent lines are also nested.
435pub(crate) struct DisplayErrorChain<E> {
436    error: E,
437    initial_indent: &'static str,
438}
439
440impl<E: std::error::Error> DisplayErrorChain<E> {
441    pub(crate) fn new(error: E) -> Self {
442        Self {
443            error,
444            initial_indent: "",
445        }
446    }
447
448    pub(crate) fn new_with_initial_indent(initial_indent: &'static str, error: E) -> Self {
449        Self {
450            error,
451            initial_indent,
452        }
453    }
454}
455
456impl<E> fmt::Display for DisplayErrorChain<E>
457where
458    E: std::error::Error,
459{
460    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
461        let mut writer = IndentWriter::new(self.initial_indent, f);
462        write!(writer, "{}", self.error)?;
463
464        let Some(mut cause) = self.error.source() else {
465            return Ok(());
466        };
467
468        write!(writer, "\n  caused by:")?;
469
470        loop {
471            writeln!(writer)?;
472            let mut indent = IndentWriter::new_skip_initial("    ", writer);
473            write!(indent, "  - {cause}")?;
474
475            let Some(next_cause) = cause.source() else {
476                break Ok(());
477            };
478
479            cause = next_cause;
480            writer = indent.into_inner();
481        }
482    }
483}
484
485/// An error was returned while managing a child process or reading its output.
486#[derive(Clone, Debug, Error)]
487pub enum ChildError {
488    /// An error occurred while reading from a child file descriptor.
489    #[error(transparent)]
490    Fd(#[from] ChildFdError),
491
492    /// An error occurred while reading the output of a setup script.
493    #[error(transparent)]
494    SetupScriptOutput(#[from] SetupScriptOutputError),
495}
496
497/// An error was returned while reading from child a file descriptor.
498#[derive(Clone, Debug, Error)]
499pub enum ChildFdError {
500    /// An error occurred while reading standard output.
501    #[error("error reading standard output")]
502    ReadStdout(#[source] Arc<std::io::Error>),
503
504    /// An error occurred while reading standard error.
505    #[error("error reading standard error")]
506    ReadStderr(#[source] Arc<std::io::Error>),
507
508    /// An error occurred while reading a combined stream.
509    #[error("error reading combined stream")]
510    ReadCombined(#[source] Arc<std::io::Error>),
511
512    /// An error occurred while waiting for the child process to exit.
513    #[error("error waiting for child process to exit")]
514    Wait(#[source] Arc<std::io::Error>),
515}
516
517/// An unknown test group was specified in the config.
518#[derive(Clone, Debug, Eq, PartialEq)]
519#[non_exhaustive]
520pub struct UnknownTestGroupError {
521    /// The name of the profile under which the unknown test group was found.
522    pub profile_name: String,
523
524    /// The name of the unknown test group.
525    pub name: TestGroup,
526}
527
528/// While parsing profile-specific config scripts, an unknown script was
529/// encountered.
530#[derive(Clone, Debug, Eq, PartialEq)]
531pub struct ProfileUnknownScriptError {
532    /// The name of the profile under which the errors occurred.
533    pub profile_name: String,
534
535    /// The name of the unknown script.
536    pub name: ScriptId,
537}
538
539/// While parsing profile-specific config scripts, a script of the wrong type
540/// was encountered.
541#[derive(Clone, Debug, Eq, PartialEq)]
542pub struct ProfileWrongConfigScriptTypeError {
543    /// The name of the profile under which the errors occurred.
544    pub profile_name: String,
545
546    /// The name of the config script.
547    pub name: ScriptId,
548
549    /// The script type that the user attempted to use the script as.
550    pub attempted: ProfileScriptType,
551
552    /// The script type that the script actually is.
553    pub actual: ScriptType,
554}
555
556/// While parsing profile-specific config scripts, a list-time-enabled script
557/// used a filter that can only be used at test run time.
558#[derive(Clone, Debug, Eq, PartialEq)]
559pub struct ProfileListScriptUsesRunFiltersError {
560    /// The name of the profile under which the errors occurred.
561    pub profile_name: String,
562
563    /// The name of the config script.
564    pub name: ScriptId,
565
566    /// The script type.
567    pub script_type: ProfileScriptType,
568
569    /// The filters that were used.
570    pub filters: BTreeSet<String>,
571}
572
573/// Errors that occurred while parsing `[[profile.*.scripts]]`.
574#[derive(Clone, Debug, Default)]
575pub struct ProfileScriptErrors {
576    /// The list of unknown script errors.
577    pub unknown_scripts: Vec<ProfileUnknownScriptError>,
578
579    /// The list of wrong script type errors.
580    pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
581
582    /// The list of list-time-enabled scripts that used a run-time filter.
583    pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
584}
585
586impl ProfileScriptErrors {
587    /// Returns true if there are no errors recorded.
588    pub fn is_empty(&self) -> bool {
589        self.unknown_scripts.is_empty()
590            && self.wrong_script_types.is_empty()
591            && self.list_scripts_using_run_filters.is_empty()
592    }
593}
594
595/// An error which indicates that a profile was requested but not known to nextest.
596#[derive(Clone, Debug, Error)]
597#[error("profile `{profile} not found (known profiles: {})`", .all_profiles.join(", "))]
598pub struct ProfileNotFound {
599    profile: String,
600    all_profiles: Vec<String>,
601}
602
603impl ProfileNotFound {
604    pub(crate) fn new(
605        profile: impl Into<String>,
606        all_profiles: impl IntoIterator<Item = impl Into<String>>,
607    ) -> Self {
608        let mut all_profiles: Vec<_> = all_profiles.into_iter().map(|s| s.into()).collect();
609        all_profiles.sort_unstable();
610        Self {
611            profile: profile.into(),
612            all_profiles,
613        }
614    }
615}
616
617/// An identifier is invalid.
618#[derive(Clone, Debug, Error, Eq, PartialEq)]
619pub enum InvalidIdentifier {
620    /// The identifier is empty.
621    #[error("identifier is empty")]
622    Empty,
623
624    /// The identifier is not in the correct Unicode format.
625    #[error("invalid identifier `{0}`")]
626    InvalidXid(SmolStr),
627
628    /// This tool identifier doesn't match the expected pattern.
629    #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
630    ToolIdentifierInvalidFormat(SmolStr),
631
632    /// One of the components of this tool identifier is empty.
633    #[error("tool identifier has empty component: `{0}`")]
634    ToolComponentEmpty(SmolStr),
635
636    /// The tool identifier is not in the correct Unicode format.
637    #[error("invalid tool identifier `{0}`")]
638    ToolIdentifierInvalidXid(SmolStr),
639}
640
641/// The name of a test group is invalid (not a valid identifier).
642#[derive(Clone, Debug, Error)]
643#[error("invalid custom test group name: {0}")]
644pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
645
646/// The name of a configuration script is invalid (not a valid identifier).
647#[derive(Clone, Debug, Error)]
648#[error("invalid configuration script name: {0}")]
649pub struct InvalidConfigScriptName(pub InvalidIdentifier);
650
651/// Error returned while parsing a [`ToolConfigFile`](crate::config::core::ToolConfigFile) value.
652#[derive(Clone, Debug, Error)]
653pub enum ToolConfigFileParseError {
654    #[error(
655        "tool-config-file has invalid format: {input}\n(hint: tool configs must be in the format <tool-name>:<path>)"
656    )]
657    /// The input was not in the format "tool:path".
658    InvalidFormat {
659        /// The input that failed to parse.
660        input: String,
661    },
662
663    /// The tool name was empty.
664    #[error("tool-config-file has empty tool name: {input}")]
665    EmptyToolName {
666        /// The input that failed to parse.
667        input: String,
668    },
669
670    /// The config file path was empty.
671    #[error("tool-config-file has empty config file path: {input}")]
672    EmptyConfigFile {
673        /// The input that failed to parse.
674        input: String,
675    },
676
677    /// The config file was not an absolute path.
678    #[error("tool-config-file is not an absolute path: {config_file}")]
679    ConfigFileNotAbsolute {
680        /// The file name that wasn't absolute.
681        config_file: Utf8PathBuf,
682    },
683}
684
685/// Error returned while parsing a [`MaxFail`](crate::config::elements::MaxFail) input.
686#[derive(Clone, Debug, Error)]
687#[error(
688    "unrecognized value for max-fail: {input}\n(hint: expected either a positive integer or \"all\")"
689)]
690pub struct MaxFailParseError {
691    /// The input that failed to parse.
692    pub input: String,
693}
694
695impl MaxFailParseError {
696    pub(crate) fn new(input: impl Into<String>) -> Self {
697        Self {
698            input: input.into(),
699        }
700    }
701}
702
703/// Error returned while parsing a [`StressCount`](crate::runner::StressCount) input.
704#[derive(Clone, Debug, Error)]
705#[error(
706    "unrecognized value for stress-count: {input}\n\
707     (hint: expected either a positive integer or \"infinite\")"
708)]
709pub struct StressCountParseError {
710    /// The input that failed to parse.
711    pub input: String,
712}
713
714impl StressCountParseError {
715    pub(crate) fn new(input: impl Into<String>) -> Self {
716        Self {
717            input: input.into(),
718        }
719    }
720}
721
722/// Error returned while parsing a [`TestThreads`](crate::config::elements::TestThreads) value.
723#[derive(Clone, Debug, Error)]
724#[error(
725    "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
726)]
727pub struct TestThreadsParseError {
728    /// The input that failed to parse.
729    pub input: String,
730}
731
732impl TestThreadsParseError {
733    pub(crate) fn new(input: impl Into<String>) -> Self {
734        Self {
735            input: input.into(),
736        }
737    }
738}
739
740/// An error that occurs while parsing a
741/// [`PartitionerBuilder`](crate::partition::PartitionerBuilder) input.
742#[derive(Clone, Debug, Error)]
743pub struct PartitionerBuilderParseError {
744    expected_format: Option<&'static str>,
745    message: Cow<'static, str>,
746}
747
748impl PartitionerBuilderParseError {
749    pub(crate) fn new(
750        expected_format: Option<&'static str>,
751        message: impl Into<Cow<'static, str>>,
752    ) -> Self {
753        Self {
754            expected_format,
755            message: message.into(),
756        }
757    }
758}
759
760impl fmt::Display for PartitionerBuilderParseError {
761    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762        match self.expected_format {
763            Some(format) => {
764                write!(
765                    f,
766                    "partition must be in the format \"{}\":\n{}",
767                    format, self.message
768                )
769            }
770            None => write!(f, "{}", self.message),
771        }
772    }
773}
774
775/// An error that occurs while operating on a
776/// [`TestFilterBuilder`](crate::test_filter::TestFilterBuilder).
777#[derive(Clone, Debug, Error)]
778pub enum TestFilterBuilderError {
779    /// An error that occurred while constructing test filters.
780    #[error("error constructing test filters")]
781    Construct {
782        /// The underlying error.
783        #[from]
784        error: aho_corasick::BuildError,
785    },
786}
787
788/// An error occurred in [`PathMapper::new`](crate::reuse_build::PathMapper::new).
789#[derive(Debug, Error)]
790pub enum PathMapperConstructError {
791    /// An error occurred while canonicalizing a directory.
792    #[error("{kind} `{input}` failed to canonicalize")]
793    Canonicalization {
794        /// The directory that failed to be canonicalized.
795        kind: PathMapperConstructKind,
796
797        /// The input provided.
798        input: Utf8PathBuf,
799
800        /// The error that occurred.
801        #[source]
802        err: std::io::Error,
803    },
804    /// The canonicalized path isn't valid UTF-8.
805    #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
806    NonUtf8Path {
807        /// The directory that failed to be canonicalized.
808        kind: PathMapperConstructKind,
809
810        /// The input provided.
811        input: Utf8PathBuf,
812
813        /// The underlying error.
814        #[source]
815        err: FromPathBufError,
816    },
817    /// A provided input is not a directory.
818    #[error("{kind} `{canonicalized_path}` is not a directory")]
819    NotADirectory {
820        /// The directory that failed to be canonicalized.
821        kind: PathMapperConstructKind,
822
823        /// The input provided.
824        input: Utf8PathBuf,
825
826        /// The canonicalized path that wasn't a directory.
827        canonicalized_path: Utf8PathBuf,
828    },
829}
830
831impl PathMapperConstructError {
832    /// The kind of directory.
833    pub fn kind(&self) -> PathMapperConstructKind {
834        match self {
835            Self::Canonicalization { kind, .. }
836            | Self::NonUtf8Path { kind, .. }
837            | Self::NotADirectory { kind, .. } => *kind,
838        }
839    }
840
841    /// The input path that failed.
842    pub fn input(&self) -> &Utf8Path {
843        match self {
844            Self::Canonicalization { input, .. }
845            | Self::NonUtf8Path { input, .. }
846            | Self::NotADirectory { input, .. } => input,
847        }
848    }
849}
850
851/// The kind of directory that failed to be read in
852/// [`PathMapper::new`](crate::reuse_build::PathMapper::new).
853///
854/// Returned as part of [`PathMapperConstructError`].
855#[derive(Copy, Clone, Debug, PartialEq, Eq)]
856pub enum PathMapperConstructKind {
857    /// The workspace root.
858    WorkspaceRoot,
859
860    /// The target directory.
861    TargetDir,
862}
863
864impl fmt::Display for PathMapperConstructKind {
865    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
866        match self {
867            Self::WorkspaceRoot => write!(f, "remapped workspace root"),
868            Self::TargetDir => write!(f, "remapped target directory"),
869        }
870    }
871}
872
873/// An error that occurs while parsing Rust build metadata from a summary.
874#[derive(Debug, Error)]
875pub enum RustBuildMetaParseError {
876    /// An error occurred while deserializing the platform.
877    #[error("error deserializing platform from build metadata")]
878    PlatformDeserializeError(#[from] target_spec::Error),
879
880    /// The host platform could not be determined.
881    #[error("the host platform could not be determined")]
882    DetectBuildTargetError(#[source] target_spec::Error),
883
884    /// The build metadata includes features unsupported.
885    #[error("unsupported features in the build metadata: {message}")]
886    Unsupported {
887        /// The detailed error message.
888        message: String,
889    },
890}
891
892/// Error returned when a user-supplied format version fails to be parsed to a
893/// valid and supported version.
894#[derive(Clone, Debug, thiserror::Error)]
895#[error("invalid format version: {input}")]
896pub struct FormatVersionError {
897    /// The input that failed to parse.
898    pub input: String,
899    /// The underlying error.
900    #[source]
901    pub error: FormatVersionErrorInner,
902}
903
904/// The different errors that can occur when parsing and validating a format version.
905#[derive(Clone, Debug, thiserror::Error)]
906pub enum FormatVersionErrorInner {
907    /// The input did not have a valid syntax.
908    #[error("expected format version in form of `{expected}`")]
909    InvalidFormat {
910        /// The expected pseudo format.
911        expected: &'static str,
912    },
913    /// A decimal integer was expected but could not be parsed.
914    #[error("version component `{which}` could not be parsed as an integer")]
915    InvalidInteger {
916        /// Which component was invalid.
917        which: &'static str,
918        /// The parse failure.
919        #[source]
920        err: std::num::ParseIntError,
921    },
922    /// The version component was not within the expected range.
923    #[error("version component `{which}` value {value} is out of range {range:?}")]
924    InvalidValue {
925        /// The component which was out of range.
926        which: &'static str,
927        /// The value that was parsed.
928        value: u8,
929        /// The range of valid values for the component.
930        range: std::ops::Range<u8>,
931    },
932}
933
934/// An error that occurs in [`BinaryList::from_messages`](crate::list::BinaryList::from_messages) or
935/// [`RustTestArtifact::from_binary_list`](crate::list::RustTestArtifact::from_binary_list).
936#[derive(Debug, Error)]
937#[non_exhaustive]
938pub enum FromMessagesError {
939    /// An error occurred while reading Cargo's JSON messages.
940    #[error("error reading Cargo JSON messages")]
941    ReadMessages(#[source] std::io::Error),
942
943    /// An error occurred while querying the package graph.
944    #[error("error querying package graph")]
945    PackageGraph(#[source] guppy::Error),
946
947    /// A target in the package graph was missing `kind` information.
948    #[error("missing kind for target {binary_name} in package {package_name}")]
949    MissingTargetKind {
950        /// The name of the malformed package.
951        package_name: String,
952        /// The name of the malformed target within the package.
953        binary_name: String,
954    },
955}
956
957/// An error that occurs while parsing test list output.
958#[derive(Debug, Error)]
959#[non_exhaustive]
960pub enum CreateTestListError {
961    /// The proposed cwd for a process is not a directory.
962    #[error(
963        "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
964         (hint: ensure project source is available at this location)"
965    )]
966    CwdIsNotDir {
967        /// The binary ID for which the current directory wasn't found.
968        binary_id: RustBinaryId,
969
970        /// The current directory that wasn't found.
971        cwd: Utf8PathBuf,
972    },
973
974    /// Running a command to gather the list of tests failed to execute.
975    #[error(
976        "for `{binary_id}`, running command `{}` failed to execute",
977        shell_words::join(command)
978    )]
979    CommandExecFail {
980        /// The binary ID for which gathering the list of tests failed.
981        binary_id: RustBinaryId,
982
983        /// The command that was run.
984        command: Vec<String>,
985
986        /// The underlying error.
987        #[source]
988        error: std::io::Error,
989    },
990
991    /// Running a command to gather the list of tests failed failed with a non-zero exit code.
992    #[error(
993        "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
994        shell_words::join(command),
995        display_exited_with(*exit_status),
996        String::from_utf8_lossy(stdout),
997        String::from_utf8_lossy(stderr),
998    )]
999    CommandFail {
1000        /// The binary ID for which gathering the list of tests failed.
1001        binary_id: RustBinaryId,
1002
1003        /// The command that was run.
1004        command: Vec<String>,
1005
1006        /// The exit status with which the command failed.
1007        exit_status: ExitStatus,
1008
1009        /// Standard output for the command.
1010        stdout: Vec<u8>,
1011
1012        /// Standard error for the command.
1013        stderr: Vec<u8>,
1014    },
1015
1016    /// Running a command to gather the list of tests produced a non-UTF-8 standard output.
1017    #[error(
1018        "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1019        shell_words::join(command),
1020        String::from_utf8_lossy(stdout),
1021        String::from_utf8_lossy(stderr)
1022    )]
1023    CommandNonUtf8 {
1024        /// The binary ID for which gathering the list of tests failed.
1025        binary_id: RustBinaryId,
1026
1027        /// The command that was run.
1028        command: Vec<String>,
1029
1030        /// Standard output for the command.
1031        stdout: Vec<u8>,
1032
1033        /// Standard error for the command.
1034        stderr: Vec<u8>,
1035    },
1036
1037    /// An error occurred while parsing a line in the test output.
1038    #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1039    ParseLine {
1040        /// The binary ID for which parsing the list of tests failed.
1041        binary_id: RustBinaryId,
1042
1043        /// A descriptive message.
1044        message: Cow<'static, str>,
1045
1046        /// The full output.
1047        full_output: String,
1048    },
1049
1050    /// An error occurred while joining paths for dynamic libraries.
1051    #[error(
1052        "error joining dynamic library paths for {}: [{}]",
1053        dylib_path_envvar(),
1054        itertools::join(.new_paths, ", ")
1055    )]
1056    DylibJoinPaths {
1057        /// New paths attempted to be added to the dynamic library environment variable.
1058        new_paths: Vec<Utf8PathBuf>,
1059
1060        /// The underlying error.
1061        #[source]
1062        error: JoinPathsError,
1063    },
1064
1065    /// Creating a Tokio runtime failed.
1066    #[error("error creating Tokio runtime")]
1067    TokioRuntimeCreate(#[source] std::io::Error),
1068}
1069
1070impl CreateTestListError {
1071    pub(crate) fn parse_line(
1072        binary_id: RustBinaryId,
1073        message: impl Into<Cow<'static, str>>,
1074        full_output: impl Into<String>,
1075    ) -> Self {
1076        Self::ParseLine {
1077            binary_id,
1078            message: message.into(),
1079            full_output: full_output.into(),
1080        }
1081    }
1082
1083    pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1084        Self::DylibJoinPaths { new_paths, error }
1085    }
1086}
1087
1088/// An error that occurs while writing list output.
1089#[derive(Debug, Error)]
1090#[non_exhaustive]
1091pub enum WriteTestListError {
1092    /// An error occurred while writing the list to the provided output.
1093    #[error("error writing to output")]
1094    Io(#[source] std::io::Error),
1095
1096    /// An error occurred while serializing JSON, or while writing it to the provided output.
1097    #[error("error serializing to JSON")]
1098    Json(#[source] serde_json::Error),
1099}
1100
1101/// An error occurred while configuring handles.
1102///
1103/// Only relevant on Windows.
1104#[derive(Debug, Error)]
1105pub enum ConfigureHandleInheritanceError {
1106    /// An error occurred. This can only happen on Windows.
1107    #[cfg(windows)]
1108    #[error("error configuring handle inheritance")]
1109    WindowsError(#[from] std::io::Error),
1110}
1111
1112/// An error that occurs while building the test runner.
1113#[derive(Debug, Error)]
1114#[non_exhaustive]
1115pub enum TestRunnerBuildError {
1116    /// An error occurred while creating the Tokio runtime.
1117    #[error("error creating Tokio runtime")]
1118    TokioRuntimeCreate(#[source] std::io::Error),
1119
1120    /// An error occurred while setting up signals.
1121    #[error("error setting up signals")]
1122    SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1123}
1124
1125/// Errors that occurred while managing test runner Tokio tasks.
1126#[derive(Debug, Error)]
1127pub struct TestRunnerExecuteErrors<E> {
1128    /// An error that occurred while reporting results to the reporter callback.
1129    pub report_error: Option<E>,
1130
1131    /// Join errors (typically panics) that occurred while running the test
1132    /// runner.
1133    pub join_errors: Vec<tokio::task::JoinError>,
1134}
1135
1136impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        if let Some(report_error) = &self.report_error {
1139            write!(f, "error reporting results: {report_error}")?;
1140        }
1141
1142        if !self.join_errors.is_empty() {
1143            if self.report_error.is_some() {
1144                write!(f, "; ")?;
1145            }
1146
1147            write!(f, "errors joining tasks: ")?;
1148
1149            for (i, join_error) in self.join_errors.iter().enumerate() {
1150                if i > 0 {
1151                    write!(f, ", ")?;
1152                }
1153
1154                write!(f, "{join_error}")?;
1155            }
1156        }
1157
1158        Ok(())
1159    }
1160}
1161
1162/// Represents an unknown archive format.
1163///
1164/// Returned by [`ArchiveFormat::autodetect`].
1165#[derive(Debug, Error)]
1166#[error(
1167    "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1168    supported_extensions()
1169)]
1170pub struct UnknownArchiveFormat {
1171    /// The name of the archive file without any leading components.
1172    pub file_name: String,
1173}
1174
1175fn supported_extensions() -> String {
1176    ArchiveFormat::SUPPORTED_FORMATS
1177        .iter()
1178        .map(|(extension, _)| *extension)
1179        .join(", ")
1180}
1181
1182/// An error that occurs while archiving data.
1183#[derive(Debug, Error)]
1184#[non_exhaustive]
1185pub enum ArchiveCreateError {
1186    /// An error occurred while creating the binary list to be written.
1187    #[error("error creating binary list")]
1188    CreateBinaryList(#[source] WriteTestListError),
1189
1190    /// An extra path was missing.
1191    #[error("extra path `{}` not found", .redactor.redact_path(path))]
1192    MissingExtraPath {
1193        /// The path that was missing.
1194        path: Utf8PathBuf,
1195
1196        /// A redactor for the path.
1197        ///
1198        /// (This should eventually move to being a field for a wrapper struct, but it's okay for
1199        /// now.)
1200        redactor: Redactor,
1201    },
1202
1203    /// An error occurred while reading data from a file on disk.
1204    #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1205    InputFileRead {
1206        /// The step that the archive errored at.
1207        step: ArchiveStep,
1208
1209        /// The name of the file that could not be read.
1210        path: Utf8PathBuf,
1211
1212        /// Whether this is a directory. `None` means the status was unknown.
1213        is_dir: Option<bool>,
1214
1215        /// The error that occurred.
1216        #[source]
1217        error: std::io::Error,
1218    },
1219
1220    /// An error occurred while reading entries from a directory on disk.
1221    #[error("error reading directory entry from `{path}")]
1222    DirEntryRead {
1223        /// The name of the directory from which entries couldn't be read.
1224        path: Utf8PathBuf,
1225
1226        /// The error that occurred.
1227        #[source]
1228        error: std::io::Error,
1229    },
1230
1231    /// An error occurred while writing data to the output file.
1232    #[error("error writing to archive")]
1233    OutputArchiveIo(#[source] std::io::Error),
1234
1235    /// An error occurred in the reporter.
1236    #[error("error reporting archive status")]
1237    ReporterIo(#[source] std::io::Error),
1238}
1239
1240fn kind_str(is_dir: Option<bool>) -> &'static str {
1241    match is_dir {
1242        Some(true) => "directory",
1243        Some(false) => "file",
1244        None => "path",
1245    }
1246}
1247
1248/// An error occurred while materializing a metadata path.
1249#[derive(Debug, Error)]
1250pub enum MetadataMaterializeError {
1251    /// An I/O error occurred while reading the metadata file.
1252    #[error("I/O error reading metadata file `{path}`")]
1253    Read {
1254        /// The path that was being read.
1255        path: Utf8PathBuf,
1256
1257        /// The error that occurred.
1258        #[source]
1259        error: std::io::Error,
1260    },
1261
1262    /// A JSON deserialization error occurred while reading the metadata file.
1263    #[error("error deserializing metadata file `{path}`")]
1264    Deserialize {
1265        /// The path that was being read.
1266        path: Utf8PathBuf,
1267
1268        /// The error that occurred.
1269        #[source]
1270        error: serde_json::Error,
1271    },
1272
1273    /// An error occurred while parsing Rust build metadata.
1274    #[error("error parsing Rust build metadata from `{path}`")]
1275    RustBuildMeta {
1276        /// The path that was deserialized.
1277        path: Utf8PathBuf,
1278
1279        /// The error that occurred.
1280        #[source]
1281        error: RustBuildMetaParseError,
1282    },
1283
1284    /// An error occurred converting data into a `PackageGraph`.
1285    #[error("error building package graph from `{path}`")]
1286    PackageGraphConstruct {
1287        /// The path that was deserialized.
1288        path: Utf8PathBuf,
1289
1290        /// The error that occurred.
1291        #[source]
1292        error: guppy::Error,
1293    },
1294}
1295
1296/// An error occurred while reading a file.
1297///
1298/// Returned as part of both [`ArchiveCreateError`] and [`ArchiveExtractError`].
1299#[derive(Debug, Error)]
1300#[non_exhaustive]
1301pub enum ArchiveReadError {
1302    /// An I/O error occurred while reading the archive.
1303    #[error("I/O error reading archive")]
1304    Io(#[source] std::io::Error),
1305
1306    /// A path wasn't valid UTF-8.
1307    #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1308    NonUtf8Path(Vec<u8>),
1309
1310    /// A file path within the archive didn't begin with "target/".
1311    #[error("path in archive `{0}` doesn't start with `target/`")]
1312    NoTargetPrefix(Utf8PathBuf),
1313
1314    /// A file path within the archive had an invalid component within it.
1315    #[error("path in archive `{path}` contains an invalid component `{component}`")]
1316    InvalidComponent {
1317        /// The path that had an invalid component.
1318        path: Utf8PathBuf,
1319
1320        /// The invalid component.
1321        component: String,
1322    },
1323
1324    /// An error occurred while reading a checksum.
1325    #[error("corrupted archive: checksum read error for path `{path}`")]
1326    ChecksumRead {
1327        /// The path for which there was a checksum read error.
1328        path: Utf8PathBuf,
1329
1330        /// The error that occurred.
1331        #[source]
1332        error: std::io::Error,
1333    },
1334
1335    /// An entry had an invalid checksum.
1336    #[error("corrupted archive: invalid checksum for path `{path}`")]
1337    InvalidChecksum {
1338        /// The path that had an invalid checksum.
1339        path: Utf8PathBuf,
1340
1341        /// The expected checksum.
1342        expected: u32,
1343
1344        /// The actual checksum.
1345        actual: u32,
1346    },
1347
1348    /// A metadata file wasn't found.
1349    #[error("metadata file `{0}` not found in archive")]
1350    MetadataFileNotFound(&'static Utf8Path),
1351
1352    /// An error occurred while deserializing a metadata file.
1353    #[error("error deserializing metadata file `{path}` in archive")]
1354    MetadataDeserializeError {
1355        /// The name of the metadata file.
1356        path: &'static Utf8Path,
1357
1358        /// The deserialize error.
1359        #[source]
1360        error: serde_json::Error,
1361    },
1362
1363    /// An error occurred while building a `PackageGraph`.
1364    #[error("error building package graph from `{path}` in archive")]
1365    PackageGraphConstructError {
1366        /// The name of the metadata file.
1367        path: &'static Utf8Path,
1368
1369        /// The error.
1370        #[source]
1371        error: guppy::Error,
1372    },
1373}
1374
1375/// An error occurred while extracting a file.
1376///
1377/// Returned by [`extract_archive`](crate::reuse_build::ReuseBuildInfo::extract_archive).
1378#[derive(Debug, Error)]
1379#[non_exhaustive]
1380pub enum ArchiveExtractError {
1381    /// An error occurred while creating a temporary directory.
1382    #[error("error creating temporary directory")]
1383    TempDirCreate(#[source] std::io::Error),
1384
1385    /// An error occurred while canonicalizing the destination directory.
1386    #[error("error canonicalizing destination directory `{dir}`")]
1387    DestDirCanonicalization {
1388        /// The directory that failed to canonicalize.
1389        dir: Utf8PathBuf,
1390
1391        /// The error that occurred.
1392        #[source]
1393        error: std::io::Error,
1394    },
1395
1396    /// The destination already exists and `--overwrite` was not passed in.
1397    #[error("destination `{0}` already exists")]
1398    DestinationExists(Utf8PathBuf),
1399
1400    /// An error occurred while reading the archive.
1401    #[error("error reading archive")]
1402    Read(#[source] ArchiveReadError),
1403
1404    /// An error occurred while deserializing Rust build metadata.
1405    #[error("error deserializing Rust build metadata")]
1406    RustBuildMeta(#[from] RustBuildMetaParseError),
1407
1408    /// An error occurred while writing out a file to the destination directory.
1409    #[error("error writing file `{path}` to disk")]
1410    WriteFile {
1411        /// The path that we couldn't write out.
1412        path: Utf8PathBuf,
1413
1414        /// The error that occurred.
1415        #[source]
1416        error: std::io::Error,
1417    },
1418
1419    /// An error occurred while reporting the extraction status.
1420    #[error("error reporting extract status")]
1421    ReporterIo(std::io::Error),
1422}
1423
1424/// An error that occurs while writing an event.
1425#[derive(Debug, Error)]
1426#[non_exhaustive]
1427pub enum WriteEventError {
1428    /// An error occurred while writing the event to the provided output.
1429    #[error("error writing to output")]
1430    Io(#[source] std::io::Error),
1431
1432    /// An error occurred while operating on the file system.
1433    #[error("error operating on path {file}")]
1434    Fs {
1435        /// The file being operated on.
1436        file: Utf8PathBuf,
1437
1438        /// The underlying IO error.
1439        #[source]
1440        error: std::io::Error,
1441    },
1442
1443    /// An error occurred while producing JUnit XML.
1444    #[error("error writing JUnit output to {file}")]
1445    Junit {
1446        /// The output file.
1447        file: Utf8PathBuf,
1448
1449        /// The underlying error.
1450        #[source]
1451        error: quick_junit::SerializeError,
1452    },
1453}
1454
1455/// An error occurred while constructing a [`CargoConfigs`](crate::cargo_config::CargoConfigs)
1456/// instance.
1457#[derive(Debug, Error)]
1458#[non_exhaustive]
1459pub enum CargoConfigError {
1460    /// Failed to retrieve the current directory.
1461    #[error("failed to retrieve current directory")]
1462    GetCurrentDir(#[source] std::io::Error),
1463
1464    /// The current directory was invalid UTF-8.
1465    #[error("current directory is invalid UTF-8")]
1466    CurrentDirInvalidUtf8(#[source] FromPathBufError),
1467
1468    /// Parsing a CLI config option failed.
1469    #[error("failed to parse --config argument `{config_str}` as TOML")]
1470    CliConfigParseError {
1471        /// The CLI config option.
1472        config_str: String,
1473
1474        /// The error that occurred trying to parse the config.
1475        #[source]
1476        error: toml_edit::TomlError,
1477    },
1478
1479    /// Deserializing a CLI config option into domain types failed.
1480    #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1481    CliConfigDeError {
1482        /// The CLI config option.
1483        config_str: String,
1484
1485        /// The error that occurred trying to deserialize the config.
1486        #[source]
1487        error: toml_edit::de::Error,
1488    },
1489
1490    /// A CLI config option is not in the dotted key format.
1491    #[error(
1492        "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1493    )]
1494    InvalidCliConfig {
1495        /// The CLI config option.
1496        config_str: String,
1497
1498        /// The reason why this Cargo CLI config is invalid.
1499        #[source]
1500        reason: InvalidCargoCliConfigReason,
1501    },
1502
1503    /// A non-UTF-8 path was encountered.
1504    #[error("non-UTF-8 path encountered")]
1505    NonUtf8Path(#[source] FromPathBufError),
1506
1507    /// Failed to retrieve the Cargo home directory.
1508    #[error("failed to retrieve the Cargo home directory")]
1509    GetCargoHome(#[source] std::io::Error),
1510
1511    /// Failed to canonicalize a path
1512    #[error("failed to canonicalize path `{path}")]
1513    FailedPathCanonicalization {
1514        /// The path that failed to canonicalize
1515        path: Utf8PathBuf,
1516
1517        /// The error the occurred during canonicalization
1518        #[source]
1519        error: std::io::Error,
1520    },
1521
1522    /// Failed to read config file
1523    #[error("failed to read config at `{path}`")]
1524    ConfigReadError {
1525        /// The path of the config file
1526        path: Utf8PathBuf,
1527
1528        /// The error that occurred trying to read the config file
1529        #[source]
1530        error: std::io::Error,
1531    },
1532
1533    /// Failed to deserialize config file
1534    #[error(transparent)]
1535    ConfigParseError(#[from] Box<CargoConfigParseError>),
1536}
1537
1538/// Failed to deserialize config file
1539///
1540/// We introduce this extra indirection, because of the `clippy::result_large_err` rule on Windows.
1541#[derive(Debug, Error)]
1542#[error("failed to parse config at `{path}`")]
1543pub struct CargoConfigParseError {
1544    /// The path of the config file
1545    pub path: Utf8PathBuf,
1546
1547    /// The error that occurred trying to deserialize the config file
1548    #[source]
1549    pub error: toml::de::Error,
1550}
1551
1552/// The reason an invalid CLI config failed.
1553///
1554/// Part of [`CargoConfigError::InvalidCliConfig`].
1555#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1556#[non_exhaustive]
1557pub enum InvalidCargoCliConfigReason {
1558    /// The argument is not a TOML dotted key expression.
1559    #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
1560    NotDottedKv,
1561
1562    /// The argument includes non-whitespace decoration.
1563    #[error("includes non-whitespace decoration")]
1564    IncludesNonWhitespaceDecoration,
1565
1566    /// The argument sets a value to an inline table.
1567    #[error("sets a value to an inline table, which is not accepted")]
1568    SetsValueToInlineTable,
1569
1570    /// The argument sets a value to an array of tables.
1571    #[error("sets a value to an array of tables, which is not accepted")]
1572    SetsValueToArrayOfTables,
1573
1574    /// The argument doesn't provide a value.
1575    #[error("doesn't provide a value")]
1576    DoesntProvideValue,
1577}
1578
1579/// The host platform couldn't be detected.
1580#[derive(Debug, Error)]
1581pub enum HostPlatformDetectError {
1582    /// Spawning `rustc -vV` failed, and detecting the build target failed as
1583    /// well.
1584    #[error(
1585        "error spawning `rustc -vV`, and detecting the build \
1586         target failed as well\n\
1587         - rustc spawn error: {}\n\
1588         - build target error: {}\n",
1589        DisplayErrorChain::new_with_initial_indent("  ", error),
1590        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1591    )]
1592    RustcVvSpawnError {
1593        /// The error.
1594        error: std::io::Error,
1595
1596        /// The error that occurred while detecting the build target.
1597        build_target_error: Box<target_spec::Error>,
1598    },
1599
1600    /// `rustc -vV` exited with a non-zero code, and detecting the build target
1601    /// failed as well.
1602    #[error(
1603        "`rustc -vV` failed with {}, and detecting the \
1604         build target failed as well\n\
1605         - `rustc -vV` stdout:\n{}\n\
1606         - `rustc -vV` stderr:\n{}\n\
1607         - build target error:\n{}\n",
1608        status,
1609        Indented { item: String::from_utf8_lossy(stdout), indent: "  " },
1610        Indented { item: String::from_utf8_lossy(stderr), indent: "  " },
1611        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1612    )]
1613    RustcVvFailed {
1614        /// The status.
1615        status: ExitStatus,
1616
1617        /// The standard output from `rustc -vV`.
1618        stdout: Vec<u8>,
1619
1620        /// The standard error from `rustc -vV`.
1621        stderr: Vec<u8>,
1622
1623        /// The error that occurred while detecting the build target.
1624        build_target_error: Box<target_spec::Error>,
1625    },
1626
1627    /// Parsing the host platform failed, and detecting the build target failed
1628    /// as well.
1629    #[error(
1630        "parsing `rustc -vV` output failed, and detecting the build target \
1631         failed as well\n\
1632         - host platform error:\n{}\n\
1633         - build target error:\n{}\n",
1634        DisplayErrorChain::new_with_initial_indent("  ", host_platform_error),
1635        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
1636    )]
1637    HostPlatformParseError {
1638        /// The error that occurred while parsing the host platform.
1639        host_platform_error: Box<target_spec::Error>,
1640
1641        /// The error that occurred while detecting the build target.
1642        build_target_error: Box<target_spec::Error>,
1643    },
1644
1645    /// Test-only code: `rustc -vV` was not queried, and detecting the build
1646    /// target failed as well.
1647    #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
1648    BuildTargetError {
1649        /// The error that occurred while detecting the build target.
1650        #[source]
1651        build_target_error: Box<target_spec::Error>,
1652    },
1653}
1654
1655/// An error occurred while determining the cross-compiling target triple.
1656#[derive(Debug, Error)]
1657pub enum TargetTripleError {
1658    /// The environment variable contained non-utf8 content
1659    #[error(
1660        "environment variable '{}' contained non-UTF-8 data",
1661        TargetTriple::CARGO_BUILD_TARGET_ENV
1662    )]
1663    InvalidEnvironmentVar,
1664
1665    /// An error occurred while deserializing the platform.
1666    #[error("error deserializing target triple from {source}")]
1667    TargetSpecError {
1668        /// The source from which the triple couldn't be parsed.
1669        source: TargetTripleSource,
1670
1671        /// The error that occurred parsing the triple.
1672        #[source]
1673        error: target_spec::Error,
1674    },
1675
1676    /// For a custom platform, reading the target path failed.
1677    #[error("target path `{path}` is not a valid file")]
1678    TargetPathReadError {
1679        /// The source from which the triple couldn't be parsed.
1680        source: TargetTripleSource,
1681
1682        /// The path that we tried to read.
1683        path: Utf8PathBuf,
1684
1685        /// The error that occurred parsing the triple.
1686        #[source]
1687        error: std::io::Error,
1688    },
1689
1690    /// Failed to create a temporary directory for a custom platform.
1691    #[error(
1692        "for custom platform obtained from {source}, \
1693         failed to create temporary directory for custom platform"
1694    )]
1695    CustomPlatformTempDirError {
1696        /// The source of the target triple.
1697        source: TargetTripleSource,
1698
1699        /// The error that occurred during the create.
1700        #[source]
1701        error: std::io::Error,
1702    },
1703
1704    /// Failed to write a custom platform to disk.
1705    #[error(
1706        "for custom platform obtained from {source}, \
1707         failed to write JSON to temporary path `{path}`"
1708    )]
1709    CustomPlatformWriteError {
1710        /// The source of the target triple.
1711        source: TargetTripleSource,
1712
1713        /// The path that we tried to write to.
1714        path: Utf8PathBuf,
1715
1716        /// The error that occurred during the write.
1717        #[source]
1718        error: std::io::Error,
1719    },
1720
1721    /// Failed to close a temporary directory for an extracted custom platform.
1722    #[error(
1723        "for custom platform obtained from {source}, \
1724         failed to close temporary directory `{dir_path}`"
1725    )]
1726    CustomPlatformCloseError {
1727        /// The source of the target triple.
1728        source: TargetTripleSource,
1729
1730        /// The directory that we tried to delete.
1731        dir_path: Utf8PathBuf,
1732
1733        /// The error that occurred during the close.
1734        #[source]
1735        error: std::io::Error,
1736    },
1737}
1738
1739impl TargetTripleError {
1740    /// Returns a [`miette::Report`] for the source, if available.
1741    ///
1742    /// This should be preferred over [`std::error::Error::source`] if
1743    /// available.
1744    pub fn source_report(&self) -> Option<miette::Report> {
1745        match self {
1746            Self::TargetSpecError { error, .. } => {
1747                Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
1748            }
1749            // The remaining types are covered via the error source path.
1750            TargetTripleError::InvalidEnvironmentVar
1751            | TargetTripleError::TargetPathReadError { .. }
1752            | TargetTripleError::CustomPlatformTempDirError { .. }
1753            | TargetTripleError::CustomPlatformWriteError { .. }
1754            | TargetTripleError::CustomPlatformCloseError { .. } => None,
1755        }
1756    }
1757}
1758
1759/// An error occurred determining the target runner
1760#[derive(Debug, Error)]
1761pub enum TargetRunnerError {
1762    /// An environment variable contained non-utf8 content
1763    #[error("environment variable '{0}' contained non-UTF-8 data")]
1764    InvalidEnvironmentVar(String),
1765
1766    /// An environment variable or config key was found that matches the target
1767    /// triple, but it didn't actually contain a binary
1768    #[error("runner '{key}' = '{value}' did not contain a runner binary")]
1769    BinaryNotSpecified {
1770        /// The source under consideration.
1771        key: PlatformRunnerSource,
1772
1773        /// The value that was read from the key
1774        value: String,
1775    },
1776}
1777
1778/// An error that occurred while setting up the signal handler.
1779#[derive(Debug, Error)]
1780#[error("error setting up signal handler")]
1781pub struct SignalHandlerSetupError(#[from] std::io::Error);
1782
1783/// An error occurred while showing test groups.
1784#[derive(Debug, Error)]
1785pub enum ShowTestGroupsError {
1786    /// Unknown test groups were specified.
1787    #[error(
1788        "unknown test groups specified: {}\n(known groups: {})",
1789        unknown_groups.iter().join(", "),
1790        known_groups.iter().join(", "),
1791    )]
1792    UnknownGroups {
1793        /// The unknown test groups.
1794        unknown_groups: BTreeSet<TestGroup>,
1795
1796        /// All known test groups.
1797        known_groups: BTreeSet<TestGroup>,
1798    },
1799}
1800
1801#[cfg(feature = "self-update")]
1802mod self_update_errors {
1803    use super::*;
1804    use mukti_metadata::ReleaseStatus;
1805    use semver::{Version, VersionReq};
1806
1807    /// An error that occurs while performing a self-update.
1808    ///
1809    /// Returned by methods in the [`update`](crate::update) module.
1810    #[cfg(feature = "self-update")]
1811    #[derive(Debug, Error)]
1812    #[non_exhaustive]
1813    pub enum UpdateError {
1814        /// Failed to read release metadata from a local path on disk.
1815        #[error("failed to read release metadata from `{path}`")]
1816        ReadLocalMetadata {
1817            /// The path that was read.
1818            path: Utf8PathBuf,
1819
1820            /// The error that occurred.
1821            #[source]
1822            error: std::io::Error,
1823        },
1824
1825        /// An error was generated by `self_update`.
1826        #[error("self-update failed")]
1827        SelfUpdate(#[source] self_update::errors::Error),
1828
1829        /// Deserializing release metadata failed.
1830        #[error("deserializing release metadata failed")]
1831        ReleaseMetadataDe(#[source] serde_json::Error),
1832
1833        /// This version was not found.
1834        #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
1835        VersionNotFound {
1836            /// The version that wasn't found.
1837            version: Version,
1838
1839            /// A list of all known versions.
1840            known: Vec<(Version, ReleaseStatus)>,
1841        },
1842
1843        /// No version was found matching a requirement.
1844        #[error("no version found matching requirement `{req}`")]
1845        NoMatchForVersionReq {
1846            /// The version requirement that had no matches.
1847            req: VersionReq,
1848        },
1849
1850        /// The specified mukti project was not found.
1851        #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
1852        MuktiProjectNotFound {
1853            /// The project that was not found.
1854            not_found: String,
1855
1856            /// Known projects.
1857            known: Vec<String>,
1858        },
1859
1860        /// No release information was found for the given target triple.
1861        #[error(
1862            "for version {version}, no release information found for target `{triple}` \
1863            (known targets: {})",
1864            known_triples.iter().join(", ")
1865        )]
1866        NoTargetData {
1867            /// The version that was fetched.
1868            version: Version,
1869
1870            /// The target triple.
1871            triple: String,
1872
1873            /// The triples that were found.
1874            known_triples: BTreeSet<String>,
1875        },
1876
1877        /// The current executable could not be determined.
1878        #[error("the current executable's path could not be determined")]
1879        CurrentExe(#[source] std::io::Error),
1880
1881        /// A temporary directory could not be created.
1882        #[error("temporary directory could not be created at `{location}`")]
1883        TempDirCreate {
1884            /// The location where the temporary directory could not be created.
1885            location: Utf8PathBuf,
1886
1887            /// The error that occurred.
1888            #[source]
1889            error: std::io::Error,
1890        },
1891
1892        /// The temporary archive could not be created.
1893        #[error("temporary archive could not be created at `{archive_path}`")]
1894        TempArchiveCreate {
1895            /// The archive file that couldn't be created.
1896            archive_path: Utf8PathBuf,
1897
1898            /// The error that occurred.
1899            #[source]
1900            error: std::io::Error,
1901        },
1902
1903        /// An error occurred while writing to a temporary archive.
1904        #[error("error writing to temporary archive at `{archive_path}`")]
1905        TempArchiveWrite {
1906            /// The archive path for which there was an error.
1907            archive_path: Utf8PathBuf,
1908
1909            /// The error that occurred.
1910            #[source]
1911            error: std::io::Error,
1912        },
1913
1914        /// An error occurred while reading from a temporary archive.
1915        #[error("error reading from temporary archive at `{archive_path}`")]
1916        TempArchiveRead {
1917            /// The archive path for which there was an error.
1918            archive_path: Utf8PathBuf,
1919
1920            /// The error that occurred.
1921            #[source]
1922            error: std::io::Error,
1923        },
1924
1925        /// A checksum mismatch occurred. (Currently, the SHA-256 checksum is checked.)
1926        #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
1927        ChecksumMismatch {
1928            /// The expected checksum.
1929            expected: String,
1930
1931            /// The actual checksum.
1932            actual: String,
1933        },
1934
1935        /// An error occurred while renaming a file.
1936        #[error("error renaming `{source}` to `{dest}`")]
1937        FsRename {
1938            /// The rename source.
1939            source: Utf8PathBuf,
1940
1941            /// The rename destination.
1942            dest: Utf8PathBuf,
1943
1944            /// The error that occurred.
1945            #[source]
1946            error: std::io::Error,
1947        },
1948
1949        /// An error occurred while running `cargo nextest self setup`.
1950        #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
1951        SelfSetup(#[source] std::io::Error),
1952    }
1953
1954    fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
1955        use std::fmt::Write;
1956
1957        // Take the first few versions here.
1958        const DISPLAY_COUNT: usize = 4;
1959
1960        let display_versions: Vec<_> = versions
1961            .iter()
1962            .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
1963            .map(|(v, _)| v.to_string())
1964            .take(DISPLAY_COUNT)
1965            .collect();
1966        let mut display_str = display_versions.join(", ");
1967        if versions.len() > display_versions.len() {
1968            write!(
1969                display_str,
1970                " and {} others",
1971                versions.len() - display_versions.len()
1972            )
1973            .unwrap();
1974        }
1975
1976        display_str
1977    }
1978
1979    #[cfg(feature = "self-update")]
1980    /// An error occurred while parsing an [`UpdateVersion`](crate::update::UpdateVersion).
1981    #[derive(Debug, Error)]
1982    pub enum UpdateVersionParseError {
1983        /// The version string is empty.
1984        #[error("version string is empty")]
1985        EmptyString,
1986
1987        /// The input is not a valid version requirement.
1988        #[error(
1989            "`{input}` is not a valid semver requirement\n\
1990                (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
1991        )]
1992        InvalidVersionReq {
1993            /// The input that was provided.
1994            input: String,
1995
1996            /// The error.
1997            #[source]
1998            error: semver::Error,
1999        },
2000
2001        /// The version is not a valid semver.
2002        #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
2003        InvalidVersion {
2004            /// The input that was provided.
2005            input: String,
2006
2007            /// The error.
2008            #[source]
2009            error: semver::Error,
2010        },
2011    }
2012
2013    fn extra_semver_output(input: &str) -> String {
2014        // If it is not a valid version but it is a valid version
2015        // requirement, add a note to the warning
2016        if input.parse::<VersionReq>().is_ok() {
2017            format!(
2018                "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
2019            )
2020        } else {
2021            "".to_owned()
2022        }
2023    }
2024}
2025
2026#[cfg(feature = "self-update")]
2027pub use self_update_errors::*;
2028
2029#[cfg(test)]
2030mod tests {
2031    use super::*;
2032
2033    #[test]
2034    fn display_error_chain() {
2035        let err1 = StringError::new("err1", None);
2036
2037        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
2038
2039        let err2 = StringError::new("err2", Some(err1));
2040        let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
2041
2042        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @r"
2043        err3
2044        err3 line 2
2045          caused by:
2046          - err2
2047          - err1
2048        ");
2049    }
2050
2051    #[test]
2052    fn display_error_list() {
2053        let err1 = StringError::new("err1", None);
2054
2055        let error_list =
2056            ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
2057                .expect(">= 1 error");
2058        insta::assert_snapshot!(format!("{}", error_list), @"err1");
2059        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
2060
2061        let err2 = StringError::new("err2", Some(err1));
2062        let err3 = StringError::new("err3", Some(err2));
2063
2064        let error_list =
2065            ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
2066                .expect(">= 1 error");
2067        insta::assert_snapshot!(format!("{}", error_list), @"err3");
2068        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2069        err3
2070          caused by:
2071          - err2
2072          - err1
2073        ");
2074
2075        let err4 = StringError::new("err4", None);
2076        let err5 = StringError::new("err5", Some(err4));
2077        let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
2078
2079        let error_list = ErrorList::<StringError>::new(
2080            "waiting for the heat death of the universe",
2081            vec![err3, err6],
2082        )
2083        .expect(">= 1 error");
2084
2085        insta::assert_snapshot!(format!("{}", error_list), @r"
2086        2 errors occurred waiting for the heat death of the universe:
2087        * err3
2088            caused by:
2089            - err2
2090            - err1
2091        * err6
2092          err6 line 2
2093            caused by:
2094            - err5
2095            - err4
2096        ");
2097        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @r"
2098        2 errors occurred waiting for the heat death of the universe:
2099        * err3
2100            caused by:
2101            - err2
2102            - err1
2103        * err6
2104          err6 line 2
2105            caused by:
2106            - err5
2107            - err4
2108        ");
2109    }
2110
2111    #[derive(Clone, Debug, Error)]
2112    struct StringError {
2113        message: String,
2114        #[source]
2115        source: Option<Box<StringError>>,
2116    }
2117
2118    impl StringError {
2119        fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
2120            Self {
2121                message: message.into(),
2122                source: source.map(Box::new),
2123            }
2124        }
2125    }
2126
2127    impl fmt::Display for StringError {
2128        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2129            write!(f, "{}", self.message)
2130        }
2131    }
2132}