Skip to main content

to/
error.rs

1use std::fmt::{self, Display, Formatter};
2use std::io;
3use std::path::PathBuf;
4
5pub type Result<T> = std::result::Result<T, AppError>;
6
7#[derive(Debug)]
8pub enum AppError {
9    Io(io::Error),
10    InvalidArgs(String),
11    TodoNotFound(PathBuf),
12    AlreadyInitialized(PathBuf),
13    InvalidTaskIndex { index: usize, len: usize },
14    MalformedTodoLine { line: usize, content: String },
15    NotGitRepository(PathBuf),
16    GitCommandFailed(String),
17    EmptyTask,
18}
19
20impl Display for AppError {
21    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
22        match self {
23            Self::Io(err) => write!(f, "{err}"),
24            Self::InvalidArgs(message) => write!(f, "{message}"),
25            Self::TodoNotFound(path) => write!(
26                f,
27                "no `.todo` file found from {} upward; run `to init` in your project root",
28                path.display()
29            ),
30            Self::AlreadyInitialized(path) => {
31                write!(f, "a `.todo` file already exists at {}", path.display())
32            }
33            Self::InvalidTaskIndex { index, len } => {
34                write!(f, "task {index} is out of range; expected a number between 1 and {len}")
35            }
36            Self::MalformedTodoLine { line, content } => write!(
37                f,
38                "invalid `.todo` format on line {line}: expected `[ ] task` or `[x] task`, got `{content}`"
39            ),
40            Self::NotGitRepository(path) => write!(
41                f,
42                "{} is not inside a git repository; `to scan` only works on git-tracked files",
43                path.display()
44            ),
45            Self::GitCommandFailed(message) => write!(f, "{message}"),
46            Self::EmptyTask => write!(f, "task text cannot be empty"),
47        }
48    }
49}
50
51impl std::error::Error for AppError {}
52
53impl From<io::Error> for AppError {
54    fn from(value: io::Error) -> Self {
55        Self::Io(value)
56    }
57}