1use 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#[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 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 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 pub fn display_config_file(&self) -> impl fmt::Display + '_ {
108 &self.config_file
109 }
110
111 pub fn display_file(&self, styles: ConfigStyles) -> impl fmt::Display + '_ {
113 DisplayConfigFile {
114 error: self,
115 styles,
116 }
117 }
118
119 pub fn display_header(&self, styles: ConfigStyles) -> impl fmt::Display + '_ {
123 DisplayConfigHeader {
124 error: self,
125 styles,
126 }
127 }
128
129 pub fn tool(&self) -> Option<&ToolName> {
131 self.tool.as_ref()
132 }
133
134 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#[derive(Debug, Error)]
199pub enum ConfigPathsCaptureError {
200 #[error("failed to determine the current directory, which config paths are resolved against")]
202 CurrentDir(#[source] CurrentDirError),
203
204 #[error("failed to resolve workspace root `{}`", .0.input())]
206 WorkspaceRoot(#[source] ResolvePathError),
207}
208
209pub 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#[derive(Debug, Error)]
233#[non_exhaustive]
234pub enum ConfigParseErrorKind {
235 #[error("error resolving the configuration path")]
237 PathResolveError(#[source] Box<ResolvePathError>),
238 #[error(transparent)]
240 PathsCaptureError(Box<ConfigPathsCaptureError>),
241 #[error(transparent)]
243 BuildError(Box<ConfigError>),
244 #[error(transparent)]
246 TomlParseError(Box<toml::de::Error>),
247 #[error(transparent)]
248 DeserializeError(Box<serde_path_to_error::Error<ConfigError>>),
250 #[error(transparent)]
252 ReadError(std::io::Error),
253 #[error(transparent)]
255 VersionOnlyDeserializeError(Box<serde_path_to_error::Error<toml::de::Error>>),
256 #[error("error parsing compiled data (destructure this variant for more details)")]
258 CompileErrors(Vec<ConfigCompileError>),
259 #[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 #[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 #[error("unknown test groups specified by config (destructure this variant for more details)")]
268 UnknownTestGroups {
269 errors: Vec<UnknownTestGroupError>,
271
272 known_groups: BTreeSet<TestGroup>,
274 },
275 #[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 #[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 #[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 #[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 #[error(
296 "errors in profile-specific config scripts (destructure this variant for more details)"
297 )]
298 ProfileScriptErrors {
299 errors: Box<ProfileScriptErrors>,
301
302 known_scripts: BTreeSet<ScriptId>,
304 },
305 #[error("unknown experimental features defined (destructure this variant for more details)")]
307 UnknownExperimentalFeatures {
308 unknown: BTreeSet<String>,
310
311 known: BTreeSet<ConfigExperimental>,
313 },
314 #[error(
318 "tool config file specifies experimental features `{}` \
319 -- only repository config files can do so",
320 .features.iter().join(", "),
321 )]
322 ExperimentalFeaturesInToolConfig {
323 features: BTreeSet<String>,
325 },
326 #[error("experimental features used but not enabled: {}", .missing_features.iter().join(", "))]
328 ExperimentalFeaturesNotEnabled {
329 missing_features: BTreeSet<ConfigExperimental>,
331 },
332 #[error("inheritance error(s) detected: {}", .0.iter().join(", "))]
334 InheritanceErrors(Vec<InheritsError>),
335 #[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 tool: ToolName,
345 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#[derive(Debug)]
359#[non_exhaustive]
360pub struct ConfigCompileError {
361 pub profile_name: String,
363
364 pub section: ConfigCompileSection,
366
367 pub kind: ConfigCompileErrorKind,
369}
370
371#[derive(Debug)]
374pub enum ConfigCompileSection {
375 DefaultFilter,
377
378 Override(usize),
380
381 Script(usize),
383}
384
385#[derive(Debug)]
387#[non_exhaustive]
388pub enum ConfigCompileErrorKind {
389 ConstraintsNotSpecified {
391 default_filter_specified: bool,
396 },
397
398 FilterAndDefaultFilterSpecified,
402
403 Parse {
405 host_parse_error: Option<target_spec::Error>,
407
408 target_parse_error: Option<target_spec::Error>,
410
411 filter_parse_errors: Vec<FiltersetParseErrors>,
413 },
414}
415
416impl ConfigCompileErrorKind {
417 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#[derive(Clone, Debug, Error)]
467#[error("test priority ({priority}) out of range: must be between -100 and 100, both inclusive")]
468pub struct TestPriorityOutOfRange {
469 pub priority: i8,
471}
472
473#[derive(Clone, Debug, Error)]
475pub enum ChildStartError {
476 #[error("error creating temporary path for setup script")]
478 TempPath(#[source] Arc<std::io::Error>),
479
480 #[error("error spawning child process")]
482 Spawn(#[source] Arc<std::io::Error>),
483}
484
485#[derive(Clone, Debug, Error)]
487pub enum SetupScriptOutputError {
488 #[error("error opening environment file `{path}`")]
490 EnvFileOpen {
491 path: Utf8PathBuf,
493
494 #[source]
496 error: Arc<std::io::Error>,
497 },
498
499 #[error("error reading environment file `{path}`")]
501 EnvFileRead {
502 path: Utf8PathBuf,
504
505 #[source]
507 error: Arc<std::io::Error>,
508 },
509
510 #[error("line `{line}` in environment file `{path}` not in KEY=VALUE format")]
512 EnvFileParse {
513 path: Utf8PathBuf,
515 line: String,
517 },
518
519 #[error("error in environment file `{path}`")]
521 EnvFileInvalidKey {
522 path: Utf8PathBuf,
524
525 #[source]
527 error: EnvVarError,
528 },
529}
530
531#[derive(Clone, Debug, Error)]
533pub enum EnvVarError {
534 #[error("key `{key}` begins with `NEXTEST`, which is reserved for internal use")]
536 ReservedKey {
537 key: String,
539 },
540
541 #[error("key `{key}` does not consist solely of letters, digits, and underscores")]
544 InvalidKey {
545 key: String,
547 },
548
549 #[error("key `{key}` does not start with a letter or underscore")]
551 InvalidKeyStartChar {
552 key: String,
554 },
555}
556
557impl 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
579pub struct ErrorList<T> {
580 description: Cow<'static, str>,
582 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 pub(crate) fn short_message(&self) -> String {
603 let string = self.to_string();
604 match string.lines().next() {
605 Some(first_line) => first_line.trim_end_matches(':').to_string(),
607 None => String::new(),
608 }
609 }
610
611 pub fn description(&self) -> &str {
613 &self.description
614 }
615
616 pub fn iter(&self) -> impl Iterator<Item = &T> {
618 self.inner.iter()
619 }
620
621 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 self.inner.len() == 1 {
647 return write!(f, "{}", self.inner[0]);
648 }
649
650 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 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 None
694 }
695 }
696}
697
698pub struct DisplayErrorChain<E> {
703 error: E,
704 initial_indent: &'static str,
705}
706
707impl<E: std::error::Error> DisplayErrorChain<E> {
708 pub fn new(error: E) -> Self {
710 Self {
711 error,
712 initial_indent: "",
713 }
714 }
715
716 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 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#[derive(Clone, Debug, Error)]
756pub enum ChildError {
757 #[error(transparent)]
759 Fd(#[from] ChildFdError),
760
761 #[error(transparent)]
763 SetupScriptOutput(#[from] SetupScriptOutputError),
764}
765
766#[derive(Clone, Debug, Error)]
768pub enum ChildFdError {
769 #[error("error reading standard output")]
771 ReadStdout(#[source] Arc<std::io::Error>),
772
773 #[error("error reading standard error")]
775 ReadStderr(#[source] Arc<std::io::Error>),
776
777 #[error("error reading combined stream")]
779 ReadCombined(#[source] Arc<std::io::Error>),
780
781 #[error("error waiting for child process to exit")]
783 Wait(#[source] Arc<std::io::Error>),
784}
785
786#[derive(Clone, Debug, Eq, PartialEq)]
788#[non_exhaustive]
789pub struct UnknownTestGroupError {
790 pub profile_name: String,
792
793 pub name: TestGroup,
795}
796
797#[derive(Clone, Debug, Eq, PartialEq)]
800pub struct ProfileUnknownScriptError {
801 pub profile_name: String,
803
804 pub name: ScriptId,
806}
807
808#[derive(Clone, Debug, Eq, PartialEq)]
811pub struct ProfileWrongConfigScriptTypeError {
812 pub profile_name: String,
814
815 pub name: ScriptId,
817
818 pub attempted: ProfileScriptType,
820
821 pub actual: ScriptType,
823}
824
825#[derive(Clone, Debug, Eq, PartialEq)]
828pub struct ProfileListScriptUsesRunFiltersError {
829 pub profile_name: String,
831
832 pub name: ScriptId,
834
835 pub script_type: ProfileScriptType,
837
838 pub filters: BTreeSet<String>,
840}
841
842#[derive(Clone, Debug, Default)]
844pub struct ProfileScriptErrors {
845 pub unknown_scripts: Vec<ProfileUnknownScriptError>,
847
848 pub wrong_script_types: Vec<ProfileWrongConfigScriptTypeError>,
850
851 pub list_scripts_using_run_filters: Vec<ProfileListScriptUsesRunFiltersError>,
853}
854
855impl ProfileScriptErrors {
856 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#[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#[derive(Clone, Debug, Error, Eq, PartialEq)]
888pub enum InvalidIdentifier {
889 #[error("identifier is empty")]
891 Empty,
892
893 #[error("invalid identifier `{0}`")]
895 InvalidXid(SmolStr),
896
897 #[error("tool identifier not of the form \"@tool:tool-name:identifier\": `{0}`")]
899 ToolIdentifierInvalidFormat(SmolStr),
900
901 #[error("tool identifier has empty component: `{0}`")]
903 ToolComponentEmpty(SmolStr),
904
905 #[error("invalid tool identifier `{0}`")]
907 ToolIdentifierInvalidXid(SmolStr),
908}
909
910#[derive(Clone, Debug, Error, Eq, PartialEq)]
912pub enum InvalidToolName {
913 #[error("tool name is empty")]
915 Empty,
916
917 #[error("invalid tool name `{0}`")]
919 InvalidXid(SmolStr),
920
921 #[error("tool name cannot start with \"@tool\": `{0}`")]
923 StartsWithToolPrefix(SmolStr),
924}
925
926#[derive(Clone, Debug, Error)]
928#[error("invalid custom test group name: {0}")]
929pub struct InvalidCustomTestGroupName(pub InvalidIdentifier);
930
931#[derive(Clone, Debug, Error)]
933#[error("invalid configuration script name: {0}")]
934pub struct InvalidConfigScriptName(pub InvalidIdentifier);
935
936#[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 pub fn spec(&self) -> &str {
948 &self.spec
949 }
950
951 pub fn kind(&self) -> &PackageSpecErrorKind {
953 &self.kind
954 }
955}
956
957#[derive(Clone, Debug, Error, PartialEq, Eq)]
964pub enum PackageSpecErrorKind {}
965
966#[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 InvalidFormat {
974 input: String,
976 },
977
978 #[error("tool-config-file has invalid tool name: {input}")]
980 InvalidToolName {
981 input: String,
983
984 #[source]
986 error: InvalidToolName,
987 },
988
989 #[error("tool-config-file has empty config file path: {input}")]
991 EmptyConfigFile {
992 input: String,
994 },
995
996 #[error("tool-config-file is not an absolute path: {config_file}")]
998 ConfigFileNotAbsolute {
999 config_file: Utf8PathBuf,
1001 },
1002}
1003
1004#[derive(Debug, Error)]
1006#[non_exhaustive]
1007pub enum UserConfigError {
1008 #[error("user config file not found at {path}")]
1011 FileNotFound {
1012 path: Utf8PathBuf,
1014 },
1015
1016 #[error("failed to read user config at {path}")]
1018 Read {
1019 path: Utf8PathBuf,
1021 #[source]
1023 error: std::io::Error,
1024 },
1025
1026 #[error("failed to parse user config at {path}")]
1028 Parse {
1029 path: Utf8PathBuf,
1031 #[source]
1033 error: toml::de::Error,
1034 },
1035
1036 #[error("user config path contains non-UTF-8 characters")]
1038 NonUtf8Path {
1039 #[source]
1041 error: FromPathBufError,
1042 },
1043
1044 #[error(
1046 "for user config at {path}, failed to compile platform spec in [[overrides]] at index {index}"
1047 )]
1048 OverridePlatformSpec {
1049 path: Utf8PathBuf,
1051 index: usize,
1053 #[source]
1055 error: Box<target_spec::Error>,
1056 },
1057}
1058
1059#[derive(Clone, Debug, Error)]
1061#[error("unrecognized value for max-fail: {reason}")]
1062pub struct MaxFailParseError {
1063 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#[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 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#[derive(Clone, Debug, Error)]
1096#[non_exhaustive]
1097pub enum DebuggerCommandParseError {
1098 #[error(transparent)]
1100 ShellWordsParse(shell_words::ParseError),
1101
1102 #[error("debugger command cannot be empty")]
1104 EmptyCommand,
1105}
1106
1107#[derive(Clone, Debug, Error)]
1109#[non_exhaustive]
1110pub enum TracerCommandParseError {
1111 #[error(transparent)]
1113 ShellWordsParse(shell_words::ParseError),
1114
1115 #[error("tracer command cannot be empty")]
1117 EmptyCommand,
1118}
1119
1120#[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 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#[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#[derive(Clone, Debug, Error)]
1176pub enum TestFilterBuildError {
1177 #[error("error constructing test filters")]
1179 Construct {
1180 #[from]
1182 error: aho_corasick::BuildError,
1183 },
1184}
1185
1186#[derive(Debug, Error)]
1188pub enum PathMapperConstructError {
1189 #[error("{kind} `{input}` failed to canonicalize")]
1191 Canonicalization {
1192 kind: PathMapperConstructKind,
1194
1195 input: Utf8PathBuf,
1197
1198 #[source]
1200 err: std::io::Error,
1201 },
1202 #[error("{kind} `{input}` canonicalized to a non-UTF-8 path")]
1204 NonUtf8Path {
1205 kind: PathMapperConstructKind,
1207
1208 input: Utf8PathBuf,
1210
1211 #[source]
1213 err: FromPathBufError,
1214 },
1215 #[error("{kind} `{canonicalized_path}` is not a directory")]
1217 NotADirectory {
1218 kind: PathMapperConstructKind,
1220
1221 input: Utf8PathBuf,
1223
1224 canonicalized_path: Utf8PathBuf,
1226 },
1227}
1228
1229impl PathMapperConstructError {
1230 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 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#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1254pub enum PathMapperConstructKind {
1255 WorkspaceRoot,
1257
1258 TargetDir,
1260
1261 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#[derive(Debug, Error)]
1277pub enum RustBuildMetaParseError {
1278 #[error("error deserializing platform from build metadata")]
1280 PlatformDeserializeError(#[from] target_spec::Error),
1281
1282 #[error("the host platform could not be determined")]
1284 DetectBuildTargetError(#[source] target_spec::Error),
1285
1286 #[error("unsupported features in the build metadata: {message}")]
1288 Unsupported {
1289 message: String,
1291 },
1292}
1293
1294#[derive(Clone, Debug, thiserror::Error)]
1297#[error("invalid format version: {input}")]
1298pub struct FormatVersionError {
1299 pub input: String,
1301 #[source]
1303 pub error: FormatVersionErrorInner,
1304}
1305
1306#[derive(Clone, Debug, thiserror::Error)]
1308pub enum FormatVersionErrorInner {
1309 #[error("expected format version in form of `{expected}`")]
1311 InvalidFormat {
1312 expected: &'static str,
1314 },
1315 #[error("version component `{which}` could not be parsed as an integer")]
1317 InvalidInteger {
1318 which: &'static str,
1320 #[source]
1322 err: std::num::ParseIntError,
1323 },
1324 #[error("version component `{which}` value {value} is out of range {range:?}")]
1326 InvalidValue {
1327 which: &'static str,
1329 value: u8,
1331 range: std::ops::Range<u8>,
1333 },
1334}
1335
1336#[derive(Debug, Error)]
1340#[non_exhaustive]
1341pub enum FromMessagesError {
1342 #[error("error reading Cargo JSON messages")]
1344 ReadMessages(#[source] std::io::Error),
1345
1346 #[error("error querying package graph")]
1348 PackageGraph(#[source] guppy::Error),
1349
1350 #[error("missing kind for target {binary_name} in package {package_name}")]
1352 MissingTargetKind {
1353 package_name: String,
1355 binary_name: String,
1357 },
1358}
1359
1360#[derive(Debug, Error)]
1362#[non_exhaustive]
1363pub enum CreateTestListError {
1364 #[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 binary_id: RustBinaryId,
1372
1373 cwd: Utf8PathBuf,
1375 },
1376
1377 #[error(
1379 "for `{binary_id}`, running command `{}` failed to execute",
1380 shell_words::join(command)
1381 )]
1382 CommandExecFail {
1383 binary_id: RustBinaryId,
1385
1386 command: Vec<String>,
1388
1389 #[source]
1391 error: std::io::Error,
1392 },
1393
1394 #[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 binary_id: RustBinaryId,
1405
1406 command: Vec<String>,
1408
1409 exit_status: ExitStatus,
1411
1412 stdout: Vec<u8>,
1414
1415 stderr: Vec<u8>,
1417 },
1418
1419 #[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 binary_id: RustBinaryId,
1429
1430 command: Vec<String>,
1432
1433 stdout: Vec<u8>,
1435
1436 stderr: Vec<u8>,
1438 },
1439
1440 #[error("for `{binary_id}`, {message}\nfull output:\n{full_output}")]
1442 ParseLine {
1443 binary_id: RustBinaryId,
1445
1446 message: Cow<'static, str>,
1448
1449 full_output: String,
1451 },
1452
1453 #[error(
1455 "error joining dynamic library paths for {}: [{}]",
1456 dylib_path_envvar(),
1457 itertools::join(.new_paths, ", ")
1458 )]
1459 DylibJoinPaths {
1460 new_paths: Vec<Utf8PathBuf>,
1462
1463 #[source]
1465 error: JoinPathsError,
1466 },
1467
1468 #[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#[derive(Debug, Error)]
1493#[non_exhaustive]
1494pub enum WriteTestListError {
1495 #[error("error writing to output")]
1497 Io(#[source] std::io::Error),
1498
1499 #[error("error serializing to JSON")]
1501 Json(#[source] serde_json::Error),
1502}
1503
1504#[derive(Debug, Error)]
1508pub enum ConfigureHandleInheritanceError {
1509 #[cfg(windows)]
1511 #[error("error configuring handle inheritance")]
1512 WindowsError(#[from] std::io::Error),
1513}
1514
1515#[derive(Debug, Error)]
1517#[non_exhaustive]
1518pub enum TestRunnerBuildError {
1519 #[error("error creating Tokio runtime")]
1521 TokioRuntimeCreate(#[source] std::io::Error),
1522
1523 #[error("error setting up signals")]
1525 SignalHandlerSetupError(#[from] SignalHandlerSetupError),
1526}
1527
1528#[derive(Debug, Error)]
1530pub struct TestRunnerExecuteErrors<E> {
1531 pub report_error: Option<E>,
1533
1534 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#[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 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#[derive(Debug, Error)]
1587#[non_exhaustive]
1588pub enum ArchiveCreateError {
1589 #[error("error creating binary list")]
1591 CreateBinaryList(#[source] WriteTestListError),
1592
1593 #[error("extra path `{}` not found", .redactor.redact_path(path))]
1595 MissingExtraPath {
1596 path: Utf8PathBuf,
1598
1599 redactor: Redactor,
1604 },
1605
1606 #[error("while archiving {step}, error writing {} `{path}` to archive", kind_str(*.is_dir))]
1608 InputFileRead {
1609 step: ArchiveStep,
1611
1612 path: Utf8PathBuf,
1614
1615 is_dir: Option<bool>,
1617
1618 #[source]
1620 error: std::io::Error,
1621 },
1622
1623 #[error("error reading directory entry from `{path}")]
1625 DirEntryRead {
1626 path: Utf8PathBuf,
1628
1629 #[source]
1631 error: std::io::Error,
1632 },
1633
1634 #[error("error writing to archive")]
1636 OutputArchiveIo(#[source] std::io::Error),
1637
1638 #[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#[derive(Debug, Error)]
1653pub enum MetadataMaterializeError {
1654 #[error("I/O error reading metadata file `{path}`")]
1656 Read {
1657 path: Utf8PathBuf,
1659
1660 #[source]
1662 error: std::io::Error,
1663 },
1664
1665 #[error("error deserializing metadata file `{path}`")]
1667 Deserialize {
1668 path: Utf8PathBuf,
1670
1671 #[source]
1673 error: serde_json::Error,
1674 },
1675
1676 #[error("error parsing Rust build metadata from `{path}`")]
1678 RustBuildMeta {
1679 path: Utf8PathBuf,
1681
1682 #[source]
1684 error: Box<RustBuildMetaParseError>,
1685 },
1686
1687 #[error("error building package graph from `{path}`")]
1689 PackageGraphConstruct {
1690 path: Utf8PathBuf,
1692
1693 #[source]
1695 error: Box<guppy::Error>,
1696 },
1697}
1698
1699#[derive(Debug, Error)]
1703#[non_exhaustive]
1704pub enum ArchiveReadError {
1705 #[error("I/O error reading archive")]
1707 Io(#[source] std::io::Error),
1708
1709 #[error("path in archive `{}` wasn't valid UTF-8", String::from_utf8_lossy(.0))]
1711 NonUtf8Path(Vec<u8>),
1712
1713 #[error("path in archive `{0}` doesn't start with `target/`")]
1715 NoTargetPrefix(Utf8PathBuf),
1716
1717 #[error("path in archive `{path}` contains an invalid component `{component}`")]
1719 InvalidComponent {
1720 path: Utf8PathBuf,
1722
1723 component: String,
1725 },
1726
1727 #[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 path: Utf8PathBuf,
1738
1739 entry_type: EntryType,
1741 },
1742
1743 #[error("corrupted archive: checksum read error for path `{path}`")]
1745 ChecksumRead {
1746 path: Utf8PathBuf,
1748
1749 #[source]
1751 error: std::io::Error,
1752 },
1753
1754 #[error("corrupted archive: invalid checksum for path `{path}`")]
1756 InvalidChecksum {
1757 path: Utf8PathBuf,
1759
1760 expected: u32,
1762
1763 actual: u32,
1765 },
1766
1767 #[error("metadata file `{0}` not found in archive")]
1769 MetadataFileNotFound(&'static Utf8Path),
1770
1771 #[error("error deserializing metadata file `{path}` in archive")]
1773 MetadataDeserializeError {
1774 path: &'static Utf8Path,
1776
1777 #[source]
1779 error: serde_json::Error,
1780 },
1781
1782 #[error("error building package graph from `{path}` in archive")]
1784 PackageGraphConstructError {
1785 path: &'static Utf8Path,
1787
1788 #[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#[derive(Debug, Error)]
1821#[non_exhaustive]
1822pub enum ArchiveExtractError {
1823 #[error("error creating temporary directory")]
1825 TempDirCreate(#[source] std::io::Error),
1826
1827 #[error("error canonicalizing destination directory `{dir}`")]
1829 DestDirCanonicalization {
1830 dir: Utf8PathBuf,
1832
1833 #[source]
1835 error: std::io::Error,
1836 },
1837
1838 #[error("destination `{0}` already exists")]
1840 DestinationExists(Utf8PathBuf),
1841
1842 #[error("error reading archive")]
1844 Read(#[source] ArchiveReadError),
1845
1846 #[error("error deserializing Rust build metadata")]
1848 RustBuildMeta(#[from] RustBuildMetaParseError),
1849
1850 #[error("error writing file `{path}` to disk")]
1852 WriteFile {
1853 path: Utf8PathBuf,
1855
1856 #[source]
1858 error: std::io::Error,
1859 },
1860
1861 #[error("error reporting extract status")]
1863 ReporterIo(std::io::Error),
1864}
1865
1866#[derive(Debug, Error)]
1868#[non_exhaustive]
1869pub enum WriteEventError {
1870 #[error("error writing to output")]
1872 Io(#[source] std::io::Error),
1873
1874 #[error("error operating on path {file}")]
1876 Fs {
1877 file: Utf8PathBuf,
1879
1880 #[source]
1882 error: std::io::Error,
1883 },
1884
1885 #[error("error writing JUnit output to {file}")]
1887 Junit {
1888 file: Utf8PathBuf,
1890
1891 #[source]
1893 error: quick_junit::SerializeError,
1894 },
1895}
1896
1897#[derive(Debug, Error)]
1900#[non_exhaustive]
1901pub enum CargoConfigError {
1902 #[error("failed to retrieve current directory")]
1904 GetCurrentDir(#[source] std::io::Error),
1905
1906 #[error("current directory is invalid UTF-8")]
1908 CurrentDirInvalidUtf8(#[source] FromPathBufError),
1909
1910 #[error("failed to parse --config argument `{config_str}` as TOML")]
1912 CliConfigParseError {
1913 config_str: String,
1915
1916 #[source]
1918 error: toml_edit::TomlError,
1919 },
1920
1921 #[error("failed to deserialize --config argument `{config_str}` as TOML")]
1923 CliConfigDeError {
1924 config_str: String,
1926
1927 #[source]
1929 error: toml_edit::de::Error,
1930 },
1931
1932 #[error(
1934 "invalid format for --config argument `{config_str}` (should be a dotted key expression)"
1935 )]
1936 InvalidCliConfig {
1937 config_str: String,
1939
1940 #[source]
1942 reason: InvalidCargoCliConfigReason,
1943 },
1944
1945 #[error("non-UTF-8 path encountered")]
1947 NonUtf8Path(#[source] FromPathBufError),
1948
1949 #[error("failed to retrieve the Cargo home directory")]
1951 GetCargoHome(#[source] std::io::Error),
1952
1953 #[error("failed to canonicalize path `{path}")]
1955 FailedPathCanonicalization {
1956 path: Utf8PathBuf,
1958
1959 #[source]
1961 error: std::io::Error,
1962 },
1963
1964 #[error("failed to read config at `{path}`")]
1966 ConfigReadError {
1967 path: Utf8PathBuf,
1969
1970 #[source]
1972 error: std::io::Error,
1973 },
1974
1975 #[error(transparent)]
1977 ConfigParseError(#[from] Box<CargoConfigParseError>),
1978}
1979
1980#[derive(Debug, Error)]
1984#[error("failed to parse config at `{path}`")]
1985pub struct CargoConfigParseError {
1986 pub path: Utf8PathBuf,
1988
1989 #[source]
1991 pub error: toml::de::Error,
1992}
1993
1994#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
1998#[non_exhaustive]
1999pub enum InvalidCargoCliConfigReason {
2000 #[error("was not a TOML dotted key expression (such as `build.jobs = 2`)")]
2002 NotDottedKv,
2003
2004 #[error("includes non-whitespace decoration")]
2006 IncludesNonWhitespaceDecoration,
2007
2008 #[error("sets a value to an inline table, which is not accepted")]
2010 SetsValueToInlineTable,
2011
2012 #[error("sets a value to an array of tables, which is not accepted")]
2014 SetsValueToArrayOfTables,
2015
2016 #[error("doesn't provide a value")]
2018 DoesntProvideValue,
2019}
2020
2021#[derive(Debug, Error)]
2023pub enum HostPlatformDetectError {
2024 #[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 error: std::io::Error,
2037
2038 build_target_error: Box<target_spec::Error>,
2040 },
2041
2042 #[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 status: ExitStatus,
2058
2059 stdout: Vec<u8>,
2061
2062 stderr: Vec<u8>,
2064
2065 build_target_error: Box<target_spec::Error>,
2067 },
2068
2069 #[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 host_platform_error: Box<target_spec::Error>,
2082
2083 build_target_error: Box<target_spec::Error>,
2085 },
2086
2087 #[error("test-only code, so `rustc -vV` was not called; failed to detect build target")]
2090 BuildTargetError {
2091 #[source]
2093 build_target_error: Box<target_spec::Error>,
2094 },
2095}
2096
2097#[derive(Debug, Error)]
2099pub enum TargetTripleError {
2100 #[error(
2102 "environment variable '{}' contained non-UTF-8 data",
2103 TargetTriple::CARGO_BUILD_TARGET_ENV
2104 )]
2105 InvalidEnvironmentVar,
2106
2107 #[error("error deserializing target triple from {source}")]
2109 TargetSpecError {
2110 source: TargetTripleSource,
2112
2113 #[source]
2115 error: target_spec::Error,
2116 },
2117
2118 #[error("target path `{path}` is not a valid file")]
2120 TargetPathReadError {
2121 source: TargetTripleSource,
2123
2124 path: Utf8PathBuf,
2126
2127 #[source]
2129 error: std::io::Error,
2130 },
2131
2132 #[error(
2134 "for custom platform obtained from {source}, \
2135 failed to create temporary directory for custom platform"
2136 )]
2137 CustomPlatformTempDirError {
2138 source: TargetTripleSource,
2140
2141 #[source]
2143 error: std::io::Error,
2144 },
2145
2146 #[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 triple_source: TargetTripleSource,
2156
2157 triple: String,
2159 },
2160
2161 #[error(
2163 "for custom platform obtained from {source}, \
2164 failed to write JSON to temporary path `{path}`"
2165 )]
2166 CustomPlatformWriteError {
2167 source: TargetTripleSource,
2169
2170 path: Utf8PathBuf,
2172
2173 #[source]
2175 error: std::io::Error,
2176 },
2177
2178 #[error(
2180 "for custom platform obtained from {source}, \
2181 failed to close temporary directory `{dir_path}`"
2182 )]
2183 CustomPlatformCloseError {
2184 source: TargetTripleSource,
2186
2187 dir_path: Utf8PathBuf,
2189
2190 #[source]
2192 error: std::io::Error,
2193 },
2194}
2195
2196impl TargetTripleError {
2197 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 TargetTripleError::InvalidEnvironmentVar
2208 | TargetTripleError::TargetPathReadError { .. }
2209 | TargetTripleError::CustomPlatformInvalidTriple { .. }
2210 | TargetTripleError::CustomPlatformTempDirError { .. }
2211 | TargetTripleError::CustomPlatformWriteError { .. }
2212 | TargetTripleError::CustomPlatformCloseError { .. } => None,
2213 }
2214 }
2215}
2216
2217#[derive(Debug, Error)]
2219pub enum TargetRunnerError {
2220 #[error("environment variable '{0}' contained non-UTF-8 data")]
2222 InvalidEnvironmentVar(String),
2223
2224 #[error("runner '{key}' = '{value}' did not contain a runner binary")]
2227 BinaryNotSpecified {
2228 key: PlatformRunnerSource,
2230
2231 value: String,
2233 },
2234}
2235
2236#[derive(Debug, Error)]
2238#[error("error setting up signal handler")]
2239pub struct SignalHandlerSetupError(#[from] std::io::Error);
2240
2241#[derive(Debug, Error)]
2243pub enum ShowTestGroupsError {
2244 #[error(
2246 "unknown test groups specified: {}\n(known groups: {})",
2247 unknown_groups.iter().join(", "),
2248 known_groups.iter().join(", "),
2249 )]
2250 UnknownGroups {
2251 unknown_groups: BTreeSet<TestGroup>,
2253
2254 known_groups: BTreeSet<TestGroup>,
2256 },
2257}
2258
2259#[derive(Debug, Error, PartialEq, Eq, Hash)]
2261pub enum InheritsError {
2262 #[error("the {} profile should not inherit from other profiles", .0)]
2264 DefaultProfileInheritance(String),
2265 #[error("profile {} inherits from an unknown profile {}", .0, .1)]
2267 UnknownInheritance(String, String),
2268 #[error("a self referential inheritance is detected from profile: {}", .0)]
2270 SelfReferentialInheritance(String),
2271 #[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#[derive(Debug, Error)]
2284pub enum RunStoreError {
2285 #[error("error creating run directory `{run_dir}`")]
2287 RunDirCreate {
2288 run_dir: Utf8PathBuf,
2290
2291 #[source]
2293 error: std::io::Error,
2294 },
2295
2296 #[error("error acquiring lock on `{path}`")]
2298 FileLock {
2299 path: Utf8PathBuf,
2301
2302 #[source]
2304 error: std::io::Error,
2305 },
2306
2307 #[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 path: Utf8PathBuf,
2315
2316 timeout_secs: u64,
2318 },
2319
2320 #[error("error reading run list from `{path}`")]
2322 RunListRead {
2323 path: Utf8PathBuf,
2325
2326 #[source]
2328 error: std::io::Error,
2329 },
2330
2331 #[error("error deserializing run list from `{path}`")]
2333 RunListDeserialize {
2334 path: Utf8PathBuf,
2336
2337 #[source]
2339 error: serde_json::Error,
2340 },
2341
2342 #[error("error serializing run list to `{path}`")]
2344 RunListSerialize {
2345 path: Utf8PathBuf,
2347
2348 #[source]
2350 error: serde_json::Error,
2351 },
2352
2353 #[error("error serializing rerun info")]
2355 RerunInfoSerialize {
2356 #[source]
2358 error: serde_json::Error,
2359 },
2360
2361 #[error("error serializing build scope")]
2363 BuildScopeSerialize {
2364 #[source]
2366 error: serde_json::Error,
2367 },
2368
2369 #[error("error serializing test list")]
2371 TestListSerialize {
2372 #[source]
2374 error: serde_json::Error,
2375 },
2376
2377 #[error("error serializing record options")]
2379 RecordOptionsSerialize {
2380 #[source]
2382 error: serde_json::Error,
2383 },
2384
2385 #[error("error serializing test event")]
2387 TestEventSerialize {
2388 #[source]
2390 error: serde_json::Error,
2391 },
2392
2393 #[error("error writing run list to `{path}`")]
2395 RunListWrite {
2396 path: Utf8PathBuf,
2398
2399 #[source]
2401 error: atomicwrites::Error<std::io::Error>,
2402 },
2403
2404 #[error("error writing to store at `{store_path}`")]
2406 StoreWrite {
2407 store_path: Utf8PathBuf,
2409
2410 #[source]
2412 error: StoreWriterError,
2413 },
2414
2415 #[error("error creating run log at `{path}`")]
2417 RunLogCreate {
2418 path: Utf8PathBuf,
2420
2421 #[source]
2423 error: std::io::Error,
2424 },
2425
2426 #[error("error writing to run log at `{path}`")]
2428 RunLogWrite {
2429 path: Utf8PathBuf,
2431
2432 #[source]
2434 error: std::io::Error,
2435 },
2436
2437 #[error("error flushing run log at `{path}`")]
2439 RunLogFlush {
2440 path: Utf8PathBuf,
2442
2443 #[source]
2445 error: std::io::Error,
2446 },
2447
2448 #[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 file_version: RunsJsonFormatVersion,
2456 max_supported_version: RunsJsonFormatVersion,
2458 },
2459}
2460
2461#[derive(Debug, Error)]
2463#[non_exhaustive]
2464pub enum StoreWriterError {
2465 #[error("error creating store")]
2467 Create {
2468 #[source]
2470 error: std::io::Error,
2471 },
2472
2473 #[error("error writing to path `{path}` in store")]
2475 Write {
2476 path: Utf8PathBuf,
2478
2479 #[source]
2481 error: std::io::Error,
2482 },
2483
2484 #[error("error compressing data")]
2486 Compress {
2487 #[source]
2489 error: std::io::Error,
2490 },
2491
2492 #[error("error finalizing store")]
2494 Finish {
2495 #[source]
2497 error: std::io::Error,
2498 },
2499
2500 #[error("error flushing store")]
2502 Flush {
2503 #[source]
2505 error: std::io::Error,
2506 },
2507}
2508
2509#[derive(Debug, Error)]
2511pub enum RecordReporterError {
2512 #[error(transparent)]
2514 RunStore(RunStoreError),
2515
2516 #[error("record writer thread panicked: {message}")]
2518 WriterPanic {
2519 message: String,
2521 },
2522}
2523
2524#[derive(Debug, Error)]
2526pub enum StateDirError {
2527 #[error("could not determine platform base directory strategy")]
2531 BaseDirStrategy(#[source] HomeDirError),
2532
2533 #[error("platform state directory is not valid UTF-8: {path:?}")]
2535 StateDirNotUtf8 {
2536 path: PathBuf,
2538 },
2539
2540 #[error("could not canonicalize workspace path `{workspace_root}`")]
2542 Canonicalize {
2543 workspace_root: Utf8PathBuf,
2545 #[source]
2547 error: std::io::Error,
2548 },
2549}
2550
2551#[derive(Debug, Error)]
2553pub enum RecordSetupError {
2554 #[error("could not determine platform state directory for recording")]
2556 StateDirNotFound(#[source] StateDirError),
2557
2558 #[error("failed to create run store")]
2560 StoreCreate(#[source] RunStoreError),
2561
2562 #[error("failed to lock run store")]
2564 StoreLock(#[source] RunStoreError),
2565
2566 #[error("failed to create run recorder")]
2568 RecorderCreate(#[source] RunStoreError),
2569}
2570
2571#[derive(Debug, Error)]
2573pub enum RecordPruneError {
2574 #[error("error deleting run `{run_id}` at `{path}`")]
2576 DeleteRun {
2577 run_id: ReportUuid,
2579
2580 path: Utf8PathBuf,
2582
2583 #[source]
2585 error: std::io::Error,
2586 },
2587
2588 #[error("error calculating size of `{path}`")]
2590 CalculateSize {
2591 path: Utf8PathBuf,
2593
2594 #[source]
2596 error: std::io::Error,
2597 },
2598
2599 #[error("error deleting orphaned directory `{path}`")]
2601 DeleteOrphan {
2602 path: Utf8PathBuf,
2604
2605 #[source]
2607 error: std::io::Error,
2608 },
2609
2610 #[error("error reading runs directory `{path}`")]
2612 ReadRunsDir {
2613 path: Utf8PathBuf,
2615
2616 #[source]
2618 error: std::io::Error,
2619 },
2620
2621 #[error("error reading directory entry in `{dir}`")]
2623 ReadDirEntry {
2624 dir: Utf8PathBuf,
2626
2627 #[source]
2629 error: std::io::Error,
2630 },
2631
2632 #[error("error reading file type for `{path}`")]
2634 ReadFileType {
2635 path: Utf8PathBuf,
2637
2638 #[source]
2640 error: std::io::Error,
2641 },
2642}
2643
2644#[derive(Clone, Debug, PartialEq, Eq, Error)]
2649#[error("invalid run ID selector `{input}`: expected `latest` or hex digits")]
2650pub struct InvalidRunIdSelector {
2651 pub input: String,
2653}
2654
2655#[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 pub input: String,
2668}
2669
2670#[derive(Debug, Error)]
2672pub enum RunIdResolutionError {
2673 #[error("no recorded run found matching `{prefix}`")]
2675 NotFound {
2676 prefix: String,
2678 },
2679
2680 #[error("prefix `{prefix}` is ambiguous, matches {count} runs")]
2682 Ambiguous {
2683 prefix: String,
2685
2686 count: usize,
2688
2689 candidates: Vec<RecordedRunInfo>,
2691
2692 run_id_index: RunIdIndex,
2694 },
2695
2696 #[error("prefix `{prefix}` contains invalid characters (expected hexadecimal)")]
2698 InvalidPrefix {
2699 prefix: String,
2701 },
2702
2703 #[error("no recorded runs exist")]
2705 NoRuns,
2706}
2707
2708#[derive(Debug, Error)]
2710pub enum RecordReadError {
2711 #[error("run not found at `{path}`")]
2713 RunNotFound {
2714 path: Utf8PathBuf,
2716 },
2717
2718 #[error("error opening archive at `{path}`")]
2720 OpenArchive {
2721 path: Utf8PathBuf,
2723
2724 #[source]
2726 error: std::io::Error,
2727 },
2728
2729 #[error("error parsing archive at `{path}`")]
2731 ParseArchive {
2732 path: Utf8PathBuf,
2734
2735 #[source]
2737 error: std::io::Error,
2738 },
2739
2740 #[error("error reading `{file_name}` from archive")]
2742 ReadArchiveFile {
2743 file_name: String,
2745
2746 #[source]
2748 error: std::io::Error,
2749 },
2750
2751 #[error("error opening run log at `{path}`")]
2753 OpenRunLog {
2754 path: Utf8PathBuf,
2756
2757 #[source]
2759 error: std::io::Error,
2760 },
2761
2762 #[error("error reading line {line_number} from run log")]
2764 ReadRunLog {
2765 line_number: usize,
2767
2768 #[source]
2770 error: std::io::Error,
2771 },
2772
2773 #[error(
2775 "line {line_number} in run log exceeds the maximum size of {}",
2776 SizeDisplay(.limit.0)
2777 )]
2778 RunLogLineTooLong {
2779 line_number: usize,
2781
2782 limit: ByteSize,
2784 },
2785
2786 #[error("error parsing event at line {line_number}")]
2788 ParseEvent {
2789 line_number: usize,
2791
2792 #[source]
2794 error: serde_json::Error,
2795 },
2796
2797 #[error("required file `{file_name}` not found in archive")]
2799 FileNotFound {
2800 file_name: String,
2802 },
2803
2804 #[error("error decompressing data from `{file_name}`")]
2806 Decompress {
2807 file_name: String,
2809
2810 #[source]
2812 error: std::io::Error,
2813 },
2814
2815 #[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 file_name: String,
2826 },
2827
2828 #[error(
2830 "file `{file_name}` in archive exceeds maximum size ({size} bytes, limit is {limit} bytes)"
2831 )]
2832 FileTooLarge {
2833 file_name: String,
2835
2836 size: u64,
2838
2839 limit: u64,
2841 },
2842
2843 #[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 file_name: String,
2854
2855 claimed_size: u64,
2857
2858 actual_size: u64,
2860 },
2861
2862 #[error("error deserializing `{file_name}`")]
2864 DeserializeMetadata {
2865 file_name: String,
2867
2868 #[source]
2870 error: serde_json::Error,
2871 },
2872
2873 #[error("failed to extract `{store_path}` to `{output_path}`")]
2875 ExtractFile {
2876 store_path: String,
2878
2879 output_path: Utf8PathBuf,
2881
2882 #[source]
2884 error: std::io::Error,
2885 },
2886
2887 #[error("error reading portable recording")]
2889 PortableRecording(#[source] PortableRecordingReadError),
2890}
2891
2892#[derive(Debug, Error)]
2894#[non_exhaustive]
2895pub enum PortableRecordingError {
2896 #[error("run directory does not exist: {path}")]
2898 RunDirNotFound {
2899 path: Utf8PathBuf,
2901 },
2902
2903 #[error("required file missing from run directory `{run_dir}`: `{file_name}`")]
2905 RequiredFileMissing {
2906 run_dir: Utf8PathBuf,
2908 file_name: &'static str,
2910 },
2911
2912 #[error("failed to serialize manifest")]
2914 SerializeManifest(#[source] serde_json::Error),
2915
2916 #[error("failed to start file {file_name} in archive")]
2918 ZipStartFile {
2919 file_name: &'static str,
2921 #[source]
2923 source: std::io::Error,
2924 },
2925
2926 #[error("failed to write {file_name} to archive")]
2928 ZipWrite {
2929 file_name: &'static str,
2931 #[source]
2933 source: std::io::Error,
2934 },
2935
2936 #[error("failed to read {file_name}")]
2938 ReadFile {
2939 file_name: &'static str,
2941 #[source]
2943 source: std::io::Error,
2944 },
2945
2946 #[error("failed to finalize archive")]
2948 ZipFinalize(#[source] std::io::Error),
2949
2950 #[error("failed to write archive atomically to {path}")]
2952 AtomicWrite {
2953 path: Utf8PathBuf,
2955 #[source]
2957 source: std::io::Error,
2958 },
2959}
2960
2961#[derive(Debug, Error)]
2963#[non_exhaustive]
2964pub enum PortableRecordingReadError {
2965 #[error("failed to open archive at `{path}`")]
2967 OpenArchive {
2968 path: Utf8PathBuf,
2970 #[source]
2972 error: std::io::Error,
2973 },
2974
2975 #[error("failed to read archive at `{path}`")]
2977 ReadArchive {
2978 path: Utf8PathBuf,
2980 #[source]
2982 error: std::io::Error,
2983 },
2984
2985 #[error("required file `{file_name}` missing from archive at `{path}`")]
2987 MissingFile {
2988 path: Utf8PathBuf,
2990 file_name: Cow<'static, str>,
2992 },
2993
2994 #[error("failed to parse manifest from archive at `{path}`")]
2996 ParseManifest {
2997 path: Utf8PathBuf,
2999 #[source]
3001 error: serde_json::Error,
3002 },
3003
3004 #[error(
3006 "portable recording format version {found} in `{path}` is incompatible: {incompatibility} \
3007 (this nextest supports version {supported})"
3008 )]
3009 UnsupportedFormatVersion {
3010 path: Utf8PathBuf,
3012 found: PortableRecordingFormatVersion,
3014 supported: PortableRecordingFormatVersion,
3016 incompatibility: PortableRecordingVersionIncompatibility,
3018 },
3019
3020 #[error("store format version {found} in `{path}` is incompatible: {incompatibility}")]
3022 UnsupportedStoreFormatVersion {
3023 path: Utf8PathBuf,
3025 found: StoreFormatVersion,
3027 supported: StoreFormatVersion,
3029 incompatibility: StoreVersionIncompatibility,
3031 },
3032
3033 #[error(
3035 "file `{file_name}` in archive `{path}` is too large \
3036 ({size} bytes, limit is {limit} bytes)"
3037 )]
3038 FileTooLarge {
3039 path: Utf8PathBuf,
3041 file_name: Cow<'static, str>,
3043 size: u64,
3045 limit: u64,
3047 },
3048
3049 #[error("failed to extract `{file_name}` from archive `{archive_path}` to `{output_path}`")]
3051 ExtractFile {
3052 archive_path: Utf8PathBuf,
3054 file_name: &'static str,
3056 output_path: Utf8PathBuf,
3058 #[source]
3060 error: std::io::Error,
3061 },
3062
3063 #[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 archive_path: Utf8PathBuf,
3074 compression: CompressionMethod,
3076 },
3077
3078 #[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 path: Utf8PathBuf,
3090 file_count: usize,
3092 zip_count: usize,
3094 },
3095
3096 #[error("unexpected I/O error while probing seekability of `{path}`")]
3103 SeekProbe {
3104 path: Utf8PathBuf,
3106 #[source]
3108 error: std::io::Error,
3109 },
3110
3111 #[error("failed to spool non-seekable input `{path}` to a temporary file")]
3117 SpoolTempFile {
3118 path: Utf8PathBuf,
3120 #[source]
3122 error: std::io::Error,
3123 },
3124
3125 #[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 path: Utf8PathBuf,
3134 limit: ByteSize,
3136 },
3137}
3138
3139#[derive(Debug, Error)]
3141pub enum ChromeTraceError {
3142 #[error("error reading recorded events")]
3144 ReadError(#[source] RecordReadError),
3145
3146 #[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 test_name: TestCaseName,
3154
3155 binary_id: RustBinaryId,
3157 },
3158
3159 #[error(
3161 "SetupScriptSlow for script `{script_id}` \
3162 has no prior SetupScriptStarted event (corrupt or truncated log?)"
3163 )]
3164 MissingScriptStart {
3165 script_id: ScriptId,
3167 },
3168
3169 #[error(
3172 "StressSubRunFinished has no prior StressSubRunStarted event \
3173 (corrupt or truncated log?)"
3174 )]
3175 MissingStressSubRunStart,
3176
3177 #[error("error serializing Chrome trace JSON")]
3179 SerializeError(#[source] serde_json::Error),
3180}
3181
3182#[derive(Debug, Error)]
3186pub enum TestListFromSummaryError {
3187 #[error("package `{name}` (id: `{package_id}`) not found in cargo metadata")]
3189 PackageNotFound {
3190 name: String,
3192
3193 package_id: String,
3195 },
3196
3197 #[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 #[derive(Debug, Error)]
3214 #[non_exhaustive]
3215 pub enum UpdateError {
3216 #[error("failed to read release metadata from `{path}`")]
3218 ReadLocalMetadata {
3219 path: Utf8PathBuf,
3221
3222 #[source]
3224 error: std::io::Error,
3225 },
3226
3227 #[error("self-update failed")]
3229 SelfUpdate(#[source] self_update::errors::Error),
3230
3231 #[error("error performing HTTP request")]
3233 Http(#[source] ureq::Error),
3234
3235 #[error("error reading HTTP response body")]
3237 HttpBody(#[source] std::io::Error),
3238
3239 #[error("Content-Length header present but could not be parsed as an integer: {value:?}")]
3242 ContentLengthInvalid {
3243 value: String,
3245 },
3246
3247 #[error("content length mismatch: expected {expected} bytes, received {actual} bytes")]
3250 ContentLengthMismatch {
3251 expected: u64,
3253 actual: u64,
3255 },
3256
3257 #[error("deserializing release metadata failed")]
3259 ReleaseMetadataDe(#[source] serde_json::Error),
3260
3261 #[error("version `{version}` not found (known versions: {})", known_versions(.known))]
3263 VersionNotFound {
3264 version: Version,
3266
3267 known: Vec<(Version, ReleaseStatus)>,
3269 },
3270
3271 #[error("no version found matching requirement `{req}`")]
3273 NoMatchForVersionReq {
3274 req: VersionReq,
3276 },
3277
3278 #[error("no stable version found")]
3280 NoStableVersion,
3281
3282 #[error("no version found matching {} channel", kind.description())]
3284 NoVersionForPrereleaseKind {
3285 kind: PrereleaseKind,
3287 },
3288
3289 #[error("project {not_found} not found in release metadata (known projects: {})", known.join(", "))]
3291 MuktiProjectNotFound {
3292 not_found: String,
3294
3295 known: Vec<String>,
3297 },
3298
3299 #[error(
3301 "for version {version}, no release information found for target `{triple}` \
3302 (known targets: {})",
3303 known_triples.iter().join(", ")
3304 )]
3305 NoTargetData {
3306 version: Version,
3308
3309 triple: String,
3311
3312 known_triples: BTreeSet<String>,
3314 },
3315
3316 #[error("the current executable's path could not be determined")]
3318 CurrentExe(#[source] std::io::Error),
3319
3320 #[error("temporary directory could not be created at `{location}`")]
3322 TempDirCreate {
3323 location: Utf8PathBuf,
3325
3326 #[source]
3328 error: std::io::Error,
3329 },
3330
3331 #[error("temporary archive could not be created at `{archive_path}`")]
3333 TempArchiveCreate {
3334 archive_path: Utf8PathBuf,
3336
3337 #[source]
3339 error: std::io::Error,
3340 },
3341
3342 #[error("error writing to temporary archive at `{archive_path}`")]
3344 TempArchiveWrite {
3345 archive_path: Utf8PathBuf,
3347
3348 #[source]
3350 error: std::io::Error,
3351 },
3352
3353 #[error("error reading from temporary archive at `{archive_path}`")]
3355 TempArchiveRead {
3356 archive_path: Utf8PathBuf,
3358
3359 #[source]
3361 error: std::io::Error,
3362 },
3363
3364 #[error("SHA-256 checksum mismatch: expected: {expected}, actual: {actual}")]
3366 ChecksumMismatch {
3367 expected: mukti_metadata::Digest,
3369
3370 actual: HexArray<32>,
3372 },
3373
3374 #[error("error renaming `{source}` to `{dest}`")]
3376 FsRename {
3377 source: Utf8PathBuf,
3379
3380 dest: Utf8PathBuf,
3382
3383 #[source]
3385 error: std::io::Error,
3386 },
3387
3388 #[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 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 #[derive(Debug, Error)]
3420 pub enum UpdateVersionParseError {
3421 #[error("version string is empty")]
3423 EmptyString,
3424
3425 #[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 input: String,
3433
3434 #[source]
3436 error: semver::Error,
3437 },
3438
3439 #[error("`{input}` is not a valid semver{}", extra_semver_output(.input))]
3441 InvalidVersion {
3442 input: String,
3444
3445 #[source]
3447 error: semver::Error,
3448 },
3449 }
3450
3451 fn extra_semver_output(input: &str) -> String {
3452 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}