jsonschema_annotator/
format.rs

1use std::path::Path;
2
3/// Format of the target file to annotate
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum TargetFormat {
6    Toml,
7    Yaml,
8}
9
10impl TargetFormat {
11    /// Detect format from file extension
12    pub fn from_path(path: &Path) -> Option<Self> {
13        let ext = path.extension()?.to_str()?;
14        Self::from_extension(ext)
15    }
16
17    /// Detect format from extension string
18    pub fn from_extension(ext: &str) -> Option<Self> {
19        match ext.to_lowercase().as_str() {
20            "toml" => Some(Self::Toml),
21            "yaml" | "yml" => Some(Self::Yaml),
22            _ => None,
23        }
24    }
25
26    /// Get the canonical file extension for this format
27    pub fn extension(&self) -> &'static str {
28        match self {
29            Self::Toml => "toml",
30            Self::Yaml => "yaml",
31        }
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_from_extension() {
41        assert_eq!(TargetFormat::from_extension("toml"), Some(TargetFormat::Toml));
42        assert_eq!(TargetFormat::from_extension("yaml"), Some(TargetFormat::Yaml));
43        assert_eq!(TargetFormat::from_extension("yml"), Some(TargetFormat::Yaml));
44        assert_eq!(TargetFormat::from_extension("TOML"), Some(TargetFormat::Toml));
45        assert_eq!(TargetFormat::from_extension("json"), None);
46    }
47
48    #[test]
49    fn test_from_path() {
50        assert_eq!(TargetFormat::from_path(Path::new("config.toml")), Some(TargetFormat::Toml));
51        assert_eq!(TargetFormat::from_path(Path::new("config.yaml")), Some(TargetFormat::Yaml));
52        assert_eq!(TargetFormat::from_path(Path::new("config.yml")), Some(TargetFormat::Yaml));
53        assert_eq!(TargetFormat::from_path(Path::new("config.json")), None);
54        assert_eq!(TargetFormat::from_path(Path::new("noext")), None);
55    }
56}