fb2_clean/config/
input.rs

1use crate::Result;
2use std::{fs, path::Path};
3
4/// Input directory OR file.
5#[derive(Clone, Debug, PartialEq)]
6pub enum Input {
7    Dir(Box<Path>),
8    File(InputFile),
9}
10
11/// Input file.
12#[derive(Clone, Debug, Hash, Eq, PartialEq)]
13pub struct InputFile {
14    pub ty: InputFileType,
15    pub path: Box<Path>,
16}
17
18/// Input file type.
19#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
20#[non_exhaustive]
21pub enum InputFileType {
22    Fb2,
23    Fb2Zip,
24}
25
26impl Input {
27    pub fn iter(&self) -> Box<dyn Iterator<Item = InputFile>> {
28        match self {
29            Self::Dir(d) => Box::new(
30                fs::read_dir(d)
31                    .ok()
32                    .into_iter()
33                    .flat_map(|rd| rd.filter_map(std::result::Result::ok))
34                    .filter_map(|entry| {
35                        let path = entry.path();
36                        get_input_file_type(&path).map(|ty| InputFile {
37                            ty,
38                            path: path.into(),
39                        })
40                    }),
41            ),
42            Self::File(f) => Box::new(Some(f.clone()).into_iter()),
43        }
44    }
45}
46
47impl Input {
48    pub(crate) fn new(path: impl AsRef<Path>) -> Result<Input> {
49        let path = fs::canonicalize(path)?.into_boxed_path();
50
51        if path.is_dir() {
52            Ok(Self::Dir(path))
53        } else if let Some(ty) = get_input_file_type(&path) {
54            Ok(Self::File(InputFile { ty, path }))
55        } else {
56            Err("File has unsupported extension".into())
57        }
58    }
59}
60
61impl InputFileType {
62    pub(crate) fn is_fb2(&self) -> bool {
63        matches!(self, Self::Fb2)
64    }
65
66    pub(crate) fn is_fb2_zip(&self) -> bool {
67        matches!(self, Self::Fb2Zip)
68    }
69}
70
71fn get_input_file_type(f: &Path) -> Option<InputFileType> {
72    let bytes = f.as_os_str().as_encoded_bytes();
73    let len = bytes.len();
74
75    for (ext, ty) in [
76        (".fb2", InputFileType::Fb2),
77        (".fb2.zip", InputFileType::Fb2Zip),
78    ] {
79        let ext = ext.as_bytes();
80        let l = ext.len();
81
82        if l > len {
83            break;
84        }
85        if bytes[len - l..len].eq_ignore_ascii_case(ext) {
86            return Some(ty);
87        }
88    }
89
90    None
91}