chanoma/
file_extension.rs

1//! 対応している設定ファイルの拡張子を扱うモジュールです。
2
3use crate::error::Error;
4use std::path::Path;
5use std::str::FromStr;
6use strum_macros::EnumIter;
7
8/// 対応済みの拡張子の列挙型です。
9#[derive(Debug, EnumIter, PartialEq, Eq)]
10pub enum FileExtension {
11    Csv,
12    Yaml,
13    //Json,
14}
15
16impl FromStr for FileExtension {
17    type Err = Error;
18    fn from_str(ext: &str) -> Result<Self, Self::Err> {
19        match ext {
20            ".csv" | "csv" => Ok(Self::Csv),
21            ".yaml" | "yaml" | ".yml" | "yml" => Ok(Self::Yaml),
22            //".json" | "json" => Ok(Self::Json),
23            _ => Err(Error::UnsupportedFileExtensionError(ext.to_string())),
24        }
25    }
26}
27
28impl ToString for FileExtension {
29    fn to_string(&self) -> String {
30        match self {
31            Self::Csv => "csv".to_string(),
32            Self::Yaml => "yaml".to_string(),
33            //Self::Json => "json".to_string(),
34        }
35    }
36}
37
38impl FileExtension {
39    /// ファイルパスから拡張子を特定します。
40    ///
41    /// ```
42    /// use chanoma::file_extension::FileExtension;
43    ///
44    /// let ext = FileExtension::from_path("/path/to/foo.csv").unwrap();
45    /// assert_eq!(ext, FileExtension::Csv);
46    /// ```
47    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
48        let path = path.as_ref();
49        let extension = match path.extension() {
50            Some(ext) => Ok(ext),
51            None => Err(Error::FileExtensionNotFoundInPath(path.to_path_buf())),
52        }?;
53        let ext_str = match extension.to_str() {
54            Some(s) => Ok(s),
55            None => Err(Error::FileExtensionCanNotConvertToStr(path.to_path_buf())),
56        }?;
57        Self::from_str(ext_str)
58    }
59}