#![deny(missing_docs)]
use std::fmt;
use std::io;
use std::num::ParseIntError;
use std::sync::Arc;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug, Clone)]
#[non_exhaustive]
pub enum Error {
#[error("IO error: {0}")]
Io(#[source] Shared<io::Error>),
#[cfg(feature = "io")]
#[error("HTTP error: {0}")]
Http(#[source] Shared<reqwest::Error>),
#[error("JSON error: {0}")]
Json(#[source] Shared<serde_json::Error>),
#[cfg(feature = "io")]
#[error("ZIP error: {0}")]
Zip(#[source] Shared<zip::result::ZipError>),
#[cfg(feature = "io")]
#[error("Header error: {0}")]
Header(#[source] Shared<reqwest::header::ToStrError>),
#[error("Parse integer error: {0}")]
ParseInt(#[from] ParseIntError),
#[error("Missing header: {0}")]
MissingHeader(String),
#[error("Configuration error: {0}")]
Config(String),
#[error("manifest parse error: {0}")]
ManifestParse(String),
#[error("cache error: {0}")]
Cache(String),
#[error("{context} exceeds size limit of {limit} bytes")]
SizeLimitExceeded {
context: String,
limit: u64,
actual: Option<u64>,
},
#[error("incomplete download: expected {expected} bytes, received {actual}")]
IncompleteDownload {
expected: u64,
actual: u64,
},
#[error("unsafe name: {0}")]
UnsafeName(String),
#[error("unsupported cache format version {found} (expected {expected})")]
UnsupportedCacheVersion {
found: u32,
expected: u32,
},
#[error("Ecosystem error: {0}")]
Ecosystem(String),
#[error("Install error: {0}")]
Install(String),
#[error("Profile error: {0}")]
Profile(String),
#[error("Profile error: {0}")]
BadProfile(#[from] crate::profile::layout::BadProfile),
#[error("Profile error: {package} is not installed")]
NotInstalled {
package: String,
},
#[error("Profile error: cannot install {package}: could not resolve {}", .unresolved.join(", "))]
UnresolvedDependency {
package: String,
unresolved: Vec<String>,
},
#[error("Profile error: cannot install {package}-{version}: {package} has no version {version}")]
MissingVersion {
package: String,
version: String,
},
#[error("Profile error: unknown game {game:?}")]
UnknownGame {
game: String,
},
#[error("Profile error: no ecosystem profile for game {game:?}")]
NoGameProfile {
game: String,
},
#[error("Profile error: no {loader:?} mod loader is installed")]
NoModLoader {
loader: crate::ecosystem::LoaderKind,
},
#[error("Profile error: the game folder {} does not exist", .path.display())]
MissingGameDir {
path: std::path::PathBuf,
},
#[error("{} of {total} downloads failed: {}", .failures.len(), list_failures(.failures))]
Download {
total: usize,
failures: Vec<(String, Error)>,
},
#[error(
"Profile error: {}; the import is unfinished (its config files were not restored)",
list_import_failures(.failures)
)]
ImportUnfinished {
failures: Vec<(String, Error)>,
},
#[error("invalid header: {0}")]
InvalidHeader(String),
#[error("Archive extraction limit exceeded: {0}")]
ExtractLimitExceeded(String),
#[error("CRC32 verification failed for {path}: expected {expected:08x}, got {actual:08x}")]
ChecksumMismatch {
path: String,
expected: u32,
actual: u32,
},
}
fn list_failures(failures: &[(String, Error)]) -> String {
failures
.iter()
.map(|(name, error)| format!("{name}: {error}"))
.collect::<Vec<_>>()
.join("; ")
}
#[derive(Debug)]
pub struct Shared<T>(Arc<T>);
impl<T> Clone for Shared<T> {
fn clone(&self) -> Self {
Self(Arc::clone(&self.0))
}
}
impl<T> std::ops::Deref for Shared<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T: fmt::Display> fmt::Display for Shared<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
fn list_import_failures(failures: &[(String, Error)]) -> String {
failures
.iter()
.map(|(name, error)| format!("importing {name}: {error}"))
.collect::<Vec<_>>()
.join("; ")
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self::Io(Shared(Arc::new(error)))
}
}
#[cfg(feature = "io")]
impl From<reqwest::Error> for Error {
fn from(error: reqwest::Error) -> Self {
Self::Http(Shared(Arc::new(error)))
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Self {
Self::Json(Shared(Arc::new(error)))
}
}
#[cfg(feature = "io")]
impl From<zip::result::ZipError> for Error {
fn from(error: zip::result::ZipError) -> Self {
Self::Zip(Shared(Arc::new(error)))
}
}
#[cfg(feature = "io")]
impl From<reqwest::header::ToStrError> for Error {
fn from(error: reqwest::header::ToStrError) -> Self {
Self::Header(Shared(Arc::new(error)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profile_error_displays_message() {
let err = Error::Profile("bad profile".to_string());
assert_eq!(err.to_string(), "Profile error: bad profile");
}
#[test]
fn a_cloned_error_keeps_its_message_and_source() {
let err = Error::from(io::Error::new(io::ErrorKind::NotFound, "gone"));
let kept = err.clone();
assert_eq!(kept.to_string(), "IO error: gone");
assert_eq!(
std::error::Error::source(&kept).map(|source| source.to_string()),
Some("gone".to_string())
);
}
#[test]
fn a_wrapped_source_downcasts_to_the_original_error() {
let io = Error::from(io::Error::new(io::ErrorKind::NotFound, "gone"));
let json = Error::from(serde_json::from_str::<u8>("x").unwrap_err());
let io_source =
std::error::Error::source(&io).and_then(|source| source.downcast_ref::<io::Error>());
let json_source = std::error::Error::source(&json)
.and_then(|source| source.downcast_ref::<serde_json::Error>());
assert_eq!(
io_source.map(io::Error::kind),
Some(io::ErrorKind::NotFound)
);
assert!(json_source.is_some());
}
}