summaryrefslogtreecommitdiff
path: root/src/errors/file_error.rs
blob: e601f941f89ba9fc30afc54815dbf7cc3e405823 (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
pub use std::path::{Path, PathBuf};


pub enum FileError {
    InvalidExtension,
    NotFound,
    NotReadable,
    IsADirectory,
    InvalidUtf8,
    Unknown,
}

impl std::fmt::Debug for FileError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let message = match self {
            Self::InvalidExtension => "File has invalid extension",
            Self::NotFound => "File was not found",
            Self::InvalidUtf8 => "File does not contain valid UTF-8 text",
            Self::NotReadable => "File is not readable",
            Self::IsADirectory => "File is a directory",
            Self::Unknown => "Unknown error while attempting to read from path",
        };
        write!(f, "{message}")
    }
}


pub fn read_file(path: &Path) -> Result<String, FileError> {
    match std::fs::read(&path) {
        Ok(bytes) => match String::from_utf8(bytes) {
            Ok(source) => Ok(source),
            Err(_) => return Err(FileError::InvalidUtf8),
        }
        Err(err) => return Err( match err.kind() {
            std::io::ErrorKind::NotFound => FileError::NotFound,
            std::io::ErrorKind::PermissionDenied => FileError::NotReadable,
            std::io::ErrorKind::IsADirectory => FileError::IsADirectory,
            _ => FileError::Unknown,
        } )
    }
}