1use std::fmt;
21use std::path::{Path, PathBuf};
22
23use geolith::error::GeolithError;
24
25use crate::exit::Exit;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum IoOp {
31 Read,
33 Write,
35 Create,
37 Open,
39 Remove,
41 Rename,
43 RenameTo,
45 List,
47 Stat,
49 Seek,
51}
52
53impl fmt::Display for IoOp {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 f.write_str(match self {
56 Self::Read => "reading",
57 Self::Write => "writing",
58 Self::Create => "creating",
59 Self::Open => "opening",
60 Self::Remove => "removing",
61 Self::Rename => "renaming",
62 Self::RenameTo => "renaming to",
63 Self::List => "listing",
64 Self::Stat => "reading the metadata of",
65 Self::Seek => "seeking in",
66 })
67 }
68}
69
70#[derive(Debug, thiserror::Error)]
72#[non_exhaustive]
73pub enum DatasetError {
74 #[error("{op} {}", path.display())]
76 Io {
77 op: IoOp,
79 path: PathBuf,
81 #[source]
83 source: std::io::Error,
84 },
85
86 #[error("i/o error")]
88 Os(#[from] std::io::Error),
89
90 #[error("{what}")]
92 IoStep {
93 what: String,
95 #[source]
97 source: std::io::Error,
98 },
99
100 #[error("{op} {}", path.display())]
102 Reader {
103 op: IoOp,
105 path: PathBuf,
107 #[source]
109 source: GeolithError,
110 },
111
112 #[error("{op} {}", path.display())]
114 ParquetFile {
115 op: IoOp,
117 path: PathBuf,
119 #[source]
121 source: parquet::errors::ParquetError,
122 },
123
124 #[error("{op} {}", path.display())]
126 TiffFile {
127 op: IoOp,
129 path: PathBuf,
131 #[source]
133 source: tiff::TiffError,
134 },
135
136 #[error("{op} {}", path.display())]
138 ShapeFile {
139 op: IoOp,
141 path: PathBuf,
143 #[source]
145 source: shapefile::Error,
146 },
147
148 #[error("{op} {}", path.display())]
150 JsonFile {
151 op: IoOp,
153 path: PathBuf,
155 #[source]
157 source: serde_json::Error,
158 },
159
160 #[error("{op} {}", path.display())]
162 DbfFile {
163 op: IoOp,
165 path: PathBuf,
167 #[source]
169 source: shapefile::dbase::Error,
170 },
171
172 #[error("{what}")]
174 Geometry {
175 what: String,
177 #[source]
179 source: Box<geojson::Error>,
180 },
181
182 #[error("{what}")]
184 Within {
185 what: String,
187 #[source]
189 source: Box<DatasetError>,
190 },
191
192 #[error("interior NUL byte")]
194 Nul(#[from] std::ffi::NulError),
195
196 #[error("geometry error")]
198 Wkb(#[from] geozero::error::GeozeroError),
199
200 #[error("path error")]
202 Prefix(#[from] std::path::StripPrefixError),
203
204 #[error("thread pool error")]
206 Pool(#[from] rayon::ThreadPoolBuildError),
207
208 #[error("not UTF-8")]
210 Utf8Text(#[from] std::string::FromUtf8Error),
211
212 #[error("request failed")]
214 Request(#[source] Box<ureq::Error>),
215
216 #[error("not UTF-8")]
218 Utf8Bytes(#[from] std::str::Utf8Error),
219
220 #[error("system clock is before 1970")]
222 Clock(#[source] std::time::SystemTimeError),
223
224 #[error("json error")]
226 JsonBare(#[from] serde_json::Error),
227
228 #[error("parsing {}", path.display())]
230 Json {
231 path: PathBuf,
233 #[source]
235 source: serde_json::Error,
236 },
237
238 #[error("{what}")]
240 JsonValue {
241 what: String,
243 #[source]
245 source: serde_json::Error,
246 },
247
248 #[error("{what} is not UTF-8")]
250 Utf8 {
251 what: String,
253 #[source]
255 source: std::string::FromUtf8Error,
256 },
257
258 #[error("{what}")]
260 Number {
261 what: String,
263 #[source]
265 source: Box<dyn std::error::Error + Send + Sync>,
266 },
267
268 #[error("{method} {url}")]
270 Http {
271 method: &'static str,
273 url: String,
275 #[source]
277 source: Box<ureq::Error>,
278 },
279
280 #[error("{method} {target}: HTTP {status}")]
282 HttpStatus {
283 method: &'static str,
285 target: String,
287 status: u16,
289 },
290
291 #[error("{tool} {command} failed{}: {stderr}", exit_text(*code))]
293 Tool {
294 tool: String,
296 command: String,
298 code: Option<i32>,
300 stderr: String,
302 },
303
304 #[error("cannot run {tool}")]
306 ToolStart {
307 tool: String,
309 #[source]
311 source: std::io::Error,
312 },
313
314 #[error(transparent)]
316 Exit(#[from] Exit),
317
318 #[error("{0}")]
320 Usage(String),
321
322 #[error("{0}")]
324 Config(String),
325
326 #[error("{0}")]
328 Data(String),
329
330 #[error("{0}")]
332 Stage(String),
333
334 #[error("{0}")]
336 Storage(String),
337
338 #[error("{0}")]
340 Fetch(String),
341
342 #[error("a worker panicked")]
344 WorkerPanicked,
345
346 #[error(transparent)]
348 Geolith(#[from] GeolithError),
349
350 #[error("parquet error")]
352 Parquet(#[from] parquet::errors::ParquetError),
353
354 #[error("arrow error")]
356 Arrow(#[from] arrow::error::ArrowError),
357
358 #[error("tiff error")]
360 Tiff(#[from] tiff::TiffError),
361}
362
363fn exit_text(code: Option<i32>) -> String {
364 code.map_or_else(String::new, |code| format!(" (exit {code})"))
365}
366
367impl From<ureq::Error> for DatasetError {
368 fn from(source: ureq::Error) -> Self {
369 Self::Request(Box::new(source))
370 }
371}
372
373pub type Result<T, E = DatasetError> = std::result::Result<T, E>;
375
376impl DatasetError {
377 #[must_use]
379 pub fn usage(message: impl Into<String>) -> Self {
380 Self::Usage(message.into())
381 }
382
383 #[must_use]
385 pub fn config(message: impl Into<String>) -> Self {
386 Self::Config(message.into())
387 }
388
389 #[must_use]
391 pub fn data(message: impl Into<String>) -> Self {
392 Self::Data(message.into())
393 }
394
395 #[must_use]
397 pub fn stage(message: impl Into<String>) -> Self {
398 Self::Stage(message.into())
399 }
400
401 #[must_use]
403 pub fn storage(message: impl Into<String>) -> Self {
404 Self::Storage(message.into())
405 }
406
407 #[must_use]
409 pub fn fetch(message: impl Into<String>) -> Self {
410 Self::Fetch(message.into())
411 }
412
413 #[must_use]
415 pub const fn exit(&self) -> Option<Exit> {
416 match self {
417 Self::Exit(exit) => Some(*exit),
418 _ => None,
419 }
420 }
421
422 #[must_use]
425 pub const fn exit_code(&self) -> i32 {
426 match self {
427 Self::Exit(exit) => exit.0,
428 _ => 1,
429 }
430 }
431}
432
433pub trait AtPath {
435 fn at_path(self, op: IoOp, path: &Path) -> DatasetError;
437}
438
439macro_rules! at_path {
440 ($($source:ty => $variant:ident),+ $(,)?) => {$(
441 impl AtPath for $source {
442 fn at_path(self, op: IoOp, path: &Path) -> DatasetError {
443 DatasetError::$variant { op, path: path.to_path_buf(), source: self }
444 }
445 }
446 )+};
447}
448
449at_path! {
450 std::io::Error => Io,
451 GeolithError => Reader,
452 parquet::errors::ParquetError => ParquetFile,
453 tiff::TiffError => TiffFile,
454 shapefile::Error => ShapeFile,
455 serde_json::Error => JsonFile,
456 shapefile::dbase::Error => DbfFile,
457}
458
459pub trait IoResultExt<T> {
461 fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T>;
467}
468
469impl<T, E: AtPath> IoResultExt<T> for std::result::Result<T, E> {
470 fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T> {
471 self.map_err(|source| source.at_path(op, path.as_ref()))
472 }
473}
474
475pub trait JsonResultExt<T> {
477 fn json_at(self, path: impl AsRef<Path>) -> Result<T>;
483
484 fn json_of(self, what: impl Into<String>) -> Result<T>;
490}
491
492impl<T> JsonResultExt<T> for serde_json::Result<T> {
493 fn json_at(self, path: impl AsRef<Path>) -> Result<T> {
494 self.map_err(|source| DatasetError::Json {
495 path: path.as_ref().to_path_buf(),
496 source,
497 })
498 }
499
500 fn json_of(self, what: impl Into<String>) -> Result<T> {
501 self.map_err(|source| DatasetError::JsonValue {
502 what: what.into(),
503 source,
504 })
505 }
506}
507
508pub trait NumberError: std::error::Error + Send + Sync + 'static {}
510
511impl NumberError for std::num::ParseIntError {}
512impl NumberError for std::num::ParseFloatError {}
513impl NumberError for std::num::TryFromIntError {}
514
515pub trait NumberResultExt<T> {
517 fn number_of(self, what: impl Into<String>) -> Result<T>;
523}
524
525impl<T, E: NumberError> NumberResultExt<T> for std::result::Result<T, E> {
526 fn number_of(self, what: impl Into<String>) -> Result<T> {
527 self.map_err(|source| DatasetError::Number {
528 what: what.into(),
529 source: Box::new(source),
530 })
531 }
532}
533
534pub trait WithinExt<T> {
536 fn within(self, what: impl Into<String>) -> Result<T>;
542}
543
544impl<T, E: Into<DatasetError>> WithinExt<T> for std::result::Result<T, E> {
545 fn within(self, what: impl Into<String>) -> Result<T> {
546 self.map_err(|source| DatasetError::Within {
547 what: what.into(),
548 source: Box::new(source.into()),
549 })
550 }
551}
552
553pub trait IoStepExt<T> {
555 fn io_step(self, what: impl Into<String>) -> Result<T>;
561}
562
563impl<T> IoStepExt<T> for std::io::Result<T> {
564 fn io_step(self, what: impl Into<String>) -> Result<T> {
565 self.map_err(|source| DatasetError::IoStep {
566 what: what.into(),
567 source,
568 })
569 }
570}
571
572#[cfg(test)]
573mod tests {
574 use super::*;
575
576 #[test]
577 fn an_io_error_names_the_operation_and_the_file() {
578 let err = std::fs::read_to_string("/nonexistent/geolith/areas.geojson")
579 .io_at(IoOp::Read, "/nonexistent/geolith/areas.geojson")
580 .expect_err("the file does not exist");
581 assert_eq!(
582 err.to_string(),
583 "reading /nonexistent/geolith/areas.geojson"
584 );
585 let line = geolith::error::report(&err);
586 assert!(
587 line.starts_with("reading /nonexistent/geolith/areas.geojson: "),
588 "{line}"
589 );
590 }
591
592 #[test]
593 fn an_exit_error_gives_its_code() {
594 assert_eq!(DatasetError::Exit(Exit(3)).exit_code(), 3);
595 assert_eq!(DatasetError::usage("--x").exit_code(), 1);
596 }
597
598 #[test]
599 fn a_tool_error_prints_the_exit_code_when_there_is_one() {
600 let err = DatasetError::Tool {
601 tool: "unzip".to_owned(),
602 command: "a.zip".to_owned(),
603 code: Some(9),
604 stderr: "bad zip".to_owned(),
605 };
606 assert_eq!(err.to_string(), "unzip a.zip failed (exit 9): bad zip");
607 }
608}