Skip to main content

deepdoc_core/
error.rs

1//! Core error type. The CLI maps these onto the exit codes from the spec.
2
3use std::path::{Path, PathBuf};
4
5use crate::detect::Format;
6
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// Process exit codes (see `docs/PRD/02-cli-spec.md`).
10pub mod exit_code {
11    /// Success.
12    pub const OK: i32 = 0;
13    /// Generic failure.
14    pub const FAILURE: i32 = 1;
15    /// Invalid arguments (also what clap returns on its own).
16    pub const USAGE: i32 = 2;
17    /// Recognised document, but no extractable text — looks like a scan, needs OCR first.
18    pub const NO_TEXT: i32 = 4;
19    /// Unsupported file type.
20    pub const UNSUPPORTED: i32 = 5;
21}
22
23#[derive(Debug, thiserror::Error)]
24pub enum Error {
25    #[error("cannot read {path}: {source}")]
26    Io {
27        path: PathBuf,
28        #[source]
29        source: std::io::Error,
30    },
31
32    #[error("unsupported file type: {path}")]
33    Unsupported { path: PathBuf },
34
35    /// The type is known but its extractor has not landed yet (pre-v0.1 only).
36    #[error("{format} is not supported yet")]
37    NotImplemented { format: Format },
38
39    /// The message names the tool that fixes it: OCR deliberately lives outside
40    /// this deterministic path (see `deepocr`), so pointing at a sibling binary
41    /// is more honest than pointing at a flag DeepDoc does not have.
42    #[error(
43        "{path} has no extractable text — it looks like a scan. Make it searchable with \
44         deepocr first, then extract the result (https://github.com/deeplabua/deepocr)"
45    )]
46    NoText { path: PathBuf },
47
48    #[error("cannot parse {path}: {message}")]
49    Parse { path: PathBuf, message: String },
50
51    #[error("invalid page range {input:?}: {message}")]
52    InvalidPageRange { input: String, message: String },
53}
54
55impl Error {
56    /// Read error carrying the path that failed.
57    pub fn io(path: impl AsRef<Path>, source: std::io::Error) -> Self {
58        Error::Io {
59            path: path.as_ref().to_path_buf(),
60            source,
61        }
62    }
63
64    pub fn parse(path: impl AsRef<Path>, message: impl Into<String>) -> Self {
65        Error::Parse {
66            path: path.as_ref().to_path_buf(),
67            message: message.into(),
68        }
69    }
70
71    /// The exit code this error should produce.
72    pub fn exit_code(&self) -> i32 {
73        match self {
74            Error::Unsupported { .. } | Error::NotImplemented { .. } => exit_code::UNSUPPORTED,
75            Error::NoText { .. } => exit_code::NO_TEXT,
76            Error::InvalidPageRange { .. } => exit_code::USAGE,
77            Error::Io { .. } | Error::Parse { .. } => exit_code::FAILURE,
78        }
79    }
80}