edres_core/
format.rs

1use std::path::Path;
2
3use crate::error::*;
4
5/// Represents an input markup format for a config file.
6///
7/// The variants that exist correspond to the features that have been enabled.
8/// For example, if the `json` feature is not enabled, then the
9/// `Format::Json` variant will not exist.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum Format {
12    #[cfg(feature = "json")]
13    Json,
14    #[cfg(feature = "toml")]
15    Toml,
16    #[cfg(feature = "yaml")]
17    Yaml,
18}
19
20impl Format {
21    /// Matches the extension of the given filename to identify
22    /// the format of the file.
23    ///
24    /// # Examples
25    /// ```
26    /// # use edres_core::Format;
27    /// assert_eq!(
28    ///     Format::from_filename("file.yml".as_ref()).unwrap(),
29    ///     Format::Yaml,
30    /// );
31    /// ```
32    pub fn from_filename(filename: &Path) -> Result<Self, Error> {
33        match filename.extension() {
34            Some(ext) => match ext.to_string_lossy().as_ref() {
35                #[cfg(feature = "json")]
36                "json" => Ok(Format::Json),
37
38                #[cfg(feature = "toml")]
39                "toml" => Ok(Format::Toml),
40
41                #[cfg(feature = "yaml")]
42                "yaml" | "yml" => Ok(Format::Yaml),
43
44                other => Err(Error::UnknownInputFormat(Some(other.into()))),
45            },
46            None => Err(Error::UnknownInputFormat(None)),
47        }
48    }
49}