summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: be0ebb793806fa5f674db6e6e9fccbe158f610a0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::io::{ErrorKind as IoErrorKind, Error as IoError};
use crate::*;

#[derive(Debug, PartialEq)]
pub enum EntryErrorKind {
    NotFound,
    PermissionDenied,
}

pub struct EntryReadError {
    pub path: PathBuf,
    pub error_kind: EntryErrorKind,
}

pub struct EntryWriteError {
    pub path: PathBuf,
    pub error_kind: EntryErrorKind,
}

impl From<EntryReadError> for EntryWriteError {
    fn from(error: EntryReadError) -> Self {
        EntryWriteError { path: error.path, error_kind: error.error_kind }
    }
}

pub(crate) fn io_result_to_read_result<T>(io_result: Result<T, IoError>, path: &Path) -> ReadResult<T> {
    match io_result {
        Ok(t) => Ok(t),
        Err(io_error) => {
            match io_error_to_entry_error(io_error) {
                Ok(error_kind) => Err( EntryReadError { path: path.to_path_buf(), error_kind }),
                Err(err) => panic!("Unexpected IO error while attempting to read from {path:?}: {err:?}"),
            }
        }
    }
}
pub(crate) fn io_result_to_write_result<T>(io_result: Result<T, IoError>, path: &Path) -> WriteResult<T> {
    match io_result {
        Ok(t) => Ok(t),
        Err(io_error) => {
            match io_error_to_entry_error(io_error) {
                Ok(error_kind) => Err( EntryWriteError { path: path.to_path_buf(), error_kind }),
                Err(err) => panic!("Unexpected IO error while attempting to write to {path:?}: {err:?}"),
            }
        }
    }
}
fn io_error_to_entry_error(io_error: IoError) -> Result<EntryErrorKind, IoErrorKind> {
    match io_error.kind() {
        IoErrorKind::NotFound => Ok(EntryErrorKind::NotFound),
        // An intermediate path component was a plain file, not a directory
        IoErrorKind::NotADirectory => Ok(EntryErrorKind::NotFound),
        // A cyclic symbolic link chain was included in the provided path
        IoErrorKind::FilesystemLoop => Ok(EntryErrorKind::NotFound),
        IoErrorKind::PermissionDenied => Ok(EntryErrorKind::PermissionDenied),
        err => Err(err),
    }
}

impl std::fmt::Debug for EntryReadError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "Error while attempting to read from file '{:?}': {:?}", self.path, self.error_kind)
    }
}
impl std::fmt::Debug for EntryWriteError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "Error while attempting to write to file '{:?}': {:?}", self.path, self.error_kind)
    }
}