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