use std::fmt;
use std::path::{Path, PathBuf};
use geolith::error::GeolithError;
use crate::exit::Exit;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IoOp {
Read,
Write,
Create,
Open,
Remove,
Rename,
RenameTo,
List,
Stat,
Seek,
}
impl fmt::Display for IoOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Read => "reading",
Self::Write => "writing",
Self::Create => "creating",
Self::Open => "opening",
Self::Remove => "removing",
Self::Rename => "renaming",
Self::RenameTo => "renaming to",
Self::List => "listing",
Self::Stat => "reading the metadata of",
Self::Seek => "seeking in",
})
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DatasetError {
#[error("{op} {}", path.display())]
Io {
op: IoOp,
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("i/o error")]
Os(#[from] std::io::Error),
#[error("{what}")]
IoStep {
what: String,
#[source]
source: std::io::Error,
},
#[error("{op} {}", path.display())]
Reader {
op: IoOp,
path: PathBuf,
#[source]
source: GeolithError,
},
#[error("{op} {}", path.display())]
ParquetFile {
op: IoOp,
path: PathBuf,
#[source]
source: parquet::errors::ParquetError,
},
#[error("{op} {}", path.display())]
TiffFile {
op: IoOp,
path: PathBuf,
#[source]
source: tiff::TiffError,
},
#[error("{op} {}", path.display())]
ShapeFile {
op: IoOp,
path: PathBuf,
#[source]
source: shapefile::Error,
},
#[error("{op} {}", path.display())]
JsonFile {
op: IoOp,
path: PathBuf,
#[source]
source: serde_json::Error,
},
#[error("{op} {}", path.display())]
DbfFile {
op: IoOp,
path: PathBuf,
#[source]
source: shapefile::dbase::Error,
},
#[error("{what}")]
Geometry {
what: String,
#[source]
source: Box<geojson::Error>,
},
#[error("{what}")]
Within {
what: String,
#[source]
source: Box<DatasetError>,
},
#[error("interior NUL byte")]
Nul(#[from] std::ffi::NulError),
#[error("geometry error")]
Wkb(#[from] geozero::error::GeozeroError),
#[error("path error")]
Prefix(#[from] std::path::StripPrefixError),
#[error("thread pool error")]
Pool(#[from] rayon::ThreadPoolBuildError),
#[error("not UTF-8")]
Utf8Text(#[from] std::string::FromUtf8Error),
#[error("request failed")]
Request(#[source] Box<ureq::Error>),
#[error("not UTF-8")]
Utf8Bytes(#[from] std::str::Utf8Error),
#[error("system clock is before 1970")]
Clock(#[source] std::time::SystemTimeError),
#[error("json error")]
JsonBare(#[from] serde_json::Error),
#[error("parsing {}", path.display())]
Json {
path: PathBuf,
#[source]
source: serde_json::Error,
},
#[error("{what}")]
JsonValue {
what: String,
#[source]
source: serde_json::Error,
},
#[error("{what} is not UTF-8")]
Utf8 {
what: String,
#[source]
source: std::string::FromUtf8Error,
},
#[error("{what}")]
Number {
what: String,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("{method} {url}")]
Http {
method: &'static str,
url: String,
#[source]
source: Box<ureq::Error>,
},
#[error("{method} {target}: HTTP {status}")]
HttpStatus {
method: &'static str,
target: String,
status: u16,
},
#[error("{tool} {command} failed{}: {stderr}", exit_text(*code))]
Tool {
tool: String,
command: String,
code: Option<i32>,
stderr: String,
},
#[error("cannot run {tool}")]
ToolStart {
tool: String,
#[source]
source: std::io::Error,
},
#[error(transparent)]
Exit(#[from] Exit),
#[error("{0}")]
Usage(String),
#[error("{0}")]
Config(String),
#[error("{0}")]
Data(String),
#[error("{0}")]
Stage(String),
#[error("{0}")]
Storage(String),
#[error("{0}")]
Fetch(String),
#[error("a worker panicked")]
WorkerPanicked,
#[error(transparent)]
Geolith(#[from] GeolithError),
#[error("parquet error")]
Parquet(#[from] parquet::errors::ParquetError),
#[error("arrow error")]
Arrow(#[from] arrow::error::ArrowError),
#[error("tiff error")]
Tiff(#[from] tiff::TiffError),
}
fn exit_text(code: Option<i32>) -> String {
code.map_or_else(String::new, |code| format!(" (exit {code})"))
}
impl From<ureq::Error> for DatasetError {
fn from(source: ureq::Error) -> Self {
Self::Request(Box::new(source))
}
}
pub type Result<T, E = DatasetError> = std::result::Result<T, E>;
impl DatasetError {
#[must_use]
pub fn usage(message: impl Into<String>) -> Self {
Self::Usage(message.into())
}
#[must_use]
pub fn config(message: impl Into<String>) -> Self {
Self::Config(message.into())
}
#[must_use]
pub fn data(message: impl Into<String>) -> Self {
Self::Data(message.into())
}
#[must_use]
pub fn stage(message: impl Into<String>) -> Self {
Self::Stage(message.into())
}
#[must_use]
pub fn storage(message: impl Into<String>) -> Self {
Self::Storage(message.into())
}
#[must_use]
pub fn fetch(message: impl Into<String>) -> Self {
Self::Fetch(message.into())
}
#[must_use]
pub const fn exit(&self) -> Option<Exit> {
match self {
Self::Exit(exit) => Some(*exit),
_ => None,
}
}
#[must_use]
pub const fn exit_code(&self) -> i32 {
match self {
Self::Exit(exit) => exit.0,
_ => 1,
}
}
}
pub trait AtPath {
fn at_path(self, op: IoOp, path: &Path) -> DatasetError;
}
macro_rules! at_path {
($($source:ty => $variant:ident),+ $(,)?) => {$(
impl AtPath for $source {
fn at_path(self, op: IoOp, path: &Path) -> DatasetError {
DatasetError::$variant { op, path: path.to_path_buf(), source: self }
}
}
)+};
}
at_path! {
std::io::Error => Io,
GeolithError => Reader,
parquet::errors::ParquetError => ParquetFile,
tiff::TiffError => TiffFile,
shapefile::Error => ShapeFile,
serde_json::Error => JsonFile,
shapefile::dbase::Error => DbfFile,
}
pub trait IoResultExt<T> {
fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T>;
}
impl<T, E: AtPath> IoResultExt<T> for std::result::Result<T, E> {
fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T> {
self.map_err(|source| source.at_path(op, path.as_ref()))
}
}
pub trait JsonResultExt<T> {
fn json_at(self, path: impl AsRef<Path>) -> Result<T>;
fn json_of(self, what: impl Into<String>) -> Result<T>;
}
impl<T> JsonResultExt<T> for serde_json::Result<T> {
fn json_at(self, path: impl AsRef<Path>) -> Result<T> {
self.map_err(|source| DatasetError::Json {
path: path.as_ref().to_path_buf(),
source,
})
}
fn json_of(self, what: impl Into<String>) -> Result<T> {
self.map_err(|source| DatasetError::JsonValue {
what: what.into(),
source,
})
}
}
pub trait NumberError: std::error::Error + Send + Sync + 'static {}
impl NumberError for std::num::ParseIntError {}
impl NumberError for std::num::ParseFloatError {}
impl NumberError for std::num::TryFromIntError {}
pub trait NumberResultExt<T> {
fn number_of(self, what: impl Into<String>) -> Result<T>;
}
impl<T, E: NumberError> NumberResultExt<T> for std::result::Result<T, E> {
fn number_of(self, what: impl Into<String>) -> Result<T> {
self.map_err(|source| DatasetError::Number {
what: what.into(),
source: Box::new(source),
})
}
}
pub trait WithinExt<T> {
fn within(self, what: impl Into<String>) -> Result<T>;
}
impl<T, E: Into<DatasetError>> WithinExt<T> for std::result::Result<T, E> {
fn within(self, what: impl Into<String>) -> Result<T> {
self.map_err(|source| DatasetError::Within {
what: what.into(),
source: Box::new(source.into()),
})
}
}
pub trait IoStepExt<T> {
fn io_step(self, what: impl Into<String>) -> Result<T>;
}
impl<T> IoStepExt<T> for std::io::Result<T> {
fn io_step(self, what: impl Into<String>) -> Result<T> {
self.map_err(|source| DatasetError::IoStep {
what: what.into(),
source,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_io_error_names_the_operation_and_the_file() {
let err = std::fs::read_to_string("/nonexistent/geolith/areas.geojson")
.io_at(IoOp::Read, "/nonexistent/geolith/areas.geojson")
.expect_err("the file does not exist");
assert_eq!(
err.to_string(),
"reading /nonexistent/geolith/areas.geojson"
);
let line = geolith::error::report(&err);
assert!(
line.starts_with("reading /nonexistent/geolith/areas.geojson: "),
"{line}"
);
}
#[test]
fn an_exit_error_gives_its_code() {
assert_eq!(DatasetError::Exit(Exit(3)).exit_code(), 3);
assert_eq!(DatasetError::usage("--x").exit_code(), 1);
}
#[test]
fn a_tool_error_prints_the_exit_code_when_there_is_one() {
let err = DatasetError::Tool {
tool: "unzip".to_owned(),
command: "a.zip".to_owned(),
code: Some(9),
stderr: "bad zip".to_owned(),
};
assert_eq!(err.to_string(), "unzip a.zip failed (exit 9): bad zip");
}
}