chanoma/
file_extension.rs1use crate::error::Error;
4use std::path::Path;
5use std::str::FromStr;
6use strum_macros::EnumIter;
7
8#[derive(Debug, EnumIter, PartialEq, Eq)]
10pub enum FileExtension {
11 Csv,
12 Yaml,
13 }
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 _ => 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 }
35 }
36}
37
38impl FileExtension {
39 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}