// SPDX-License-Identifier: Apache-2.0 OR MIT use alloc::{ boxed::Box, format, string::{String, ToString as _}, }; use core::fmt; use std::{ffi::OsString, io}; macro_rules! format_err { ($($tt:tt)*) => { crate::Error::new(alloc::format!($($tt)*)) }; } macro_rules! bail { ($($tt:tt)*) => { return Err(format_err!($($tt)*)) }; } pub(crate) type Result = core::result::Result; /// An error that occurred during loading or resolving the Cargo configuration. #[derive(Debug)] pub struct Error(ErrorKind); // Hiding error variants from a library's public error type to prevent // dependency updates from becoming breaking changes. // We can add `is_*` methods that indicate the kind of error if needed, but // don't expose dependencies' types directly in the public API. #[derive(Debug)] pub(crate) enum ErrorKind { Io(io::Error), CfgExprParse(crate::cfg_expr::error::ParseError), Other(Box), WithContext(Box, Option>), } impl Error { pub(crate) fn new(e: impl Into) -> Self { Self(e.into()) } pub(crate) fn env_not_unicode(name: &str, var: OsString) -> Self { Self(ErrorKind::WithContext( format!("failed to parse environment variable `{name}`").into_boxed_str(), Some(Box::new(std::env::VarError::NotUnicode(var))), )) } pub(crate) fn env_not_unicode_redacted(name: &str) -> Self { Self(ErrorKind::WithContext( format!("failed to parse environment variable `{name}`").into_boxed_str(), Some("environment variable was not valid unicode: [REDACTED]".into()), )) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.0 { ErrorKind::Io(e) => fmt::Display::fmt(e, f), ErrorKind::CfgExprParse(e) => fmt::Display::fmt(e, f), ErrorKind::Other(e) | ErrorKind::WithContext(e, ..) => fmt::Display::fmt(e, f), } } } impl core::error::Error for Error { fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { match &self.0 { ErrorKind::Io(e) => e.source(), ErrorKind::CfgExprParse(e) => e.source(), ErrorKind::Other(_) => None, ErrorKind::WithContext(_, e) => Some(&**e.as_ref()?), } } } // TODO: consider removing this in the next breaking release impl From for io::Error { fn from(e: Error) -> Self { match e.0 { ErrorKind::Io(e) => e, ErrorKind::CfgExprParse(e) => Self::other(e), ErrorKind::Other(e) | ErrorKind::WithContext(e, None) => Self::other(e.into_string()), ErrorKind::WithContext(msg, Some(source)) => { let kind = if let Some(e) = source.downcast_ref::() { e.kind() } else if source.downcast_ref::().is_some() { io::ErrorKind::InvalidData } else { io::ErrorKind::Other }; Self::new(kind, Error(ErrorKind::WithContext(msg, Some(source)))) } } } } impl From for ErrorKind { fn from(s: String) -> Self { Self::Other(s.into_boxed_str()) } } impl From for ErrorKind { fn from(e: crate::cfg_expr::error::ParseError) -> Self { Self::CfgExprParse(e) } } // Note: Do not implement From to prevent dependency // updates from becoming breaking changes. // Implementing `From` should also be avoided whenever possible, // as it would be a breaking change to remove the implementation if the // conversion is no longer needed due to changes in the internal implementation. // TODO(semver): consider removing them in the next breaking release impl From for Error { fn from(e: io::Error) -> Self { Self(ErrorKind::Io(e)) } } // TODO(semver): this is no longer used in our code; remove in the next breaking release impl From for Error { fn from(e: std::env::VarError) -> Self { Self(ErrorKind::Other(e.to_string().into_boxed_str())) } } // Inspired by anyhow::Context. pub(crate) trait Context { fn context(self, context: C) -> Result where C: fmt::Display; fn with_context(self, context: F) -> Result where C: fmt::Display, F: FnOnce() -> C; } impl Context for Result where E: core::error::Error + Send + Sync + 'static, { fn context(self, context: C) -> Result where C: fmt::Display, { match self { Ok(ok) => Ok(ok), Err(e) => Err(Error(ErrorKind::WithContext( context.to_string().into_boxed_str(), Some(Box::new(e)), ))), } } fn with_context(self, context: F) -> Result where C: fmt::Display, F: FnOnce() -> C, { match self { Ok(ok) => Ok(ok), Err(e) => Err(Error(ErrorKind::WithContext( context().to_string().into_boxed_str(), Some(Box::new(e)), ))), } } } impl Context for Option { fn context(self, context: C) -> Result where C: fmt::Display, { match self { Some(ok) => Ok(ok), None => Err(Error(ErrorKind::WithContext(context.to_string().into_boxed_str(), None))), } } fn with_context(self, context: F) -> Result where C: fmt::Display, F: FnOnce() -> C, { match self { Some(ok) => Ok(ok), None => { Err(Error(ErrorKind::WithContext(context().to_string().into_boxed_str(), None))) } } } }