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