Skip to main content

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::{
10            ConfigExperimental, ConfigPath, ConfigPathResolveError, ConfigSource, ConfigStyles,
11            NextestConfig, ToolName,
12        },
13        elements::{CustomTestGroup, TestGroup},
14        scripts::{ProfileScriptType, ScriptId, ScriptType},
15    },
16    helpers::{display_exited_with, dylib_path_envvar, plural},
17    indenter::{DisplayIndented, indented},
18    record::{
19        PortableRecordingFormatVersion, PortableRecordingVersionIncompatibility, RecordedRunInfo,
20        RunIdIndex, RunsJsonFormatVersion, StoreFormatVersion, StoreVersionIncompatibility,
21    },
22    redact::{Redactor, SizeDisplay},
23    reuse_build::{ArchiveFormat, ArchiveStep},
24    target_runner::PlatformRunnerSource,
25};
26use bytesize::ByteSize;
27use camino::{FromPathBufError, Utf8Path, Utf8PathBuf};
28use camino_anchored::{CurrentDirError, ResolvePathError};
29use config::ConfigError;
30use eazip::CompressionMethod;
31use etcetera::HomeDirError;
32use itertools::{Either, Itertools};
33use nextest_filtering::errors::FiltersetParseErrors;
34use nextest_metadata::{RustBinaryId, TestCaseName};
35use owo_colors::{OwoColorize, Style};
36use quick_junit::ReportUuid;
37use serde::{Deserialize, Serialize};
38use smol_str::SmolStr;
39use std::{
40    borrow::Cow,
41    collections::BTreeSet,
42    env::JoinPathsError,
43    fmt::{self, Write as _},
44    path::PathBuf,
45    process::ExitStatus,
46    sync::Arc,
47};
48use tar::EntryType;
49use target_spec_miette::IntoMietteDiagnostic;
50use thiserror::Error;
51
52/// An error that occurred while parsing the config.
53#[derive(Debug, Error)]
54#[error("{}", self.display_header(ConfigStyles::default()))]
55#[non_exhaustive]
56pub struct ConfigParseError {
57    config_file: ConfigErrorPath,
58    tool: Option<ToolName>,
59    #[source]
60    kind: ConfigParseErrorKind,
61}
62
63impl ConfigParseError {
64    pub(crate) fn new(source: &ConfigSource, kind: ConfigParseErrorKind) -> Self {
65        Self {
66            config_file: ConfigErrorPath::Resolved(source.path().clone()),
67            tool: source.tool().cloned(),
68            kind,
69        }
70    }
71
72    /// Creates a new `ConfigParseError` for errors not attributable to a single
73    /// source, such as the composite config build.
74    pub(crate) fn from_path(config_file: &ConfigPath, kind: ConfigParseErrorKind) -> Self {
75        Self {
76            config_file: ConfigErrorPath::Resolved(config_file.clone()),
77            tool: None,
78            kind,
79        }
80    }
81
82    pub(crate) fn from_paths_capture_error(
83        workspace_root: &Utf8Path,
84        config_file: Option<&Utf8Path>,
85        error: ConfigPathsCaptureError,
86    ) -> Self {
87        let config_file = match config_file {
88            Some(config_file) => config_file.to_owned(),
89            None => workspace_root.join(NextestConfig::CONFIG_PATH),
90        };
91        Self {
92            config_file: ConfigErrorPath::Unresolved(config_file),
93            tool: None,
94            kind: ConfigParseErrorKind::PathsCaptureError(Box::new(error)),
95        }
96    }
97
98    /// Returns the config file for this error.
99    pub fn config_file(&self) -> &Utf8Path {
100        match &self.config_file {
101            ConfigErrorPath::Resolved(path) => path.absolute_path(),
102            ConfigErrorPath::Unresolved(path) => path,
103        }
104    }
105
106    /// Returns the invocation-relative path for diagnostics.
107    pub fn display_config_file(&self) -> impl fmt::Display + '_ {
108        &self.config_file
109    }
110
111    /// Renders "`path` provided by tool `x`".
112    pub fn display_file(&self, styles: ConfigStyles) -> impl fmt::Display + '_ {
113        DisplayConfigFile {
114            error: self,
115            styles,
116        }
117    }
118
119    /// Renders the full "failed to parse nextest config at ..." heading.
120    ///
121    /// The Display impl is this with no styling.
122    pub fn display_header(&self, styles: ConfigStyles) -> impl fmt::Display + '_ {
123        DisplayConfigHeader {
124            error: self,
125            styles,
126        }
127    }
128
129    /// Returns the tool name associated with this error.
130    pub fn tool(&self) -> Option<&ToolName> {
131        self.tool.as_ref()
132    }
133
134    /// Returns the kind of error this is.
135    pub fn kind(&self) -> &ConfigParseErrorKind {
136        &self.kind
137    }
138}
139
140struct DisplayConfigFile<'a> {
141    error: &'a ConfigParseError,
142    styles: ConfigStyles,
143}
144
145impl fmt::Display for DisplayConfigFile<'_> {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(
148            f,
149            "`{}`{}",
150            self.error.display_config_file().style(self.styles.path),
151            provided_by_tool(self.error.tool(), self.styles.tool),
152        )
153    }
154}
155
156struct DisplayConfigHeader<'a> {
157    error: &'a ConfigParseError,
158    styles: ConfigStyles,
159}
160
161impl fmt::Display for DisplayConfigHeader<'_> {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        write!(
164            f,
165            "failed to parse nextest config at {}",
166            self.error.display_file(self.styles),
167        )
168    }
169}
170
171#[derive(Debug)]
172enum ConfigErrorPath {
173    Resolved(ConfigPath),
174    Unresolved(Utf8PathBuf),
175}
176
177impl fmt::Display for ConfigErrorPath {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        match self {
180            Self::Resolved(path) => fmt::Display::fmt(&path.display(), f),
181            Self::Unresolved(path) => fmt::Display::fmt(path, f),
182        }
183    }
184}
185
186impl From<ConfigPathResolveError> for ConfigParseError {
187    fn from(error: ConfigPathResolveError) -> Self {
188        Self {
189            config_file: ConfigErrorPath::Unresolved(error.path),
190            tool: None,
191            kind: ConfigParseErrorKind::PathResolveError(Box::new(error.error)),
192        }
193    }
194}
195
196/// An error produced by
197/// [`ConfigPaths::capture`](crate::config::core::ConfigPaths::capture).
198#[derive(Debug, Error)]
199pub enum ConfigPathsCaptureError {
200    /// The process's current directory could not be determined.
201    #[error("failed to determine the current directory, which config paths are resolved against")]
202    CurrentDir(#[source] CurrentDirError),
203
204    /// The workspace root could not be resolved against the current directory.
205    #[error("failed to resolve workspace root `{}`", .0.input())]
206    WorkspaceRoot(#[source] ResolvePathError),
207}
208
209/// Renders " provided by tool `x`" when a tool provided the file, and nothing
210/// otherwise.
211pub fn provided_by_tool(tool: Option<&ToolName>, style: Style) -> impl fmt::Display + '_ {
212    ProvidedByTool { tool, style }
213}
214
215struct ProvidedByTool<'a> {
216    tool: Option<&'a ToolName>,
217    style: Style,
218}
219
220impl fmt::Display for ProvidedByTool<'_> {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        match self.tool {
223            Some(tool) => write!(f, " provided by tool `{}`", tool.style(self.style)),
224            None => Ok(()),
225        }
226    }
227}
228
229/// The kind of error that occurred while parsing a config.
230///
231/// Returned by [`ConfigParseError::kind`].
232#[derive(Debug, Error)]
233#[non_exhaustive]
234pub enum ConfigParseErrorKind {
235    /// An input path could not be resolved to an absolute location.
236    #[error("error resolving the configuration path")]
237    PathResolveError(#[source] Box<ResolvePathError>),
238    /// The current directory or workspace root could not be determined.
239    #[error(transparent)]
240    PathsCaptureError(Box<ConfigPathsCaptureError>),
241    /// An error occurred while building the config.
242    #[error(transparent)]
243    BuildError(Box<ConfigError>),
244    /// An error occurred while parsing the config into a table.
245    #[error(transparent)]
246    TomlParseError(Box<toml::de::Error>),
247    #[error(transparent)]
248    /// An error occurred while deserializing the config.
249    DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
250    /// An error occurred while reading a config file.
251    #[error(transparent)]
252    ReadError(std::io::Error),
253    /// An error occurred while deserializing the config (version only).
254    #[error(transparent)]
255    VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
256    /// Errors occurred while compiling configuration strings.
257    #[error("error parsing compiled data (destructure this variant for more details)")]
258    CompileErrors(Vec<ConfigCompileError>),
259    /// An invalid set of test groups was defined by the user.
260    #[error("invalid test groups defined: {}\n(test groups cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
261    InvalidTestGroupsDefined(BTreeSet<CustomTestGroup>),
262    /// An invalid set of test groups was defined by a tool config file.
263    #[error(
264        "invalid test groups defined by tool: {}\n(test groups must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
265    InvalidTestGroupsDefinedByTool(BTreeSet<CustomTestGroup>),
266    /// Some test groups were unknown.
267    #[error("unknown test groups specified by config (destructure this variant for more details)")]
268    UnknownTestGroups {
269        /// The list of errors that occurred.
270        errors: Vec<UnknownTestGroupError>,
271
272        /// Known groups up to this point.
273        known_groups: BTreeSet<TestGroup>,
274    },
275    /// Both `[script.*]` and `[scripts.*]` were defined.
276    #[error(
277        "both `[script.*]` and `[scripts.*]` defined\n\
278         (hint: [script.*] will be removed in the future: switch to [scripts.setup.*])"
279    )]
280    BothScriptAndScriptsDefined,
281    /// An invalid set of config scripts was defined by the user.
282    #[error("invalid config scripts defined: {}\n(config scripts cannot start with '@tool:' unless specified by a tool)", .0.iter().join(", "))]
283    InvalidConfigScriptsDefined(BTreeSet<ScriptId>),
284    /// An invalid set of config scripts was defined by a tool config file.
285    #[error(
286        "invalid config scripts defined by tool: {}\n(config scripts must start with '@tool:<tool-name>:')", .0.iter().join(", "))]
287    InvalidConfigScriptsDefinedByTool(BTreeSet<ScriptId>),
288    /// The same config script name was used across config script types.
289    #[error(
290        "config script names used more than once: {}\n\
291         (config script names must be unique across all script types)", .0.iter().join(", ")
292    )]
293    DuplicateConfigScriptNames(BTreeSet<ScriptId>),
294    /// Errors occurred while parsing `[[profile.<profile-name>.scripts]]`.
295    #[error(
296        "errors in profile-specific config scripts (destructure this variant for more details)"
297    )]
298    ProfileScriptErrors {
299        /// The errors that occurred.
300        errors: Box<ProfileScriptErrors>,
301
302        /// Known scripts up to this point.
303        known_scripts: BTreeSet<ScriptId>,
304    },
305    /// An unknown experimental feature or features were defined.
306    #[error("unknown experimental features defined (destructure this variant for more details)")]
307    UnknownExperimentalFeatures {
308        /// The set of unknown features.
309        unknown: BTreeSet<String>,
310
311        /// The set of known features.
312        known: BTreeSet<ConfigExperimental>,
313    },
314    /// A tool specified an experimental feature.
315    ///
316    /// Tools are not allowed to specify experimental features.
317    #[error(
318        "tool config file specifies experimental features `{}` \
319         -- only repository config files can do so",
320        .features.iter().join(", "),
321    )]
322    ExperimentalFeaturesInToolConfig {
323        /// The name of the experimental feature.
324        features: BTreeSet<String>,
325    },
326    /// Experimental features were used but not enabled.
327    #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
328    ExperimentalFeaturesNotEnabled {
329        /// The features that were not enabled.
330        missing_features: BTreeSet<ConfigExperimental>,
331    },
332    /// An inheritance cycle was detected in the profile configuration.
333    #[error("inheritance error(s) detected: {}", .0.iter().join(", "))]
334    InheritanceErrors(Vec<InheritsError>),
335    /// A tool provided more than one config file.
336    #[error(
337        "tool `{tool}` already provided config file `{}`\n\
338         (hint: each tool can provide at most one config file: merge the files, \
339         or pass `--tool-config-file {tool}:<path>` only once)",
340        .first.display(),
341    )]
342    DuplicateToolConfigFile {
343        /// The tool that passed more than one file.
344        tool: ToolName,
345        /// The file from the earlier, higher-priority argument.
346        first: ConfigPath,
347    },
348}
349
350impl From<ConfigError> for ConfigParseErrorKind {
351    fn from(error: ConfigError) -> Self {
352        ConfigParseErrorKind::BuildError(Box::new(error))
353    }
354}
355
356/// An error that occurred while compiling overrides or scripts specified in
357/// configuration.
358#[derive(Debug)]
359#[non_exhaustive]
360pub struct ConfigCompileError {
361    /// The name of the profile under which the data was found.
362    pub profile_name: String,
363
364    /// The section within the profile where the error occurred.
365    pub section: ConfigCompileSection,
366
367    /// The kind of error that occurred.
368    pub kind: ConfigCompileErrorKind,
369}
370
371/// For a [`ConfigCompileError`], the section within the profile where the error
372/// occurred.
373#[derive(Debug)]
374pub enum ConfigCompileSection {
375    /// `profile.<profile-name>.default-filter`.
376    DefaultFilter,
377
378    /// `[[profile.<profile-name>.overrides]]` at the corresponding index.
379    Override(usize),
380
381    /// `[[profile.<profile-name>.scripts]]` at the corresponding index.
382    Script(usize),
383}
384
385/// The kind of error that occurred while parsing config overrides.
386#[derive(Debug)]
387#[non_exhaustive]
388pub enum ConfigCompileErrorKind {
389    /// Neither `platform` nor `filter` were specified.
390    ConstraintsNotSpecified {
391        /// Whether `default-filter` was specified.
392        ///
393        /// If default-filter is specified, then specifying `filter` is not
394        /// allowed -- so we show a different message in that case.
395        default_filter_specified: bool,
396    },
397
398    /// Both `filter` and `default-filter` were specified.
399    ///
400    /// It only makes sense to specify one of the two.
401    FilterAndDefaultFilterSpecified,
402
403    /// One or more errors occurred while parsing expressions.
404    Parse {
405        /// A potential error that occurred while parsing the host platform expression.
406        host_parse_error: Option<target_spec::Error>,
407
408        /// A potential error that occurred while parsing the target platform expression.
409        target_parse_error: Option<target_spec::Error>,
410
411        /// Filterset or default filter parse errors.
412        filter_parse_errors: Vec<FiltersetParseErrors>,
413    },
414}
415
416impl ConfigCompileErrorKind {
417    /// Returns [`miette::Report`]s for each error recorded by self.
418    pub fn reports(&self) -> impl Iterator<Item = miette::Report> + '_ {
419        match self {
420            Self::ConstraintsNotSpecified {
421                default_filter_specified,
422            } => {
423                let message = if *default_filter_specified {
424                    "for override with `default-filter`, `platform` must also be specified"
425                } else {
426                    "at least one of `platform` and `filter` must be specified"
427                };
428                Either::Left(std::iter::once(miette::Report::msg(message)))
429            }
430            Self::FilterAndDefaultFilterSpecified => {
431                Either::Left(std::iter::once(miette::Report::msg(
432                    "at most one of `filter` and `default-filter` must be specified",
433                )))
434            }
435            Self::Parse {
436                host_parse_error,
437                target_parse_error,
438                filter_parse_errors,
439            } => {
440                let host_parse_report = host_parse_error
441                    .as_ref()
442                    .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
443                let target_parse_report = target_parse_error
444                    .as_ref()
445                    .map(|error| miette::Report::new_boxed(error.clone().into_diagnostic()));
446                let filter_parse_reports =
447                    filter_parse_errors.iter().flat_map(|filter_parse_errors| {
448                        filter_parse_errors.errors.iter().map(|single_error| {
449                            miette::Report::new(single_error.clone())
450                                .with_source_code(filter_parse_errors.input.to_owned())
451                        })
452                    });
453
454                Either::Right(
455                    host_parse_report
456                        .into_iter()
457                        .chain(target_parse_report)
458                        .chain(filter_parse_reports),
459                )
460            }
461        }
462    }
463}
464
465/// A test priority specified was out of range.
466#[derive(Clone, Debug, Error)]
467#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
468pub struct TestPriorityOutOfRange {
469    /// The priority that was out of range.
470    pub priority: i8,
471}
472
473/// An execution error occurred while attempting to start a test.
474#[derive(Clone, Debug, Error)]
475pub enum ChildStartError {
476    /// An error occurred while creating a temporary path for a setup script.
477    #[error("error creating temporary path for setup script")]
478    TempPath(#[source] Arc<std::io::Error>),
479
480    /// An error occurred while spawning the child process.
481    #[error("error spawning child process")]
482    Spawn(#[source] Arc<std::io::Error>),
483}
484
485/// An error that occurred while reading the output of a setup script.
486#[derive(Clone, Debug, Error)]
487pub enum SetupScriptOutputError {
488    /// An error occurred while opening the setup script environment file.
489    #[error("error opening environment file `{path}`")]
490    EnvFileOpen {
491        /// The path to the environment file.
492        path: Utf8PathBuf,
493
494        /// The underlying error.
495        #[source]
496        error: Arc<std::io::Error>,
497    },
498
499    /// An error occurred while reading the setup script environment file.
500    #[error("error reading environment file `{path}`")]
501    EnvFileRead {
502        /// The path to the environment file.
503        path: Utf8PathBuf,
504
505        /// The underlying error.
506        #[source]
507        error: Arc<std::io::Error>,
508    },
509
510    /// An error occurred while parsing the setup script environment file.
511    #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
512    EnvFileParse {
513        /// The path to the environment file.
514        path: Utf8PathBuf,
515        /// The line at issue.
516        line: String,
517    },
518
519    /// An environment variable key in the environment file was invalid.
520    #[error("error in environment file `{path}`")]
521    EnvFileInvalidKey {
522        /// The path to the environment file.
523        path: Utf8PathBuf,
524
525        /// The underlying error.
526        #[source]
527        error: EnvVarError,
528    },
529}
530
531/// An error that describes an invalid/reserved key or value in an environment variable.
532#[derive(Clone, Debug, Error)]
533pub enum EnvVarError {
534    /// An environment variable key was reserved.
535    #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
536    ReservedKey {
537        /// The environment variable name.
538        key: String,
539    },
540
541    // See: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html
542    /// An environment variable key is invalid.
543    #[error("key `{key}` does not consist solely of letters, digits, and underscores")]
544    InvalidKey {
545        /// The environment variable name.
546        key: String,
547    },
548
549    /// An environment variable key is invalid.
550    #[error("key `{key}` does not start with a letter or underscore")]
551    InvalidKeyStartChar {
552        /// The environment variable name.
553        key: String,
554    },
555}
556
557// `Display` messages are phrased as statements ("key X does not..."), but
558// `serde::de::Expected` needs them as expectations ("a key that..."). This impl
559// provides the expected-form messages for use with `invalid_value`.
560impl serde::de::Expected for EnvVarError {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        f.write_str(match self {
563            Self::ReservedKey { .. } => {
564                "a key that does not begin with `NEXTEST`, which is reserved for internal use"
565            }
566            Self::InvalidKey { .. } => {
567                "a key that consists solely of letters, digits, and underscores"
568            }
569            Self::InvalidKeyStartChar { .. } => "a key that starts with a letter or underscore",
570        })
571    }
572}
573
574/// A list of errors that implements `Error`.
575///
576/// In the future, we'll likely want to replace this with a `miette::Diagnostic`-based error, since
577/// that supports multiple causes via "related".
578#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
579pub struct ErrorList<T> {
580    // A description of what the errors are.
581    description: Cow<'static, str>,
582    // Invariant: this list is non-empty.
583    inner: Vec<T>,
584}
585
586impl<T: std::error::Error> ErrorList<T> {
587    pub(crate) fn new<U>(description: &'static str, errors: Vec<U>) -> Option<Self>
588    where
589        T: From<U>,
590    {
591        if errors.is_empty() {
592            None
593        } else {
594            Some(Self {
595                description: Cow::Borrowed(description),
596                inner: errors.into_iter().map(T::from).collect(),
597            })
598        }
599    }
600
601    /// Returns a short summary of the error list.
602    pub(crate) fn short_message(&self) -> String {
603        let string = self.to_string();
604        match string.lines().next() {
605            // Remove a trailing colon if it exists for a better UX.
606            Some(first_line) => first_line.trim_end_matches(':').to_string(),
607            None => String::new(),
608        }
609    }
610
611    /// Returns the description of what the errors are.
612    pub fn description(&self) -> &str {
613        &self.description
614    }
615
616    /// Iterates over the errors in this list.
617    pub fn iter(&self) -> impl Iterator<Item = &T> {
618        self.inner.iter()
619    }
620
621    /// Transforms the errors in this list using the given function.
622    pub fn map<U, F>(self, f: F) -> ErrorList<U>
623    where
624        U: std::error::Error,
625        F: FnMut(T) -> U,
626    {
627        ErrorList {
628            description: self.description,
629            inner: self.inner.into_iter().map(f).collect(),
630        }
631    }
632}
633
634impl<T: std::error::Error> IntoIterator for ErrorList<T> {
635    type Item = T;
636    type IntoIter = std::vec::IntoIter<T>;
637
638    fn into_iter(self) -> Self::IntoIter {
639        self.inner.into_iter()
640    }
641}
642
643impl<T: std::error::Error> fmt::Display for ErrorList<T> {
644    fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
645        // If a single error occurred, pretend that this is just that.
646        if self.inner.len() == 1 {
647            return write!(f, "{}", self.inner[0]);
648        }
649
650        // Otherwise, list all errors.
651        writeln!(
652            f,
653            "{} errors occurred {}:",
654            self.inner.len(),
655            self.description,
656        )?;
657        for error in &self.inner {
658            let mut indent = indented(f).with_str("  ").skip_initial();
659            writeln!(indent, "* {}", DisplayErrorChain::new(error))?;
660            f = indent.into_inner();
661        }
662        Ok(())
663    }
664}
665
666#[cfg(test)]
667impl<T: proptest::arbitrary::Arbitrary + std::fmt::Debug + 'static> proptest::arbitrary::Arbitrary
668    for ErrorList<T>
669{
670    type Parameters = ();
671    type Strategy = proptest::strategy::BoxedStrategy<Self>;
672
673    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
674        use proptest::prelude::*;
675
676        // Generate 1-5 errors (non-empty).
677        proptest::collection::vec(any::<T>(), 1..=5)
678            .prop_map(|inner| ErrorList {
679                description: Cow::Borrowed("test errors"),
680                inner,
681            })
682            .boxed()
683    }
684}
685
686impl<T: std::error::Error> std::error::Error for ErrorList<T> {
687    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
688        if self.inner.len() == 1 {
689            self.inner[0].source()
690        } else {
691            // More than one error occurred, so we can't return a single error here. Instead, we
692            // return `None` and display the chain of causes in `fmt::Display`.
693            None
694        }
695    }
696}
697
698/// A wrapper type to display a chain of errors with internal indentation.
699///
700/// This is similar to the display-error-chain crate, but uses an indenter
701/// internally to ensure that subsequent lines are also nested.
702pub struct DisplayErrorChain<E> {
703    error: E,
704    initial_indent: &'static str,
705}
706
707impl<E: std::error::Error> DisplayErrorChain<E> {
708    /// Creates a new `DisplayErrorChain` with the given error.
709    pub fn new(error: E) -> Self {
710        Self {
711            error,
712            initial_indent: "",
713        }
714    }
715
716    /// Creates a new `DisplayErrorChain` with the given error and initial indentation.
717    pub fn new_with_initial_indent(initial_indent: &'static str, error: E) -> Self {
718        Self {
719            error,
720            initial_indent,
721        }
722    }
723}
724
725impl<E> fmt::Display for DisplayErrorChain<E>
726where
727    E: std::error::Error,
728{
729    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730        let mut writer = indented(f).with_str(self.initial_indent);
731        write!(writer, "{}", self.error)?;
732
733        let Some(mut cause) = self.error.source() else {
734            return Ok(());
735        };
736
737        write!(writer, "\n  caused by:")?;
738
739        loop {
740            writeln!(writer)?;
741            // Wrap the existing writer to accumulate indentation.
742            let mut indent = indented(&mut writer).with_str("    ").skip_initial();
743            write!(indent, "  - {cause}")?;
744
745            let Some(next_cause) = cause.source() else {
746                break Ok(());
747            };
748
749            cause = next_cause;
750        }
751    }
752}
753
754/// An error was returned while managing a child process or reading its output.
755#[derive(Clone, Debug, Error)]
756pub enum ChildError {
757    /// An error occurred while reading from a child file descriptor.
758    #[error(transparent)]
759    Fd(#[from] ChildFdError),
760
761    /// An error occurred while reading the output of a setup script.
762    #[error(transparent)]
763    SetupScriptOutput(#[from] SetupScriptOutputError),
764}
765
766/// An error was returned while reading from child a file descriptor.
767#[derive(Clone, Debug, Error)]
768pub enum ChildFdError {
769    /// An error occurred while reading standard output.
770    #[error("error reading standard output")]
771    ReadStdout(#[source] Arc<std::io::Error>),
772
773    /// An error occurred while reading standard error.
774    #[error("error reading standard error")]
775    ReadStderr(#[source] Arc<std::io::Error>),
776
777    /// An error occurred while reading a combined stream.
778    #[error("error reading combined stream")]
779    ReadCombined(#[source] Arc<std::io::Error>),
780
781    /// An error occurred while waiting for the child process to exit.
782    #[error("error waiting for child process to exit")]
783    Wait(#[source] Arc<std::io::Error>),
784}
785
786/// An unknown test group was specified in the config.
787#[derive(Clone, Debug, Eq, PartialEq)]
788#[non_exhaustive]
789pub struct UnknownTestGroupError {
790    /// The name of the profile under which the unknown test group was found.
791    pub profile_name: String,
792
793    /// The name of the unknown test group.
794    pub name: TestGroup,
795}
796
797/// While parsing profile-specific config scripts, an unknown script was
798/// encountered.
799#[derive(Clone, Debug, Eq, PartialEq)]
800pub struct ProfileUnknownScriptError {
801    /// The name of the profile under which the errors occurred.
802    pub profile_name: String,
803
804    /// The name of the unknown script.
805    pub name: ScriptId,
806}
807
808/// While parsing profile-specific config scripts, a script of the wrong type
809/// was encountered.
810#[derive(Clone, Debug, Eq, PartialEq)]
811pub struct ProfileWrongConfigScriptTypeError {
812    /// The name of the profile under which the errors occurred.
813    pub profile_name: String,
814
815    /// The name of the config script.
816    pub name: ScriptId,
817
818    /// The script type that the user attempted to use the script as.
819    pub attempted: ProfileScriptType,
820
821    /// The script type that the script actually is.
822    pub actual: ScriptType,
823}
824
825/// While parsing profile-specific config scripts, a list-time-enabled script
826/// used a filter that can only be used at test run time.
827#[derive(Clone, Debug, Eq, PartialEq)]
828pub struct ProfileListScriptUsesRunFiltersError {
829    /// The name of the profile under which the errors occurred.
830    pub profile_name: String,
831
832    /// The name of the config script.
833    pub name: ScriptId,
834
835    /// The script type.
836    pub script_type: ProfileScriptType,
837
838    /// The filters that were used.
839    pub filters: BTreeSet<String>,
840}
841
842/// Errors that occurred while parsing `[[profile.*.scripts]]`.
843#[derive(Clone, Debug, Default)]
844pub struct ProfileScriptErrors {
845    /// The list of unknown script errors.
846    pub unknown_scripts: Vec<ProfileUnknownScriptError>,
847
848    /// The list of wrong script type errors.
849    pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
850
851    /// The list of list-time-enabled scripts that used a run-time filter.
852    pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
853}
854
855impl ProfileScriptErrors {
856    /// Returns true if there are no errors recorded.
857    pub fn is_empty(&self) -> bool {
858        self.unknown_scripts.is_empty()
859            && self.wrong_script_types.is_empty()
860            && self.list_scripts_using_run_filters.is_empty()
861    }
862}
863
864/// An error which indicates that a profile was requested but not known to nextest.
865#[derive(Clone, Debug, Error)]
866#[error("profile `{profile}` not found (known profiles: {})", .all_profiles.join(", "))]
867pub struct ProfileNotFound {
868    profile: String,
869    all_profiles: Vec<String>,
870}
871
872impl ProfileNotFound {
873    pub(crate) fn new(
874        profile: impl Into<String>,
875        all_profiles: impl IntoIterator<Item = impl Into<String>>,
876    ) -> Self {
877        let mut all_profiles: Vec<_> = all_profiles.into_iter().map(|s| s.into()).collect();
878        all_profiles.sort_unstable();
879        Self {
880            profile: profile.into(),
881            all_profiles,
882        }
883    }
884}
885
886/// An identifier is invalid.
887#[derive(Clone, Debug, Error, Eq, PartialEq)]
888pub enum InvalidIdentifier {
889    /// The identifier is empty.
890    #[error("identifier is empty")]
891    Empty,
892
893    /// The identifier is not in the correct Unicode format.
894    #[error("invalid identifier `{0}`")]
895    InvalidXid(SmolStr),
896
897    /// This tool identifier doesn't match the expected pattern.
898    #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
899    ToolIdentifierInvalidFormat(SmolStr),
900
901    /// One of the components of this tool identifier is empty.
902    #[error("tool identifier has empty component: `{0}`")]
903    ToolComponentEmpty(SmolStr),
904
905    /// The tool identifier is not in the correct Unicode format.
906    #[error("invalid tool identifier `{0}`")]
907    ToolIdentifierInvalidXid(SmolStr),
908}
909
910/// A tool name is invalid.
911#[derive(Clone, Debug, Error, Eq, PartialEq)]
912pub enum InvalidToolName {
913    /// The tool name is empty.
914    #[error("tool name is empty")]
915    Empty,
916
917    /// The tool name is not in the correct Unicode format.
918    #[error("invalid tool name `{0}`")]
919    InvalidXid(SmolStr),
920
921    /// The tool name starts with "@tool", which is reserved for tool identifiers.
922    #[error("tool name cannot start with \"@tool\": `{0}`")]
923    StartsWithToolPrefix(SmolStr),
924}
925
926/// The name of a test group is invalid (not a valid identifier).
927#[derive(Clone, Debug, Error)]
928#[error("invalid custom test group name: {0}")]
929pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
930
931/// The name of a configuration script is invalid (not a valid identifier).
932#[derive(Clone, Debug, Error)]
933#[error("invalid configuration script name: {0}")]
934pub struct InvalidConfigScriptName(pub InvalidIdentifier);
935
936/// An error that occurred while constructing a
937/// [`PackageSpec`](crate::build_scope::PackageSpec).
938#[derive(Clone, Debug, Error, PartialEq, Eq)]
939#[error("invalid package spec `{}`: {kind}", .spec.escape_debug())]
940pub struct PackageSpecError {
941    spec: String,
942    kind: PackageSpecErrorKind,
943}
944
945impl PackageSpecError {
946    /// Returns the raw package spec string that caused this error.
947    pub fn spec(&self) -> &str {
948        &self.spec
949    }
950
951    /// Returns the kind of error that occurred.
952    pub fn kind(&self) -> &PackageSpecErrorKind {
953        &self.kind
954    }
955}
956
957/// The kind of error that occurred while constructing a
958/// [`PackageSpec`](crate::build_scope::PackageSpec).
959///
960/// Returned by [`PackageSpecError::kind`].
961///
962/// This is uninhabited until package spec validation lands.
963#[derive(Clone, Debug, Error, PartialEq, Eq)]
964pub enum PackageSpecErrorKind {}
965
966/// Error returned while parsing a [`ToolConfigFile`](crate::config::core::ToolConfigFile) value.
967#[derive(Clone, Debug, Error, PartialEq, Eq)]
968pub enum ToolConfigFileParseError {
969    #[error(
970        "tool-config-file has invalid format: {input}\n(hint: tool configs must be in the format <tool-name>:<path>)"
971    )]
972    /// The input was not in the format "tool:path".
973    InvalidFormat {
974        /// The input that failed to parse.
975        input: String,
976    },
977
978    /// The tool name was invalid.
979    #[error("tool-config-file has invalid tool name: {input}")]
980    InvalidToolName {
981        /// The input that failed to parse.
982        input: String,
983
984        /// The error that occurred.
985        #[source]
986        error: InvalidToolName,
987    },
988
989    /// The config file path was empty.
990    #[error("tool-config-file has empty config file path: {input}")]
991    EmptyConfigFile {
992        /// The input that failed to parse.
993        input: String,
994    },
995
996    /// The config file was not an absolute path.
997    #[error("tool-config-file is not an absolute path: {config_file}")]
998    ConfigFileNotAbsolute {
999        /// The file name that wasn't absolute.
1000        config_file: Utf8PathBuf,
1001    },
1002}
1003
1004/// Errors that can occur while loading user config.
1005#[derive(Debug, Error)]
1006#[non_exhaustive]
1007pub enum UserConfigError {
1008    /// The user config file specified via `--user-config-file` or
1009    /// `NEXTEST_USER_CONFIG_FILE` does not exist.
1010    #[error("user config file not found at {path}")]
1011    FileNotFound {
1012        /// The path that was specified.
1013        path: Utf8PathBuf,
1014    },
1015
1016    /// Failed to read the user config file.
1017    #[error("failed to read user config at {path}")]
1018    Read {
1019        /// The path to the config file.
1020        path: Utf8PathBuf,
1021        /// The underlying I/O error.
1022        #[source]
1023        error: std::io::Error,
1024    },
1025
1026    /// Failed to parse the user config file.
1027    #[error("failed to parse user config at {path}")]
1028    Parse {
1029        /// The path to the config file.
1030        path: Utf8PathBuf,
1031        /// The underlying TOML parse error.
1032        #[source]
1033        error: toml::de::Error,
1034    },
1035
1036    /// The user config path contains non-UTF-8 characters.
1037    #[error("user config path contains non-UTF-8 characters")]
1038    NonUtf8Path {
1039        /// The underlying error from path conversion.
1040        #[source]
1041        error: FromPathBufError,
1042    },
1043
1044    /// Failed to compile a platform spec in an override.
1045    #[error(
1046        "for user config at {path}, failed to compile platform spec in [[overrides]] at index {index}"
1047    )]
1048    OverridePlatformSpec {
1049        /// The path to the config file.
1050        path: Utf8PathBuf,
1051        /// The index of the override in the array.
1052        index: usize,
1053        /// The underlying target-spec error.
1054        #[source]
1055        error: Box<target_spec::Error>,
1056    },
1057}
1058
1059/// Error returned while parsing a [`MaxFail`](crate::config::elements::MaxFail) input.
1060#[derive(Clone, Debug, Error)]
1061#[error("unrecognized value for max-fail: {reason}")]
1062pub struct MaxFailParseError {
1063    /// The reason parsing failed.
1064    pub reason: String,
1065}
1066
1067impl MaxFailParseError {
1068    pub(crate) fn new(reason: impl Into<String>) -> Self {
1069        Self {
1070            reason: reason.into(),
1071        }
1072    }
1073}
1074
1075/// Error returned while parsing a [`StressCount`](crate::runner::StressCount) input.
1076#[derive(Clone, Debug, Error)]
1077#[error(
1078    "unrecognized value for stress-count: {input}\n\
1079     (hint: expected either a positive integer or \"infinite\")"
1080)]
1081pub struct StressCountParseError {
1082    /// The input that failed to parse.
1083    pub input: String,
1084}
1085
1086impl StressCountParseError {
1087    pub(crate) fn new(input: impl Into<String>) -> Self {
1088        Self {
1089            input: input.into(),
1090        }
1091    }
1092}
1093
1094/// An error that occurred while parsing a debugger command.
1095#[derive(Clone, Debug, Error)]
1096#[non_exhaustive]
1097pub enum DebuggerCommandParseError {
1098    /// The command string could not be parsed as shell words.
1099    #[error(transparent)]
1100    ShellWordsParse(shell_words::ParseError),
1101
1102    /// The command was empty.
1103    #[error("debugger command cannot be empty")]
1104    EmptyCommand,
1105}
1106
1107/// An error that occurred while parsing a tracer command.
1108#[derive(Clone, Debug, Error)]
1109#[non_exhaustive]
1110pub enum TracerCommandParseError {
1111    /// The command string could not be parsed as shell words.
1112    #[error(transparent)]
1113    ShellWordsParse(shell_words::ParseError),
1114
1115    /// The command was empty.
1116    #[error("tracer command cannot be empty")]
1117    EmptyCommand,
1118}
1119
1120/// Error returned while parsing a [`TestThreads`](crate::config::elements::TestThreads) value.
1121#[derive(Clone, Debug, Error)]
1122#[error(
1123    "unrecognized value for test-threads: {input}\n(hint: expected either an integer or \"num-cpus\")"
1124)]
1125pub struct TestThreadsParseError {
1126    /// The input that failed to parse.
1127    pub input: String,
1128}
1129
1130impl TestThreadsParseError {
1131    pub(crate) fn new(input: impl Into<String>) -> Self {
1132        Self {
1133            input: input.into(),
1134        }
1135    }
1136}
1137
1138/// An error that occurs while parsing a
1139/// [`PartitionerBuilder`](crate::partition::PartitionerBuilder) input.
1140#[derive(Clone, Debug, Error)]
1141pub struct PartitionerBuilderParseError {
1142    expected_format: Option<&'static str>,
1143    message: Cow<'static, str>,
1144}
1145
1146impl PartitionerBuilderParseError {
1147    pub(crate) fn new(
1148        expected_format: Option<&'static str>,
1149        message: impl Into<Cow<'static, str>>,
1150    ) -> Self {
1151        Self {
1152            expected_format,
1153            message: message.into(),
1154        }
1155    }
1156}
1157
1158impl fmt::Display for PartitionerBuilderParseError {
1159    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160        match self.expected_format {
1161            Some(format) => {
1162                write!(
1163                    f,
1164                    "partition must be in the format \"{}\":\n{}",
1165                    format, self.message
1166                )
1167            }
1168            None => write!(f, "{}", self.message),
1169        }
1170    }
1171}
1172
1173/// An error that occurs while building a
1174/// [`TestFilter`](crate::test_filter::TestFilter).
1175#[derive(Clone, Debug, Error)]
1176pub enum TestFilterBuildError {
1177    /// An error that occurred while constructing test filters.
1178    #[error("error constructing test filters")]
1179    Construct {
1180        /// The underlying error.
1181        #[from]
1182        error: aho_corasick::BuildError,
1183    },
1184}
1185
1186/// An error occurred in [`PathMapper::new`](crate::reuse_build::PathMapper::new).
1187#[derive(Debug, Error)]
1188pub enum PathMapperConstructError {
1189    /// An error occurred while canonicalizing a directory.
1190    #[error("{kind} `{input}` failed to canonicalize")]
1191    Canonicalization {
1192        /// The directory that failed to be canonicalized.
1193        kind: PathMapperConstructKind,
1194
1195        /// The input provided.
1196        input: Utf8PathBuf,
1197
1198        /// The error that occurred.
1199        #[source]
1200        err: std::io::Error,
1201    },
1202    /// The canonicalized path isn't valid UTF-8.
1203    #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
1204    NonUtf8Path {
1205        /// The directory that failed to be canonicalized.
1206        kind: PathMapperConstructKind,
1207
1208        /// The input provided.
1209        input: Utf8PathBuf,
1210
1211        /// The underlying error.
1212        #[source]
1213        err: FromPathBufError,
1214    },
1215    /// A provided input is not a directory.
1216    #[error("{kind} `{canonicalized_path}` is not a directory")]
1217    NotADirectory {
1218        /// The directory that failed to be canonicalized.
1219        kind: PathMapperConstructKind,
1220
1221        /// The input provided.
1222        input: Utf8PathBuf,
1223
1224        /// The canonicalized path that wasn't a directory.
1225        canonicalized_path: Utf8PathBuf,
1226    },
1227}
1228
1229impl PathMapperConstructError {
1230    /// The kind of directory.
1231    pub fn kind(&self) -> PathMapperConstructKind {
1232        match self {
1233            Self::Canonicalization { kind, .. }
1234            | Self::NonUtf8Path { kind, .. }
1235            | Self::NotADirectory { kind, .. } => *kind,
1236        }
1237    }
1238
1239    /// The input path that failed.
1240    pub fn input(&self) -> &Utf8Path {
1241        match self {
1242            Self::Canonicalization { input, .. }
1243            | Self::NonUtf8Path { input, .. }
1244            | Self::NotADirectory { input, .. } => input,
1245        }
1246    }
1247}
1248
1249/// The kind of directory that failed to be read in
1250/// [`PathMapper::new`](crate::reuse_build::PathMapper::new).
1251///
1252/// Returned as part of [`PathMapperConstructError`].
1253#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1254pub enum PathMapperConstructKind {
1255    /// The workspace root.
1256    WorkspaceRoot,
1257
1258    /// The target directory.
1259    TargetDir,
1260
1261    /// The build directory.
1262    BuildDir,
1263}
1264
1265impl fmt::Display for PathMapperConstructKind {
1266    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1267        match self {
1268            Self::WorkspaceRoot => write!(f, "remapped workspace root"),
1269            Self::TargetDir => write!(f, "remapped target directory"),
1270            Self::BuildDir => write!(f, "remapped build directory"),
1271        }
1272    }
1273}
1274
1275/// An error that occurs while parsing Rust build metadata from a summary.
1276#[derive(Debug, Error)]
1277pub enum RustBuildMetaParseError {
1278    /// An error occurred while deserializing the platform.
1279    #[error("error deserializing platform from build metadata")]
1280    PlatformDeserializeError(#[from] target_spec::Error),
1281
1282    /// The host platform could not be determined.
1283    #[error("the host platform could not be determined")]
1284    DetectBuildTargetError(#[source] target_spec::Error),
1285
1286    /// The build metadata includes features unsupported.
1287    #[error("unsupported features in the build metadata: {message}")]
1288    Unsupported {
1289        /// The detailed error message.
1290        message: String,
1291    },
1292}
1293
1294/// Error returned when a user-supplied format version fails to be parsed to a
1295/// valid and supported version.
1296#[derive(Clone, Debug, thiserror::Error)]
1297#[error("invalid format version: {input}")]
1298pub struct FormatVersionError {
1299    /// The input that failed to parse.
1300    pub input: String,
1301    /// The underlying error.
1302    #[source]
1303    pub error: FormatVersionErrorInner,
1304}
1305
1306/// The different errors that can occur when parsing and validating a format version.
1307#[derive(Clone, Debug, thiserror::Error)]
1308pub enum FormatVersionErrorInner {
1309    /// The input did not have a valid syntax.
1310    #[error("expected format version in form of `{expected}`")]
1311    InvalidFormat {
1312        /// The expected pseudo format.
1313        expected: &'static str,
1314    },
1315    /// A decimal integer was expected but could not be parsed.
1316    #[error("version component `{which}` could not be parsed as an integer")]
1317    InvalidInteger {
1318        /// Which component was invalid.
1319        which: &'static str,
1320        /// The parse failure.
1321        #[source]
1322        err: std::num::ParseIntError,
1323    },
1324    /// The version component was not within the expected range.
1325    #[error("version component `{which}` value {value} is out of range {range:?}")]
1326    InvalidValue {
1327        /// The component which was out of range.
1328        which: &'static str,
1329        /// The value that was parsed.
1330        value: u8,
1331        /// The range of valid values for the component.
1332        range: std::ops::Range<u8>,
1333    },
1334}
1335
1336/// An error that occurs in [`BinaryList::from_messages`](crate::list::BinaryList::from_messages),
1337/// [`BinaryListBuilder`](crate::list::BinaryListBuilder), or
1338/// [`RustTestArtifact::from_binary_list`](crate::list::RustTestArtifact::from_binary_list).
1339#[derive(Debug, Error)]
1340#[non_exhaustive]
1341pub enum FromMessagesError {
1342    /// An error occurred while reading Cargo's JSON messages.
1343    #[error("error reading Cargo JSON messages")]
1344    ReadMessages(#[source] std::io::Error),
1345
1346    /// An error occurred while querying the package graph.
1347    #[error("error querying package graph")]
1348    PackageGraph(#[source] guppy::Error),
1349
1350    /// A target in the package graph was missing `kind` information.
1351    #[error("missing kind for target {binary_name} in package {package_name}")]
1352    MissingTargetKind {
1353        /// The name of the malformed package.
1354        package_name: String,
1355        /// The name of the malformed target within the package.
1356        binary_name: String,
1357    },
1358}
1359
1360/// An error that occurs while parsing test list output.
1361#[derive(Debug, Error)]
1362#[non_exhaustive]
1363pub enum CreateTestListError {
1364    /// The proposed cwd for a process is not a directory.
1365    #[error(
1366        "for `{binary_id}`, current directory `{cwd}` is not a directory\n\
1367         (hint: ensure project source is available at this location)"
1368    )]
1369    CwdIsNotDir {
1370        /// The binary ID for which the current directory wasn't found.
1371        binary_id: RustBinaryId,
1372
1373        /// The current directory that wasn't found.
1374        cwd: Utf8PathBuf,
1375    },
1376
1377    /// Running a command to gather the list of tests failed to execute.
1378    #[error(
1379        "for `{binary_id}`, running command `{}` failed to execute",
1380        shell_words::join(command)
1381    )]
1382    CommandExecFail {
1383        /// The binary ID for which gathering the list of tests failed.
1384        binary_id: RustBinaryId,
1385
1386        /// The command that was run.
1387        command: Vec<String>,
1388
1389        /// The underlying error.
1390        #[source]
1391        error: std::io::Error,
1392    },
1393
1394    /// Running a command to gather the list of tests failed failed with a non-zero exit code.
1395    #[error(
1396        "for `{binary_id}`, command `{}` {}\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1397        shell_words::join(command),
1398        display_exited_with(*exit_status),
1399        String::from_utf8_lossy(stdout),
1400        String::from_utf8_lossy(stderr),
1401    )]
1402    CommandFail {
1403        /// The binary ID for which gathering the list of tests failed.
1404        binary_id: RustBinaryId,
1405
1406        /// The command that was run.
1407        command: Vec<String>,
1408
1409        /// The exit status with which the command failed.
1410        exit_status: ExitStatus,
1411
1412        /// Standard output for the command.
1413        stdout: Vec<u8>,
1414
1415        /// Standard error for the command.
1416        stderr: Vec<u8>,
1417    },
1418
1419    /// Running a command to gather the list of tests produced a non-UTF-8 standard output.
1420    #[error(
1421        "for `{binary_id}`, command `{}` produced non-UTF-8 output:\n--- stdout:\n{}\n--- stderr:\n{}\n---",
1422        shell_words::join(command),
1423        String::from_utf8_lossy(stdout),
1424        String::from_utf8_lossy(stderr)
1425    )]
1426    CommandNonUtf8 {
1427        /// The binary ID for which gathering the list of tests failed.
1428        binary_id: RustBinaryId,
1429
1430        /// The command that was run.
1431        command: Vec<String>,
1432
1433        /// Standard output for the command.
1434        stdout: Vec<u8>,
1435
1436        /// Standard error for the command.
1437        stderr: Vec<u8>,
1438    },
1439
1440    /// An error occurred while parsing a line in the test output.
1441    #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1442    ParseLine {
1443        /// The binary ID for which parsing the list of tests failed.
1444        binary_id: RustBinaryId,
1445
1446        /// A descriptive message.
1447        message: Cow<'static, str>,
1448
1449        /// The full output.
1450        full_output: String,
1451    },
1452
1453    /// An error occurred while joining paths for dynamic libraries.
1454    #[error(
1455        "error joining dynamic library paths for {}: [{}]",
1456        dylib_path_envvar(),
1457        itertools::join(.new_paths, ", ")
1458    )]
1459    DylibJoinPaths {
1460        /// New paths attempted to be added to the dynamic library environment variable.
1461        new_paths: Vec<Utf8PathBuf>,
1462
1463        /// The underlying error.
1464        #[source]
1465        error: JoinPathsError,
1466    },
1467
1468    /// Creating a Tokio runtime failed.
1469    #[error("error creating Tokio runtime")]
1470    TokioRuntimeCreate(#[source] std::io::Error),
1471}
1472
1473impl CreateTestListError {
1474    pub(crate) fn parse_line(
1475        binary_id: RustBinaryId,
1476        message: impl Into<Cow<'static, str>>,
1477        full_output: impl Into<String>,
1478    ) -> Self {
1479        Self::ParseLine {
1480            binary_id,
1481            message: message.into(),
1482            full_output: full_output.into(),
1483        }
1484    }
1485
1486    pub(crate) fn dylib_join_paths(new_paths: Vec<Utf8PathBuf>, error: JoinPathsError) -> Self {
1487        Self::DylibJoinPaths { new_paths, error }
1488    }
1489}
1490
1491/// An error that occurs while writing list output.
1492#[derive(Debug, Error)]
1493#[non_exhaustive]
1494pub enum WriteTestListError {
1495    /// An error occurred while writing the list to the provided output.
1496    #[error("error writing to output")]
1497    Io(#[source] std::io::Error),
1498
1499    /// An error occurred while serializing JSON, or while writing it to the provided output.
1500    #[error("error serializing to JSON")]
1501    Json(#[source] serde_json::Error),
1502}
1503
1504/// An error occurred while configuring handles.
1505///
1506/// Only relevant on Windows.
1507#[derive(Debug, Error)]
1508pub enum ConfigureHandleInheritanceError {
1509    /// An error occurred. This can only happen on Windows.
1510    #[cfg(windows)]
1511    #[error("error configuring handle inheritance")]
1512    WindowsError(#[from] std::io::Error),
1513}
1514
1515/// An error that occurs while building the test runner.
1516#[derive(Debug, Error)]
1517#[non_exhaustive]
1518pub enum TestRunnerBuildError {
1519    /// An error occurred while creating the Tokio runtime.
1520    #[error("error creating Tokio runtime")]
1521    TokioRuntimeCreate(#[source] std::io::Error),
1522
1523    /// An error occurred while setting up signals.
1524    #[error("error setting up signals")]
1525    SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1526}
1527
1528/// Errors that occurred while managing test runner Tokio tasks.
1529#[derive(Debug, Error)]
1530pub struct TestRunnerExecuteErrors<E> {
1531    /// An error that occurred while reporting results to the reporter callback.
1532    pub report_error: Option<E>,
1533
1534    /// Join errors (typically panics) that occurred while running the test
1535    /// runner.
1536    pub join_errors: Vec<tokio::task::JoinError>,
1537}
1538
1539impl<E: std::error::Error> fmt::Display for TestRunnerExecuteErrors<E> {
1540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1541        if let Some(report_error) = &self.report_error {
1542            write!(f, "error reporting results: {report_error}")?;
1543        }
1544
1545        if !self.join_errors.is_empty() {
1546            if self.report_error.is_some() {
1547                write!(f, "; ")?;
1548            }
1549
1550            write!(f, "errors joining tasks: ")?;
1551
1552            for (i, join_error) in self.join_errors.iter().enumerate() {
1553                if i > 0 {
1554                    write!(f, ", ")?;
1555                }
1556
1557                write!(f, "{join_error}")?;
1558            }
1559        }
1560
1561        Ok(())
1562    }
1563}
1564
1565/// Represents an unknown archive format.
1566///
1567/// Returned by [`ArchiveFormat::autodetect`].
1568#[derive(Debug, Error)]
1569#[error(
1570    "could not detect archive format from file name `{file_name}` (supported extensions: {})",
1571    supported_extensions()
1572)]
1573pub struct UnknownArchiveFormat {
1574    /// The name of the archive file without any leading components.
1575    pub file_name: String,
1576}
1577
1578fn supported_extensions() -> String {
1579    ArchiveFormat::SUPPORTED_FORMATS
1580        .iter()
1581        .map(|(extension, _)| *extension)
1582        .join(", ")
1583}
1584
1585/// An error that occurs while archiving data.
1586#[derive(Debug, Error)]
1587#[non_exhaustive]
1588pub enum ArchiveCreateError {
1589    /// An error occurred while creating the binary list to be written.
1590    #[error("error creating binary list")]
1591    CreateBinaryList(#[source] WriteTestListError),
1592
1593    /// An extra path was missing.
1594    #[error("extra path `{}` not found", .redactor.redact_path(path))]
1595    MissingExtraPath {
1596        /// The path that was missing.
1597        path: Utf8PathBuf,
1598
1599        /// A redactor for the path.
1600        ///
1601        /// (This should eventually move to being a field for a wrapper struct, but it's okay for
1602        /// now.)
1603        redactor: Redactor,
1604    },
1605
1606    /// An error occurred while reading data from a file on disk.
1607    #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1608    InputFileRead {
1609        /// The step that the archive errored at.
1610        step: ArchiveStep,
1611
1612        /// The name of the file that could not be read.
1613        path: Utf8PathBuf,
1614
1615        /// Whether this is a directory. `None` means the status was unknown.
1616        is_dir: Option<bool>,
1617
1618        /// The error that occurred.
1619        #[source]
1620        error: std::io::Error,
1621    },
1622
1623    /// An error occurred while reading entries from a directory on disk.
1624    #[error("error reading directory entry from `{path}")]
1625    DirEntryRead {
1626        /// The name of the directory from which entries couldn't be read.
1627        path: Utf8PathBuf,
1628
1629        /// The error that occurred.
1630        #[source]
1631        error: std::io::Error,
1632    },
1633
1634    /// An error occurred while writing data to the output file.
1635    #[error("error writing to archive")]
1636    OutputArchiveIo(#[source] std::io::Error),
1637
1638    /// An error occurred in the reporter.
1639    #[error("error reporting archive status")]
1640    ReporterIo(#[source] std::io::Error),
1641}
1642
1643fn kind_str(is_dir: Option<bool>) -> &'static str {
1644    match is_dir {
1645        Some(true) => "directory",
1646        Some(false) => "file",
1647        None => "path",
1648    }
1649}
1650
1651/// An error occurred while materializing a metadata path.
1652#[derive(Debug, Error)]
1653pub enum MetadataMaterializeError {
1654    /// An I/O error occurred while reading the metadata file.
1655    #[error("I/O error reading metadata file `{path}`")]
1656    Read {
1657        /// The path that was being read.
1658        path: Utf8PathBuf,
1659
1660        /// The error that occurred.
1661        #[source]
1662        error: std::io::Error,
1663    },
1664
1665    /// A JSON deserialization error occurred while reading the metadata file.
1666    #[error("error deserializing metadata file `{path}`")]
1667    Deserialize {
1668        /// The path that was being read.
1669        path: Utf8PathBuf,
1670
1671        /// The error that occurred.
1672        #[source]
1673        error: serde_json::Error,
1674    },
1675
1676    /// An error occurred while parsing Rust build metadata.
1677    #[error("error parsing Rust build metadata from `{path}`")]
1678    RustBuildMeta {
1679        /// The path that was deserialized.
1680        path: Utf8PathBuf,
1681
1682        /// The error that occurred.
1683        #[source]
1684        error: Box<RustBuildMetaParseError>,
1685    },
1686
1687    /// An error occurred converting data into a `PackageGraph`.
1688    #[error("error building package graph from `{path}`")]
1689    PackageGraphConstruct {
1690        /// The path that was deserialized.
1691        path: Utf8PathBuf,
1692
1693        /// The error that occurred.
1694        #[source]
1695        error: Box<guppy::Error>,
1696    },
1697}
1698
1699/// An error occurred while reading a file.
1700///
1701/// Returned as part of both [`ArchiveCreateError`] and [`ArchiveExtractError`].
1702#[derive(Debug, Error)]
1703#[non_exhaustive]
1704pub enum ArchiveReadError {
1705    /// An I/O error occurred while reading the archive.
1706    #[error("I/O error reading archive")]
1707    Io(#[source] std::io::Error),
1708
1709    /// A path wasn't valid UTF-8.
1710    #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1711    NonUtf8Path(Vec<u8>),
1712
1713    /// A file path within the archive didn't begin with "target/".
1714    #[error("path in archive `{0}` doesn't start with `target/`")]
1715    NoTargetPrefix(Utf8PathBuf),
1716
1717    /// A file path within the archive had an invalid component within it.
1718    #[error("path in archive `{path}` contains an invalid component `{component}`")]
1719    InvalidComponent {
1720        /// The path that had an invalid component.
1721        path: Utf8PathBuf,
1722
1723        /// The invalid component.
1724        component: String,
1725    },
1726
1727    /// An archive entry was of an unsupported type: a symlink, hard link,
1728    /// device, FIFO, or other non-file type.
1729    #[error(
1730        "path in archive `{path}` has unsupported entry type: {} \
1731         (nextest archives only contain regular files and directories, so this archive \
1732         was likely not created by `cargo nextest archive`, or was modified afterwards)",
1733        display_entry_type(*entry_type),
1734    )]
1735    UnsupportedEntryType {
1736        /// The path with the unsupported entry type.
1737        path: Utf8PathBuf,
1738
1739        /// The entry type.
1740        entry_type: EntryType,
1741    },
1742
1743    /// An error occurred while reading a checksum.
1744    #[error("corrupted archive: checksum read error for path `{path}`")]
1745    ChecksumRead {
1746        /// The path for which there was a checksum read error.
1747        path: Utf8PathBuf,
1748
1749        /// The error that occurred.
1750        #[source]
1751        error: std::io::Error,
1752    },
1753
1754    /// An entry had an invalid checksum.
1755    #[error("corrupted archive: invalid checksum for path `{path}`")]
1756    InvalidChecksum {
1757        /// The path that had an invalid checksum.
1758        path: Utf8PathBuf,
1759
1760        /// The expected checksum.
1761        expected: u32,
1762
1763        /// The actual checksum.
1764        actual: u32,
1765    },
1766
1767    /// A metadata file wasn't found.
1768    #[error("metadata file `{0}` not found in archive")]
1769    MetadataFileNotFound(&'static Utf8Path),
1770
1771    /// An error occurred while deserializing a metadata file.
1772    #[error("error deserializing metadata file `{path}` in archive")]
1773    MetadataDeserializeError {
1774        /// The name of the metadata file.
1775        path: &'static Utf8Path,
1776
1777        /// The deserialize error.
1778        #[source]
1779        error: serde_json::Error,
1780    },
1781
1782    /// An error occurred while building a `PackageGraph`.
1783    #[error("error building package graph from `{path}` in archive")]
1784    PackageGraphConstructError {
1785        /// The name of the metadata file.
1786        path: &'static Utf8Path,
1787
1788        /// The error.
1789        #[source]
1790        error: Box<guppy::Error>,
1791    },
1792}
1793
1794fn display_entry_type(entry_type: EntryType) -> String {
1795    let description = match entry_type {
1796        EntryType::Regular => "regular file",
1797        EntryType::Link => "hard link",
1798        EntryType::Symlink => "symbolic link",
1799        EntryType::Char => "character device",
1800        EntryType::Block => "block device",
1801        EntryType::Directory => "directory",
1802        EntryType::Fifo => "FIFO",
1803        EntryType::Continuous => "contiguous file",
1804        EntryType::GNULongName => "GNU long name header",
1805        EntryType::GNULongLink => "GNU long link header",
1806        EntryType::GNUSparse => "GNU sparse file",
1807        EntryType::XGlobalHeader => "PAX global header",
1808        EntryType::XHeader => "PAX extended header",
1809        _ => "unknown",
1810    };
1811    format!(
1812        "{description} (type byte {:?})",
1813        char::from(entry_type.as_byte())
1814    )
1815}
1816
1817/// An error occurred while extracting a file.
1818///
1819/// Returned by [`extract_archive`](crate::reuse_build::ReuseBuildInfo::extract_archive).
1820#[derive(Debug, Error)]
1821#[non_exhaustive]
1822pub enum ArchiveExtractError {
1823    /// An error occurred while creating a temporary directory.
1824    #[error("error creating temporary directory")]
1825    TempDirCreate(#[source] std::io::Error),
1826
1827    /// An error occurred while canonicalizing the destination directory.
1828    #[error("error canonicalizing destination directory `{dir}`")]
1829    DestDirCanonicalization {
1830        /// The directory that failed to canonicalize.
1831        dir: Utf8PathBuf,
1832
1833        /// The error that occurred.
1834        #[source]
1835        error: std::io::Error,
1836    },
1837
1838    /// The destination already exists and `--overwrite` was not passed in.
1839    #[error("destination `{0}` already exists")]
1840    DestinationExists(Utf8PathBuf),
1841
1842    /// An error occurred while reading the archive.
1843    #[error("error reading archive")]
1844    Read(#[source] ArchiveReadError),
1845
1846    /// An error occurred while deserializing Rust build metadata.
1847    #[error("error deserializing Rust build metadata")]
1848    RustBuildMeta(#[from] RustBuildMetaParseError),
1849
1850    /// An error occurred while writing out a file to the destination directory.
1851    #[error("error writing file `{path}` to disk")]
1852    WriteFile {
1853        /// The path that we couldn't write out.
1854        path: Utf8PathBuf,
1855
1856        /// The error that occurred.
1857        #[source]
1858        error: std::io::Error,
1859    },
1860
1861    /// An error occurred while reporting the extraction status.
1862    #[error("error reporting extract status")]
1863    ReporterIo(std::io::Error),
1864}
1865
1866/// An error that occurs while writing an event.
1867#[derive(Debug, Error)]
1868#[non_exhaustive]
1869pub enum WriteEventError {
1870    /// An error occurred while writing the event to the provided output.
1871    #[error("error writing to output")]
1872    Io(#[source] std::io::Error),
1873
1874    /// An error occurred while operating on the file system.
1875    #[error("error operating on path {file}")]
1876    Fs {
1877        /// The file being operated on.
1878        file: Utf8PathBuf,
1879
1880        /// The underlying IO error.
1881        #[source]
1882        error: std::io::Error,
1883    },
1884
1885    /// An error occurred while producing JUnit XML.
1886    #[error("error writing JUnit output to {file}")]
1887    Junit {
1888        /// The output file.
1889        file: Utf8PathBuf,
1890
1891        /// The underlying error.
1892        #[source]
1893        error: quick_junit::SerializeError,
1894    },
1895}
1896
1897/// An error occurred while constructing a [`CargoConfigs`](crate::cargo_config::CargoConfigs)
1898/// instance.
1899#[derive(Debug, Error)]
1900#[non_exhaustive]
1901pub enum CargoConfigError {
1902    /// Failed to retrieve the current directory.
1903    #[error("failed to retrieve current directory")]
1904    GetCurrentDir(#[source] std::io::Error),
1905
1906    /// The current directory was invalid UTF-8.
1907    #[error("current directory is invalid UTF-8")]
1908    CurrentDirInvalidUtf8(#[source] FromPathBufError),
1909
1910    /// Parsing a CLI config option failed.
1911    #[error("failed to parse --config argument `{config_str}` as TOML")]
1912    CliConfigParseError {
1913        /// The CLI config option.
1914        config_str: String,
1915
1916        /// The error that occurred trying to parse the config.
1917        #[source]
1918        error: toml_edit::TomlError,
1919    },
1920
1921    /// Deserializing a CLI config option into domain types failed.
1922    #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1923    CliConfigDeError {
1924        /// The CLI config option.
1925        config_str: String,
1926
1927        /// The error that occurred trying to deserialize the config.
1928        #[source]
1929        error: toml_edit::de::Error,
1930    },
1931
1932    /// A CLI config option is not in the dotted key format.
1933    #[error(
1934        "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1935    )]
1936    InvalidCliConfig {
1937        /// The CLI config option.
1938        config_str: String,
1939
1940        /// The reason why this Cargo CLI config is invalid.
1941        #[source]
1942        reason: InvalidCargoCliConfigReason,
1943    },
1944
1945    /// A non-UTF-8 path was encountered.
1946    #[error("non-UTF-8 path encountered")]
1947    NonUtf8Path(#[source] FromPathBufError),
1948
1949    /// Failed to retrieve the Cargo home directory.
1950    #[error("failed to retrieve the Cargo home directory")]
1951    GetCargoHome(#[source] std::io::Error),
1952
1953    /// Failed to canonicalize a path
1954    #[error("failed to canonicalize path `{path}")]
1955    FailedPathCanonicalization {
1956        /// The path that failed to canonicalize
1957        path: Utf8PathBuf,
1958
1959        /// The error the occurred during canonicalization
1960        #[source]
1961        error: std::io::Error,
1962    },
1963
1964    /// Failed to read config file
1965    #[error("failed to read config at `{path}`")]
1966    ConfigReadError {
1967        /// The path of the config file
1968        path: Utf8PathBuf,
1969
1970        /// The error that occurred trying to read the config file
1971        #[source]
1972        error: std::io::Error,
1973    },
1974
1975    /// Failed to deserialize config file
1976    #[error(transparent)]
1977    ConfigParseError(#[from] Box<CargoConfigParseError>),
1978}
1979
1980/// Failed to deserialize config file
1981///
1982/// We introduce this extra indirection, because of the `clippy::result_large_err` rule on Windows.
1983#[derive(Debug, Error)]
1984#[error("failed to parse config at `{path}`")]
1985pub struct CargoConfigParseError {
1986    /// The path of the config file
1987    pub path: Utf8PathBuf,
1988
1989    /// The error that occurred trying to deserialize the config file
1990    #[source]
1991    pub error: toml::de::Error,
1992}
1993
1994/// The reason an invalid CLI config failed.
1995///
1996/// Part of [`CargoConfigError::InvalidCliConfig`].
1997#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1998#[non_exhaustive]
1999pub enum InvalidCargoCliConfigReason {
2000    /// The argument is not a TOML dotted key expression.
2001    #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
2002    NotDottedKv,
2003
2004    /// The argument includes non-whitespace decoration.
2005    #[error("includes non-whitespace decoration")]
2006    IncludesNonWhitespaceDecoration,
2007
2008    /// The argument sets a value to an inline table.
2009    #[error("sets a value to an inline table, which is not accepted")]
2010    SetsValueToInlineTable,
2011
2012    /// The argument sets a value to an array of tables.
2013    #[error("sets a value to an array of tables, which is not accepted")]
2014    SetsValueToArrayOfTables,
2015
2016    /// The argument doesn't provide a value.
2017    #[error("doesn't provide a value")]
2018    DoesntProvideValue,
2019}
2020
2021/// The host platform couldn't be detected.
2022#[derive(Debug, Error)]
2023pub enum HostPlatformDetectError {
2024    /// Spawning `rustc -vV` failed, and detecting the build target failed as
2025    /// well.
2026    #[error(
2027        "error spawning `rustc -vV`, and detecting the build \
2028         target failed as well\n\
2029         - rustc spawn error: {}\n\
2030         - build target error: {}\n",
2031        DisplayErrorChain::new_with_initial_indent("  ", error),
2032        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
2033    )]
2034    RustcVvSpawnError {
2035        /// The error.
2036        error: std::io::Error,
2037
2038        /// The error that occurred while detecting the build target.
2039        build_target_error: Box<target_spec::Error>,
2040    },
2041
2042    /// `rustc -vV` exited with a non-zero code, and detecting the build target
2043    /// failed as well.
2044    #[error(
2045        "`rustc -vV` failed with {}, and detecting the \
2046         build target failed as well\n\
2047         - `rustc -vV` stdout:\n{}\n\
2048         - `rustc -vV` stderr:\n{}\n\
2049         - build target error:\n{}\n",
2050        status,
2051        DisplayIndented { item: String::from_utf8_lossy(stdout), indent: "  " },
2052        DisplayIndented { item: String::from_utf8_lossy(stderr), indent: "  " },
2053        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
2054    )]
2055    RustcVvFailed {
2056        /// The status.
2057        status: ExitStatus,
2058
2059        /// The standard output from `rustc -vV`.
2060        stdout: Vec<u8>,
2061
2062        /// The standard error from `rustc -vV`.
2063        stderr: Vec<u8>,
2064
2065        /// The error that occurred while detecting the build target.
2066        build_target_error: Box<target_spec::Error>,
2067    },
2068
2069    /// Parsing the host platform failed, and detecting the build target failed
2070    /// as well.
2071    #[error(
2072        "parsing `rustc -vV` output failed, and detecting the build target \
2073         failed as well\n\
2074         - host platform error:\n{}\n\
2075         - build target error:\n{}\n",
2076        DisplayErrorChain::new_with_initial_indent("  ", host_platform_error),
2077        DisplayErrorChain::new_with_initial_indent("  ", build_target_error)
2078    )]
2079    HostPlatformParseError {
2080        /// The error that occurred while parsing the host platform.
2081        host_platform_error: Box<target_spec::Error>,
2082
2083        /// The error that occurred while detecting the build target.
2084        build_target_error: Box<target_spec::Error>,
2085    },
2086
2087    /// Test-only code: `rustc -vV` was not queried, and detecting the build
2088    /// target failed as well.
2089    #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
2090    BuildTargetError {
2091        /// The error that occurred while detecting the build target.
2092        #[source]
2093        build_target_error: Box<target_spec::Error>,
2094    },
2095}
2096
2097/// An error occurred while determining the cross-compiling target triple.
2098#[derive(Debug, Error)]
2099pub enum TargetTripleError {
2100    /// The environment variable contained non-utf8 content
2101    #[error(
2102        "environment variable '{}' contained non-UTF-8 data",
2103        TargetTriple::CARGO_BUILD_TARGET_ENV
2104    )]
2105    InvalidEnvironmentVar,
2106
2107    /// An error occurred while deserializing the platform.
2108    #[error("error deserializing target triple from {source}")]
2109    TargetSpecError {
2110        /// The source from which the triple couldn't be parsed.
2111        source: TargetTripleSource,
2112
2113        /// The error that occurred parsing the triple.
2114        #[source]
2115        error: target_spec::Error,
2116    },
2117
2118    /// For a custom platform, reading the target path failed.
2119    #[error("target path `{path}` is not a valid file")]
2120    TargetPathReadError {
2121        /// The source from which the triple couldn't be parsed.
2122        source: TargetTripleSource,
2123
2124        /// The path that we tried to read.
2125        path: Utf8PathBuf,
2126
2127        /// The error that occurred parsing the triple.
2128        #[source]
2129        error: std::io::Error,
2130    },
2131
2132    /// Failed to create a temporary directory for a custom platform.
2133    #[error(
2134        "for custom platform obtained from {source}, \
2135         failed to create temporary directory for custom platform"
2136    )]
2137    CustomPlatformTempDirError {
2138        /// The source of the target triple.
2139        source: TargetTripleSource,
2140
2141        /// The error that occurred during the create.
2142        #[source]
2143        error: std::io::Error,
2144    },
2145
2146    /// A custom triple from metadata can't be used as a file name.
2147    #[error(
2148        "for custom platform obtained from {triple_source}, \
2149         triple {triple:?} cannot be used as a file name \
2150         (custom platform triples must be a single path component other than `.` or `..`); \
2151         the metadata may be malformed and should be regenerated"
2152    )]
2153    CustomPlatformInvalidTriple {
2154        /// The location where the triple was obtained from.
2155        triple_source: TargetTripleSource,
2156
2157        /// The triple that was rejected.
2158        triple: String,
2159    },
2160
2161    /// Failed to write a custom platform to disk.
2162    #[error(
2163        "for custom platform obtained from {source}, \
2164         failed to write JSON to temporary path `{path}`"
2165    )]
2166    CustomPlatformWriteError {
2167        /// The source of the target triple.
2168        source: TargetTripleSource,
2169
2170        /// The path that we tried to write to.
2171        path: Utf8PathBuf,
2172
2173        /// The error that occurred during the write.
2174        #[source]
2175        error: std::io::Error,
2176    },
2177
2178    /// Failed to close a temporary directory for an extracted custom platform.
2179    #[error(
2180        "for custom platform obtained from {source}, \
2181         failed to close temporary directory `{dir_path}`"
2182    )]
2183    CustomPlatformCloseError {
2184        /// The source of the target triple.
2185        source: TargetTripleSource,
2186
2187        /// The directory that we tried to delete.
2188        dir_path: Utf8PathBuf,
2189
2190        /// The error that occurred during the close.
2191        #[source]
2192        error: std::io::Error,
2193    },
2194}
2195
2196impl TargetTripleError {
2197    /// Returns a [`miette::Report`] for the source, if available.
2198    ///
2199    /// This should be preferred over [`std::error::Error::source`] if
2200    /// available.
2201    pub fn source_report(&self) -> Option<miette::Report> {
2202        match self {
2203            Self::TargetSpecError { error, .. } => {
2204                Some(miette::Report::new_boxed(error.clone().into_diagnostic()))
2205            }
2206            // The remaining types are covered via the error source path.
2207            TargetTripleError::InvalidEnvironmentVar
2208            | TargetTripleError::TargetPathReadError { .. }
2209            | TargetTripleError::CustomPlatformInvalidTriple { .. }
2210            | TargetTripleError::CustomPlatformTempDirError { .. }
2211            | TargetTripleError::CustomPlatformWriteError { .. }
2212            | TargetTripleError::CustomPlatformCloseError { .. } => None,
2213        }
2214    }
2215}
2216
2217/// An error occurred determining the target runner
2218#[derive(Debug, Error)]
2219pub enum TargetRunnerError {
2220    /// An environment variable contained non-utf8 content
2221    #[error("environment variable '{0}' contained non-UTF-8 data")]
2222    InvalidEnvironmentVar(String),
2223
2224    /// An environment variable or config key was found that matches the target
2225    /// triple, but it didn't actually contain a binary
2226    #[error("runner '{key}' = '{value}' did not contain a runner binary")]
2227    BinaryNotSpecified {
2228        /// The source under consideration.
2229        key: PlatformRunnerSource,
2230
2231        /// The value that was read from the key
2232        value: String,
2233    },
2234}
2235
2236/// An error that occurred while setting up the signal handler.
2237#[derive(Debug, Error)]
2238#[error("error setting up signal handler")]
2239pub struct SignalHandlerSetupError(#[from] std::io::Error);
2240
2241/// An error occurred while showing test groups.
2242#[derive(Debug, Error)]
2243pub enum ShowTestGroupsError {
2244    /// Unknown test groups were specified.
2245    #[error(
2246        "unknown test groups specified: {}\n(known groups: {})",
2247        unknown_groups.iter().join(", "),
2248        known_groups.iter().join(", "),
2249    )]
2250    UnknownGroups {
2251        /// The unknown test groups.
2252        unknown_groups: BTreeSet<TestGroup>,
2253
2254        /// All known test groups.
2255        known_groups: BTreeSet<TestGroup>,
2256    },
2257}
2258
2259/// An error occurred while processing profile's inherits setting
2260#[derive(Debug, Error, PartialEq, Eq, Hash)]
2261pub enum InheritsError {
2262    /// The default profile should not be able to inherit from other profiles
2263    #[error("the {} profile should not inherit from other profiles", .0)]
2264    DefaultProfileInheritance(String),
2265    /// An unknown/unfound profile was detected to inherit from in profile configuration
2266    #[error("profile {} inherits from an unknown profile {}", .0, .1)]
2267    UnknownInheritance(String, String),
2268    /// A self referential inheritance is detected from this profile
2269    #[error("a self referential inheritance is detected from profile: {}", .0)]
2270    SelfReferentialInheritance(String),
2271    /// An inheritance cycle was detected in the profile configuration.
2272    #[error("inheritance cycle detected in profile configuration from: {}", .0.iter().map(|scc| {
2273        format!("[{}]", scc.iter().join(", "))
2274    }).join(", "))]
2275    InheritanceCycle(Vec<Vec<String>>),
2276}
2277
2278// ---
2279// Record and replay errors
2280// ---
2281
2282/// An error that occurred while managing the run store.
2283#[derive(Debug, Error)]
2284pub enum RunStoreError {
2285    /// An error occurred while creating the run directory.
2286    #[error("error creating run directory `{run_dir}`")]
2287    RunDirCreate {
2288        /// The run directory that could not be created.
2289        run_dir: Utf8PathBuf,
2290
2291        /// The underlying error.
2292        #[source]
2293        error: std::io::Error,
2294    },
2295
2296    /// An error occurred while acquiring a file lock.
2297    #[error("error acquiring lock on `{path}`")]
2298    FileLock {
2299        /// The path to the lock file.
2300        path: Utf8PathBuf,
2301
2302        /// The underlying error.
2303        #[source]
2304        error: std::io::Error,
2305    },
2306
2307    /// Timed out waiting to acquire a file lock.
2308    #[error(
2309        "timed out acquiring lock on `{path}` after {timeout_secs}s (is the state directory \
2310         on a networked filesystem?)"
2311    )]
2312    FileLockTimeout {
2313        /// The path to the lock file.
2314        path: Utf8PathBuf,
2315
2316        /// The timeout duration in seconds.
2317        timeout_secs: u64,
2318    },
2319
2320    /// An error occurred while reading the run list.
2321    #[error("error reading run list from `{path}`")]
2322    RunListRead {
2323        /// The path to the run list file.
2324        path: Utf8PathBuf,
2325
2326        /// The underlying error.
2327        #[source]
2328        error: std::io::Error,
2329    },
2330
2331    /// An error occurred while deserializing the run list.
2332    #[error("error deserializing run list from `{path}`")]
2333    RunListDeserialize {
2334        /// The path to the run list file.
2335        path: Utf8PathBuf,
2336
2337        /// The underlying error.
2338        #[source]
2339        error: serde_json::Error,
2340    },
2341
2342    /// An error occurred while serializing the run list.
2343    #[error("error serializing run list to `{path}`")]
2344    RunListSerialize {
2345        /// The path to the run list file.
2346        path: Utf8PathBuf,
2347
2348        /// The underlying error.
2349        #[source]
2350        error: serde_json::Error,
2351    },
2352
2353    /// An error occurred while serializing rerun info.
2354    #[error("error serializing rerun info")]
2355    RerunInfoSerialize {
2356        /// The underlying error.
2357        #[source]
2358        error: serde_json::Error,
2359    },
2360
2361    /// An error occurred while serializing the build scope.
2362    #[error("error serializing build scope")]
2363    BuildScopeSerialize {
2364        /// The underlying error.
2365        #[source]
2366        error: serde_json::Error,
2367    },
2368
2369    /// An error occurred while serializing the test list.
2370    #[error("error serializing test list")]
2371    TestListSerialize {
2372        /// The underlying error.
2373        #[source]
2374        error: serde_json::Error,
2375    },
2376
2377    /// An error occurred while serializing the record options.
2378    #[error("error serializing record options")]
2379    RecordOptionsSerialize {
2380        /// The underlying error.
2381        #[source]
2382        error: serde_json::Error,
2383    },
2384
2385    /// An error occurred while serializing a test event.
2386    #[error("error serializing test event")]
2387    TestEventSerialize {
2388        /// The underlying error.
2389        #[source]
2390        error: serde_json::Error,
2391    },
2392
2393    /// An error occurred while writing the run list.
2394    #[error("error writing run list to `{path}`")]
2395    RunListWrite {
2396        /// The path to the run list file.
2397        path: Utf8PathBuf,
2398
2399        /// The underlying error.
2400        #[source]
2401        error: atomicwrites::Error<std::io::Error>,
2402    },
2403
2404    /// An error occurred while writing to the store.
2405    #[error("error writing to store at `{store_path}`")]
2406    StoreWrite {
2407        /// The path to the store file.
2408        store_path: Utf8PathBuf,
2409
2410        /// The underlying error.
2411        #[source]
2412        error: StoreWriterError,
2413    },
2414
2415    /// An error occurred while creating the run log.
2416    #[error("error creating run log at `{path}`")]
2417    RunLogCreate {
2418        /// The path to the run log file.
2419        path: Utf8PathBuf,
2420
2421        /// The underlying error.
2422        #[source]
2423        error: std::io::Error,
2424    },
2425
2426    /// An error occurred while writing to the run log.
2427    #[error("error writing to run log at `{path}`")]
2428    RunLogWrite {
2429        /// The path to the run log file.
2430        path: Utf8PathBuf,
2431
2432        /// The underlying error.
2433        #[source]
2434        error: std::io::Error,
2435    },
2436
2437    /// An error occurred while flushing the run log.
2438    #[error("error flushing run log at `{path}`")]
2439    RunLogFlush {
2440        /// The path to the run log file.
2441        path: Utf8PathBuf,
2442
2443        /// The underlying error.
2444        #[source]
2445        error: std::io::Error,
2446    },
2447
2448    /// Cannot write to runs.json.zst because it has a newer format version.
2449    #[error(
2450        "cannot write to record store: runs.json.zst format version {file_version} is newer than \
2451         supported version {max_supported_version}"
2452    )]
2453    FormatVersionTooNew {
2454        /// The format version in the file.
2455        file_version: RunsJsonFormatVersion,
2456        /// The maximum version this nextest can write.
2457        max_supported_version: RunsJsonFormatVersion,
2458    },
2459}
2460
2461/// An error that occurred while writing to a zip store.
2462#[derive(Debug, Error)]
2463#[non_exhaustive]
2464pub enum StoreWriterError {
2465    /// An error occurred while creating the store file.
2466    #[error("error creating store")]
2467    Create {
2468        /// The underlying error.
2469        #[source]
2470        error: std::io::Error,
2471    },
2472
2473    /// An error occurred while writing to a file in the store.
2474    #[error("error writing to path `{path}` in store")]
2475    Write {
2476        /// The path within the store.
2477        path: Utf8PathBuf,
2478
2479        /// The underlying error.
2480        #[source]
2481        error: std::io::Error,
2482    },
2483
2484    /// An error occurred while compressing data with a zstd dictionary.
2485    #[error("error compressing data")]
2486    Compress {
2487        /// The underlying error.
2488        #[source]
2489        error: std::io::Error,
2490    },
2491
2492    /// An error occurred while finalizing the store.
2493    #[error("error finalizing store")]
2494    Finish {
2495        /// The underlying error.
2496        #[source]
2497        error: std::io::Error,
2498    },
2499
2500    /// An error occurred while flushing the store.
2501    #[error("error flushing store")]
2502    Flush {
2503        /// The underlying error.
2504        #[source]
2505        error: std::io::Error,
2506    },
2507}
2508
2509/// An error that occurred in the record reporter.
2510#[derive(Debug, Error)]
2511pub enum RecordReporterError {
2512    /// An error occurred while writing to the run store.
2513    #[error(transparent)]
2514    RunStore(RunStoreError),
2515
2516    /// The writer thread panicked.
2517    #[error("record writer thread panicked: {message}")]
2518    WriterPanic {
2519        /// A message extracted from the panic payload, if available.
2520        message: String,
2521    },
2522}
2523
2524/// An error determining the state directory for recordings.
2525#[derive(Debug, Error)]
2526pub enum StateDirError {
2527    /// The platform base strategy could not be determined.
2528    ///
2529    /// This typically means the platform doesn't support standard directory layouts.
2530    #[error("could not determine platform base directory strategy")]
2531    BaseDirStrategy(#[source] HomeDirError),
2532
2533    /// The platform state directory path is not valid UTF-8.
2534    #[error("platform state directory is not valid UTF-8: {path:?}")]
2535    StateDirNotUtf8 {
2536        /// The path that was not valid UTF-8.
2537        path: PathBuf,
2538    },
2539
2540    /// The workspace path could not be canonicalized.
2541    #[error("could not canonicalize workspace path `{workspace_root}`")]
2542    Canonicalize {
2543        /// The workspace root that could not be canonicalized.
2544        workspace_root: Utf8PathBuf,
2545        /// The underlying I/O error.
2546        #[source]
2547        error: std::io::Error,
2548    },
2549}
2550
2551/// An error during recording session setup.
2552#[derive(Debug, Error)]
2553pub enum RecordSetupError {
2554    /// The platform state directory could not be determined.
2555    #[error("could not determine platform state directory for recording")]
2556    StateDirNotFound(#[source] StateDirError),
2557
2558    /// Failed to create the run store.
2559    #[error("failed to create run store")]
2560    StoreCreate(#[source] RunStoreError),
2561
2562    /// Failed to acquire exclusive lock on the run store.
2563    #[error("failed to lock run store")]
2564    StoreLock(#[source] RunStoreError),
2565
2566    /// Failed to create the run recorder.
2567    #[error("failed to create run recorder")]
2568    RecorderCreate(#[source] RunStoreError),
2569}
2570
2571/// An error that occurred while pruning recorded runs.
2572#[derive(Debug, Error)]
2573pub enum RecordPruneError {
2574    /// An error occurred while deleting a run directory.
2575    #[error("error deleting run `{run_id}` at `{path}`")]
2576    DeleteRun {
2577        /// The run ID that could not be deleted.
2578        run_id: ReportUuid,
2579
2580        /// The path to the run directory.
2581        path: Utf8PathBuf,
2582
2583        /// The underlying error.
2584        #[source]
2585        error: std::io::Error,
2586    },
2587
2588    /// An error occurred while calculating the size of a path.
2589    #[error("error calculating size of `{path}`")]
2590    CalculateSize {
2591        /// The path whose size could not be calculated.
2592        path: Utf8PathBuf,
2593
2594        /// The underlying error.
2595        #[source]
2596        error: std::io::Error,
2597    },
2598
2599    /// An error occurred while deleting an orphaned directory.
2600    #[error("error deleting orphaned directory `{path}`")]
2601    DeleteOrphan {
2602        /// The path to the orphaned directory.
2603        path: Utf8PathBuf,
2604
2605        /// The underlying error.
2606        #[source]
2607        error: std::io::Error,
2608    },
2609
2610    /// An error occurred while reading the runs directory.
2611    #[error("error reading runs directory `{path}`")]
2612    ReadRunsDir {
2613        /// The path to the runs directory.
2614        path: Utf8PathBuf,
2615
2616        /// The underlying error.
2617        #[source]
2618        error: std::io::Error,
2619    },
2620
2621    /// An error occurred while reading a directory entry.
2622    #[error("error reading directory entry in `{dir}`")]
2623    ReadDirEntry {
2624        /// The path to the directory being read.
2625        dir: Utf8PathBuf,
2626
2627        /// The underlying error.
2628        #[source]
2629        error: std::io::Error,
2630    },
2631
2632    /// An error occurred while reading file type.
2633    #[error("error reading file type for `{path}`")]
2634    ReadFileType {
2635        /// The path whose file type could not be read.
2636        path: Utf8PathBuf,
2637
2638        /// The underlying error.
2639        #[source]
2640        error: std::io::Error,
2641    },
2642}
2643
2644/// Error returned when parsing an invalid run ID selector.
2645///
2646/// A valid selector is either "latest" or a string containing only hex digits
2647/// and dashes (for UUID format).
2648#[derive(Clone, Debug, PartialEq, Eq, Error)]
2649#[error("invalid run ID selector `{input}`: expected `latest` or hex digits")]
2650pub struct InvalidRunIdSelector {
2651    /// The invalid input string.
2652    pub input: String,
2653}
2654
2655/// Error returned when parsing a [`RunIdOrRecordingSelector`](crate::record::RunIdOrRecordingSelector) fails.
2656///
2657/// A valid selector is either "latest", a string containing only hex digits
2658/// and dashes (for UUID format), or a file path (ending in `.zip` or
2659/// containing path separators).
2660#[derive(Clone, Debug, PartialEq, Eq, Error)]
2661#[error(
2662    "invalid run ID selector `{input}`: expected `latest`, hex digits, \
2663     or a file path (ending in `.zip` or containing path separators)"
2664)]
2665pub struct InvalidRunIdOrRecordingSelector {
2666    /// The invalid input string.
2667    pub input: String,
2668}
2669
2670/// An error resolving a run ID prefix.
2671#[derive(Debug, Error)]
2672pub enum RunIdResolutionError {
2673    /// No run found matching the prefix.
2674    #[error("no recorded run found matching `{prefix}`")]
2675    NotFound {
2676        /// The prefix that was searched for.
2677        prefix: String,
2678    },
2679
2680    /// Multiple runs match the prefix.
2681    #[error("prefix `{prefix}` is ambiguous, matches {count} runs")]
2682    Ambiguous {
2683        /// The prefix that was searched for.
2684        prefix: String,
2685
2686        /// The number of matching runs.
2687        count: usize,
2688
2689        /// The candidates that matched (up to a limit).
2690        candidates: Vec<RecordedRunInfo>,
2691
2692        /// The run ID index for computing shortest unique prefixes.
2693        run_id_index: RunIdIndex,
2694    },
2695
2696    /// The prefix contains invalid characters.
2697    #[error("prefix `{prefix}` contains invalid characters (expected hexadecimal)")]
2698    InvalidPrefix {
2699        /// The invalid prefix.
2700        prefix: String,
2701    },
2702
2703    /// No recorded runs exist.
2704    #[error("no recorded runs exist")]
2705    NoRuns,
2706}
2707
2708/// An error that occurred while reading a recorded run.
2709#[derive(Debug, Error)]
2710pub enum RecordReadError {
2711    /// The run was not found.
2712    #[error("run not found at `{path}`")]
2713    RunNotFound {
2714        /// The path where the run was expected.
2715        path: Utf8PathBuf,
2716    },
2717
2718    /// Failed to open the archive.
2719    #[error("error opening archive at `{path}`")]
2720    OpenArchive {
2721        /// The path to the archive.
2722        path: Utf8PathBuf,
2723
2724        /// The underlying error.
2725        #[source]
2726        error: std::io::Error,
2727    },
2728
2729    /// Failed to parse the archive (corrupt or truncated).
2730    #[error("error parsing archive at `{path}`")]
2731    ParseArchive {
2732        /// The path to the archive.
2733        path: Utf8PathBuf,
2734
2735        /// The underlying error.
2736        #[source]
2737        error: std::io::Error,
2738    },
2739
2740    /// Failed to read an archive file.
2741    #[error("error reading `{file_name}` from archive")]
2742    ReadArchiveFile {
2743        /// The file name within the archive.
2744        file_name: String,
2745
2746        /// The underlying error.
2747        #[source]
2748        error: std::io::Error,
2749    },
2750
2751    /// Failed to open the run log.
2752    #[error("error opening run log at `{path}`")]
2753    OpenRunLog {
2754        /// The path to the run log.
2755        path: Utf8PathBuf,
2756
2757        /// The underlying error.
2758        #[source]
2759        error: std::io::Error,
2760    },
2761
2762    /// Failed to read a line from the run log.
2763    #[error("error reading line {line_number} from run log")]
2764    ReadRunLog {
2765        /// The line number that failed.
2766        line_number: usize,
2767
2768        /// The underlying error.
2769        #[source]
2770        error: std::io::Error,
2771    },
2772
2773    /// A run log line was longer than the limit.
2774    #[error(
2775        "line {line_number} in run log exceeds the maximum size of {}",
2776        SizeDisplay(.limit.0)
2777    )]
2778    RunLogLineTooLong {
2779        /// The line number that was too long.
2780        line_number: usize,
2781
2782        /// The maximum line length.
2783        limit: ByteSize,
2784    },
2785
2786    /// Failed to parse an event from the run log.
2787    #[error("error parsing event at line {line_number}")]
2788    ParseEvent {
2789        /// The line number that failed.
2790        line_number: usize,
2791
2792        /// The underlying error.
2793        #[source]
2794        error: serde_json::Error,
2795    },
2796
2797    /// Required file not found in archive.
2798    #[error("required file `{file_name}` not found in archive")]
2799    FileNotFound {
2800        /// The file name that was not found.
2801        file_name: String,
2802    },
2803
2804    /// Failed to decompress archive data.
2805    #[error("error decompressing data from `{file_name}`")]
2806    Decompress {
2807        /// The file name being decompressed.
2808        file_name: String,
2809
2810        /// The underlying error.
2811        #[source]
2812        error: std::io::Error,
2813    },
2814
2815    /// Unknown output file type in archive.
2816    ///
2817    /// This indicates the archive was created by a newer version of nextest
2818    /// with additional output types that this version doesn't recognize.
2819    #[error(
2820        "unknown output file type `{file_name}` in archive \
2821         (archive may have been created by a newer version of nextest)"
2822    )]
2823    UnknownOutputType {
2824        /// The file name with the unknown type.
2825        file_name: String,
2826    },
2827
2828    /// Archive file exceeds maximum allowed size.
2829    #[error(
2830        "file `{file_name}` in archive exceeds maximum size ({size} bytes, limit is {limit} bytes)"
2831    )]
2832    FileTooLarge {
2833        /// The file name in the archive.
2834        file_name: String,
2835
2836        /// The size of the file.
2837        size: u64,
2838
2839        /// The maximum allowed size.
2840        limit: u64,
2841    },
2842
2843    /// Archive file size doesn't match the header.
2844    ///
2845    /// This indicates a corrupt or tampered archive since nextest controls
2846    /// archive creation.
2847    #[error(
2848        "file `{file_name}` size mismatch: header claims {claimed_size} bytes, \
2849         but read {actual_size} bytes (archive may be corrupt or tampered)"
2850    )]
2851    SizeMismatch {
2852        /// The file name in the archive.
2853        file_name: String,
2854
2855        /// The size claimed in the ZIP header.
2856        claimed_size: u64,
2857
2858        /// The actual size read.
2859        actual_size: u64,
2860    },
2861
2862    /// Failed to deserialize metadata.
2863    #[error("error deserializing `{file_name}`")]
2864    DeserializeMetadata {
2865        /// The file name being deserialized.
2866        file_name: String,
2867
2868        /// The underlying error.
2869        #[source]
2870        error: serde_json::Error,
2871    },
2872
2873    /// Failed to extract a file from the store.
2874    #[error("failed to extract `{store_path}` to `{output_path}`")]
2875    ExtractFile {
2876        /// The path within the store.
2877        store_path: String,
2878
2879        /// The output path where extraction was attempted.
2880        output_path: Utf8PathBuf,
2881
2882        /// The underlying I/O error.
2883        #[source]
2884        error: std::io::Error,
2885    },
2886
2887    /// An error occurred while reading a portable recording.
2888    #[error("error reading portable recording")]
2889    PortableRecording(#[source] PortableRecordingReadError),
2890}
2891
2892/// An error that occurred while creating a portable recording.
2893#[derive(Debug, Error)]
2894#[non_exhaustive]
2895pub enum PortableRecordingError {
2896    /// The run directory does not exist.
2897    #[error("run directory does not exist: {path}")]
2898    RunDirNotFound {
2899        /// The path that was expected to exist.
2900        path: Utf8PathBuf,
2901    },
2902
2903    /// A required file is missing from the run directory.
2904    #[error("required file missing from run directory `{run_dir}`: `{file_name}`")]
2905    RequiredFileMissing {
2906        /// The run directory that was being validated.
2907        run_dir: Utf8PathBuf,
2908        /// The name of the missing file.
2909        file_name: &'static str,
2910    },
2911
2912    /// Failed to serialize the manifest.
2913    #[error("failed to serialize manifest")]
2914    SerializeManifest(#[source] serde_json::Error),
2915
2916    /// Failed to start a file in the zip archive.
2917    #[error("failed to start file {file_name} in archive")]
2918    ZipStartFile {
2919        /// The file that failed to start.
2920        file_name: &'static str,
2921        /// The underlying I/O error.
2922        #[source]
2923        source: std::io::Error,
2924    },
2925
2926    /// Failed to write to the zip archive.
2927    #[error("failed to write {file_name} to archive")]
2928    ZipWrite {
2929        /// The file being written.
2930        file_name: &'static str,
2931        /// The underlying I/O error.
2932        #[source]
2933        source: std::io::Error,
2934    },
2935
2936    /// Failed to read a source file.
2937    #[error("failed to read {file_name}")]
2938    ReadFile {
2939        /// The file being read.
2940        file_name: &'static str,
2941        /// The underlying I/O error.
2942        #[source]
2943        source: std::io::Error,
2944    },
2945
2946    /// Failed to finalize the zip archive.
2947    #[error("failed to finalize archive")]
2948    ZipFinalize(#[source] std::io::Error),
2949
2950    /// Failed to write the archive atomically.
2951    #[error("failed to write archive atomically to {path}")]
2952    AtomicWrite {
2953        /// The destination path.
2954        path: Utf8PathBuf,
2955        /// The underlying error.
2956        #[source]
2957        source: std::io::Error,
2958    },
2959}
2960
2961/// An error that occurred while reading a portable recording.
2962#[derive(Debug, Error)]
2963#[non_exhaustive]
2964pub enum PortableRecordingReadError {
2965    /// Failed to open the archive file.
2966    #[error("failed to open archive at `{path}`")]
2967    OpenArchive {
2968        /// The path to the archive.
2969        path: Utf8PathBuf,
2970        /// The underlying I/O error.
2971        #[source]
2972        error: std::io::Error,
2973    },
2974
2975    /// Failed to read from the archive.
2976    #[error("failed to read archive at `{path}`")]
2977    ReadArchive {
2978        /// The path to the archive.
2979        path: Utf8PathBuf,
2980        /// The underlying I/O error.
2981        #[source]
2982        error: std::io::Error,
2983    },
2984
2985    /// A required file is missing from the archive.
2986    #[error("required file `{file_name}` missing from archive at `{path}`")]
2987    MissingFile {
2988        /// The path to the archive.
2989        path: Utf8PathBuf,
2990        /// The name of the missing file.
2991        file_name: Cow<'static, str>,
2992    },
2993
2994    /// Failed to parse the manifest.
2995    #[error("failed to parse manifest from archive at `{path}`")]
2996    ParseManifest {
2997        /// The path to the archive.
2998        path: Utf8PathBuf,
2999        /// The underlying JSON error.
3000        #[source]
3001        error: serde_json::Error,
3002    },
3003
3004    /// The portable recording format version is not supported.
3005    #[error(
3006        "portable recording format version {found} in `{path}` is incompatible: {incompatibility} \
3007         (this nextest supports version {supported})"
3008    )]
3009    UnsupportedFormatVersion {
3010        /// The path to the archive.
3011        path: Utf8PathBuf,
3012        /// The format version found in the archive.
3013        found: PortableRecordingFormatVersion,
3014        /// The supported format version.
3015        supported: PortableRecordingFormatVersion,
3016        /// The specific incompatibility.
3017        incompatibility: PortableRecordingVersionIncompatibility,
3018    },
3019
3020    /// The store format version is not supported.
3021    #[error("store format version {found} in `{path}` is incompatible: {incompatibility}")]
3022    UnsupportedStoreFormatVersion {
3023        /// The path to the archive.
3024        path: Utf8PathBuf,
3025        /// The store format version found in the archive.
3026        found: StoreFormatVersion,
3027        /// The supported store format version.
3028        supported: StoreFormatVersion,
3029        /// The specific incompatibility.
3030        incompatibility: StoreVersionIncompatibility,
3031    },
3032
3033    /// A file in the archive exceeds the size limit.
3034    #[error(
3035        "file `{file_name}` in archive `{path}` is too large \
3036         ({size} bytes, limit is {limit} bytes)"
3037    )]
3038    FileTooLarge {
3039        /// The path to the archive.
3040        path: Utf8PathBuf,
3041        /// The name of the file.
3042        file_name: Cow<'static, str>,
3043        /// The size of the file.
3044        size: u64,
3045        /// The size limit.
3046        limit: u64,
3047    },
3048
3049    /// Failed to extract a file from the archive.
3050    #[error("failed to extract `{file_name}` from archive `{archive_path}` to `{output_path}`")]
3051    ExtractFile {
3052        /// The path to the archive.
3053        archive_path: Utf8PathBuf,
3054        /// The name of the file being extracted.
3055        file_name: &'static str,
3056        /// The path where extraction was attempted.
3057        output_path: Utf8PathBuf,
3058        /// The underlying I/O error.
3059        #[source]
3060        error: std::io::Error,
3061    },
3062
3063    /// The inner archive is compressed.
3064    ///
3065    /// With portable recordings, the inner archive must be stored uncompressed.
3066    #[error(
3067        "for portable recording `{archive_path}`, the inner archive is stored \
3068         with {:?} compression -- it must be stored uncompressed",
3069        compression
3070    )]
3071    CompressedInnerArchive {
3072        /// The path to the archive.
3073        archive_path: Utf8PathBuf,
3074        /// The compression method used.
3075        compression: CompressionMethod,
3076    },
3077
3078    /// The archive has no manifest and is not a valid wrapper archive.
3079    ///
3080    /// A wrapper archive must contain exactly one `.zip` file.
3081    #[error(
3082        "archive at `{path}` has no manifest and is not a wrapper archive \
3083         (contains {file_count} {}, {zip_count} of which {} in .zip)",
3084        plural::files_str(*file_count),
3085        plural::end_str(*zip_count)
3086    )]
3087    NotAWrapperArchive {
3088        /// The path to the archive.
3089        path: Utf8PathBuf,
3090        /// The total number of files in the archive.
3091        file_count: usize,
3092        /// The number of files ending in `.zip`.
3093        zip_count: usize,
3094    },
3095
3096    /// An unexpected I/O error occurred while probing whether the input is
3097    /// seekable.
3098    ///
3099    /// This is distinct from the expected `ESPIPE`/`ERROR_INVALID_FUNCTION`
3100    /// errors that indicate a pipe or FIFO. Unexpected errors (e.g. `EBADF`,
3101    /// `EIO`) are propagated here rather than falling into the spool path.
3102    #[error("unexpected I/O error while probing seekability of `{path}`")]
3103    SeekProbe {
3104        /// The path to the recording.
3105        path: Utf8PathBuf,
3106        /// The underlying I/O error.
3107        #[source]
3108        error: std::io::Error,
3109    },
3110
3111    /// An I/O error occurred while spooling a non-seekable input to a
3112    /// temporary file.
3113    ///
3114    /// This covers temp file creation, data copying, and seeking back to
3115    /// the start.
3116    #[error("failed to spool non-seekable input `{path}` to a temporary file")]
3117    SpoolTempFile {
3118        /// The path to the recording (e.g. `/proc/self/fd/11`).
3119        path: Utf8PathBuf,
3120        /// The underlying I/O error.
3121        #[source]
3122        error: std::io::Error,
3123    },
3124
3125    /// The input being spooled to a temporary file exceeded the size limit.
3126    #[error(
3127        "recording at `{path}` exceeds the spool size limit \
3128         ({}); use a file path instead of process substitution",
3129        SizeDisplay(.limit.0)
3130    )]
3131    SpoolTooLarge {
3132        /// The path to the recording.
3133        path: Utf8PathBuf,
3134        /// The size limit.
3135        limit: ByteSize,
3136    },
3137}
3138
3139/// Errors that can occur during Chrome trace conversion.
3140#[derive(Debug, Error)]
3141pub enum ChromeTraceError {
3142    /// An error occurred while reading recorded events.
3143    #[error("error reading recorded events")]
3144    ReadError(#[source] RecordReadError),
3145
3146    /// An event referenced a test that was never started.
3147    #[error(
3148        "event for test `{test_name}` in binary `{binary_id}` \
3149         has no prior TestStarted event (corrupt or truncated log?)"
3150    )]
3151    MissingTestStart {
3152        /// The test name.
3153        test_name: TestCaseName,
3154
3155        /// The binary ID.
3156        binary_id: RustBinaryId,
3157    },
3158
3159    /// A SetupScriptSlow event referenced a script that is not running.
3160    #[error(
3161        "SetupScriptSlow for script `{script_id}` \
3162         has no prior SetupScriptStarted event (corrupt or truncated log?)"
3163    )]
3164    MissingScriptStart {
3165        /// The script ID.
3166        script_id: ScriptId,
3167    },
3168
3169    /// A StressSubRunFinished event arrived without a prior
3170    /// StressSubRunStarted.
3171    #[error(
3172        "StressSubRunFinished has no prior StressSubRunStarted event \
3173         (corrupt or truncated log?)"
3174    )]
3175    MissingStressSubRunStart,
3176
3177    /// An error occurred while serializing the trace to JSON.
3178    #[error("error serializing Chrome trace JSON")]
3179    SerializeError(#[source] serde_json::Error),
3180}
3181
3182/// An error that occurred while reconstructing a TestList from a summary.
3183///
3184/// Returned by [`TestList::from_summary`](crate::list::TestList::from_summary).
3185#[derive(Debug, Error)]
3186pub enum TestListFromSummaryError {
3187    /// Package not found in the package graph.
3188    #[error("package `{name}` (id: `{package_id}`) not found in cargo metadata")]
3189    PackageNotFound {
3190        /// The package name.
3191        name: String,
3192
3193        /// The package ID that was looked up.
3194        package_id: String,
3195    },
3196
3197    /// Error parsing rust build metadata.
3198    #[error("error parsing rust build metadata")]
3199    RustBuildMeta(#[source] RustBuildMetaParseError),
3200}
3201
3202#[cfg(feature = "self-update")]
3203mod self_update_errors {
3204    use super::*;
3205    use crate::update::PrereleaseKind;
3206    use byte_wrapper::HexArray;
3207    use mukti_metadata::ReleaseStatus;
3208    use semver::{Version, VersionReq};
3209
3210    /// An error that occurs while performing a self-update.
3211    ///
3212    /// Returned by methods in the [`update`](crate::update) module.
3213    #[derive(Debug, Error)]
3214    #[non_exhaustive]
3215    pub enum UpdateError {
3216        /// Failed to read release metadata from a local path on disk.
3217        #[error("failed to read release metadata from `{path}`")]
3218        ReadLocalMetadata {
3219            /// The path that was read.
3220            path: Utf8PathBuf,
3221
3222            /// The error that occurred.
3223            #[source]
3224            error: std::io::Error,
3225        },
3226
3227        /// An error was generated by `self_update`.
3228        #[error("self-update failed")]
3229        SelfUpdate(#[source] self_update::errors::Error),
3230
3231        /// An HTTP error occurred while performing a request.
3232        #[error("error performing HTTP request")]
3233        Http(#[source] ureq::Error),
3234
3235        /// An error occurred while reading an HTTP response body.
3236        #[error("error reading HTTP response body")]
3237        HttpBody(#[source] std::io::Error),
3238
3239        /// The server's Content-Length header was present but could not be
3240        /// parsed.
3241        #[error("Content-Length header present but could not be parsed as an integer: {value:?}")]
3242        ContentLengthInvalid {
3243            /// The raw header value.
3244            value: String,
3245        },
3246
3247        /// The server's Content-Length header didn't match the number of bytes
3248        /// received.
3249        #[error("content length mismatch: expected {expected} bytes, received {actual} bytes")]
3250        ContentLengthMismatch {
3251            /// The expected number of bytes (from the Content-Length header).
3252            expected: u64,
3253            /// The actual number of bytes received.
3254            actual: u64,
3255        },
3256
3257        /// Deserializing release metadata failed.
3258        #[error("deserializing release metadata failed")]
3259        ReleaseMetadataDe(#[source] serde_json::Error),
3260
3261        /// This version was not found.
3262        #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
3263        VersionNotFound {
3264            /// The version that wasn't found.
3265            version: Version,
3266
3267            /// A list of all known versions.
3268            known: Vec<(Version, ReleaseStatus)>,
3269        },
3270
3271        /// No version was found matching a requirement.
3272        #[error("no version found matching requirement `{req}`")]
3273        NoMatchForVersionReq {
3274            /// The version requirement that had no matches.
3275            req: VersionReq,
3276        },
3277
3278        /// No stable (non-prerelease) version was found.
3279        #[error("no stable version found")]
3280        NoStableVersion,
3281
3282        /// No version matching the requested prerelease kind was found.
3283        #[error("no version found matching {} channel", kind.description())]
3284        NoVersionForPrereleaseKind {
3285            /// The kind of prerelease that was requested.
3286            kind: PrereleaseKind,
3287        },
3288
3289        /// The specified mukti project was not found.
3290        #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
3291        MuktiProjectNotFound {
3292            /// The project that was not found.
3293            not_found: String,
3294
3295            /// Known projects.
3296            known: Vec<String>,
3297        },
3298
3299        /// No release information was found for the given target triple.
3300        #[error(
3301            "for version {version}, no release information found for target `{triple}` \
3302            (known targets: {})",
3303            known_triples.iter().join(", ")
3304        )]
3305        NoTargetData {
3306            /// The version that was fetched.
3307            version: Version,
3308
3309            /// The target triple.
3310            triple: String,
3311
3312            /// The triples that were found.
3313            known_triples: BTreeSet<String>,
3314        },
3315
3316        /// The current executable could not be determined.
3317        #[error("the current executable's path could not be determined")]
3318        CurrentExe(#[source] std::io::Error),
3319
3320        /// A temporary directory could not be created.
3321        #[error("temporary directory could not be created at `{location}`")]
3322        TempDirCreate {
3323            /// The location where the temporary directory could not be created.
3324            location: Utf8PathBuf,
3325
3326            /// The error that occurred.
3327            #[source]
3328            error: std::io::Error,
3329        },
3330
3331        /// The temporary archive could not be created.
3332        #[error("temporary archive could not be created at `{archive_path}`")]
3333        TempArchiveCreate {
3334            /// The archive file that couldn't be created.
3335            archive_path: Utf8PathBuf,
3336
3337            /// The error that occurred.
3338            #[source]
3339            error: std::io::Error,
3340        },
3341
3342        /// An error occurred while writing to a temporary archive.
3343        #[error("error writing to temporary archive at `{archive_path}`")]
3344        TempArchiveWrite {
3345            /// The archive path for which there was an error.
3346            archive_path: Utf8PathBuf,
3347
3348            /// The error that occurred.
3349            #[source]
3350            error: std::io::Error,
3351        },
3352
3353        /// An error occurred while reading from a temporary archive.
3354        #[error("error reading from temporary archive at `{archive_path}`")]
3355        TempArchiveRead {
3356            /// The archive path for which there was an error.
3357            archive_path: Utf8PathBuf,
3358
3359            /// The error that occurred.
3360            #[source]
3361            error: std::io::Error,
3362        },
3363
3364        /// A checksum mismatch occurred. (Currently, the SHA-256 checksum is checked.)
3365        #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
3366        ChecksumMismatch {
3367            /// The expected checksum.
3368            expected: mukti_metadata::Digest,
3369
3370            /// The actual checksum.
3371            actual: HexArray<32>,
3372        },
3373
3374        /// An error occurred while renaming a file.
3375        #[error("error renaming `{source}` to `{dest}`")]
3376        FsRename {
3377            /// The rename source.
3378            source: Utf8PathBuf,
3379
3380            /// The rename destination.
3381            dest: Utf8PathBuf,
3382
3383            /// The error that occurred.
3384            #[source]
3385            error: std::io::Error,
3386        },
3387
3388        /// An error occurred while running `cargo nextest self setup`.
3389        #[error("cargo-nextest binary updated, but error running `cargo nextest self setup`")]
3390        SelfSetup(#[source] std::io::Error),
3391    }
3392
3393    fn known_versions(versions: &[(Version, ReleaseStatus)]) -> String {
3394        use std::fmt::Write;
3395
3396        // Take the first few versions here.
3397        const DISPLAY_COUNT: usize = 4;
3398
3399        let display_versions: Vec<_> = versions
3400            .iter()
3401            .filter(|(v, status)| v.pre.is_empty() && *status == ReleaseStatus::Active)
3402            .map(|(v, _)| v.to_string())
3403            .take(DISPLAY_COUNT)
3404            .collect();
3405        let mut display_str = display_versions.join(", ");
3406        if versions.len() > display_versions.len() {
3407            write!(
3408                display_str,
3409                " and {} others",
3410                versions.len() - display_versions.len()
3411            )
3412            .unwrap();
3413        }
3414
3415        display_str
3416    }
3417
3418    /// An error occurred while parsing an [`UpdateVersion`](crate::update::UpdateVersion).
3419    #[derive(Debug, Error)]
3420    pub enum UpdateVersionParseError {
3421        /// The version string is empty.
3422        #[error("version string is empty")]
3423        EmptyString,
3424
3425        /// The input is not a valid version requirement.
3426        #[error(
3427            "`{input}` is not a valid semver requirement\n\
3428                (hint: see https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html for the correct format)"
3429        )]
3430        InvalidVersionReq {
3431            /// The input that was provided.
3432            input: String,
3433
3434            /// The error.
3435            #[source]
3436            error: semver::Error,
3437        },
3438
3439        /// The version is not a valid semver.
3440        #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
3441        InvalidVersion {
3442            /// The input that was provided.
3443            input: String,
3444
3445            /// The error.
3446            #[source]
3447            error: semver::Error,
3448        },
3449    }
3450
3451    fn extra_semver_output(input: &str) -> String {
3452        // If it is not a valid version but it is a valid version
3453        // requirement, add a note to the warning
3454        if input.parse::<VersionReq>().is_ok() {
3455            format!(
3456                "\n(if you want to specify a semver range, add an explicit qualifier, like ^{input})"
3457            )
3458        } else {
3459            "".to_owned()
3460        }
3461    }
3462}
3463
3464#[cfg(feature = "self-update")]
3465pub use self_update_errors::*;
3466
3467#[cfg(test)]
3468mod tests {
3469    use super::*;
3470
3471    #[test]
3472    fn display_error_chain() {
3473        let err1 = StringError::new("err1", None);
3474
3475        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err1)), @"err1");
3476
3477        let err2 = StringError::new("err2", Some(err1));
3478        let err3 = StringError::new("err3\nerr3 line 2", Some(err2));
3479
3480        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&err3)), @"
3481        err3
3482        err3 line 2
3483          caused by:
3484          - err2
3485          - err1
3486        ");
3487    }
3488
3489    #[test]
3490    fn display_error_list() {
3491        let err1 = StringError::new("err1", None);
3492
3493        let error_list =
3494            ErrorList::<StringError>::new("waiting on the water to boil", vec![err1.clone()])
3495                .expect(">= 1 error");
3496        insta::assert_snapshot!(format!("{}", error_list), @"err1");
3497        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"err1");
3498
3499        let err2 = StringError::new("err2", Some(err1));
3500        let err3 = StringError::new("err3", Some(err2));
3501
3502        let error_list =
3503            ErrorList::<StringError>::new("waiting on flowers to bloom", vec![err3.clone()])
3504                .expect(">= 1 error");
3505        insta::assert_snapshot!(format!("{}", error_list), @"err3");
3506        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"
3507        err3
3508          caused by:
3509          - err2
3510          - err1
3511        ");
3512
3513        let err4 = StringError::new("err4", None);
3514        let err5 = StringError::new("err5", Some(err4));
3515        let err6 = StringError::new("err6\nerr6 line 2", Some(err5));
3516
3517        let error_list = ErrorList::<StringError>::new(
3518            "waiting for the heat death of the universe",
3519            vec![err3, err6],
3520        )
3521        .expect(">= 1 error");
3522
3523        insta::assert_snapshot!(format!("{}", error_list), @"
3524        2 errors occurred waiting for the heat death of the universe:
3525        * err3
3526            caused by:
3527            - err2
3528            - err1
3529        * err6
3530          err6 line 2
3531            caused by:
3532            - err5
3533            - err4
3534        ");
3535        insta::assert_snapshot!(format!("{}", DisplayErrorChain::new(&error_list)), @"
3536        2 errors occurred waiting for the heat death of the universe:
3537        * err3
3538            caused by:
3539            - err2
3540            - err1
3541        * err6
3542          err6 line 2
3543            caused by:
3544            - err5
3545            - err4
3546        ");
3547    }
3548
3549    #[derive(Clone, Debug, Error)]
3550    struct StringError {
3551        message: String,
3552        #[source]
3553        source: Option<Box<StringError>>,
3554    }
3555
3556    impl StringError {
3557        fn new(message: impl Into<String>, source: Option<StringError>) -> Self {
3558            Self {
3559                message: message.into(),
3560                source: source.map(Box::new),
3561            }
3562        }
3563    }
3564
3565    impl fmt::Display for StringError {
3566        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3567            write!(f, "{}", self.message)
3568        }
3569    }
3570}