rust_config_tree/config_format.rs
1//! Format inference for config files and generated templates.
2
3use std::{ffi::OsStr, path::Path};
4
5/// File format used when loading config files or rendering templates.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum ConfigFormat {
8 /// YAML format, selected for `.yaml`, `.yml`, unknown extensions, and paths
9 /// without an extension.
10 Yaml,
11 /// TOML format, selected for `.toml`.
12 Toml,
13 /// JSON5-compatible format, selected for `.json` and `.json5`.
14 Json,
15}
16
17/// Path-based format inference for config files and generated templates.
18impl ConfigFormat {
19 /// Infers the config format from a path extension.
20 ///
21 /// Unknown extensions intentionally fall back to YAML.
22 ///
23 /// # Arguments
24 ///
25 /// - `path`: Config or template path whose extension should be inspected.
26 ///
27 /// # Returns
28 ///
29 /// Returns the inferred [`ConfigFormat`].
30 ///
31 /// # Examples
32 ///
33 /// ```
34 /// use rust_config_tree::config::ConfigFormat;
35 ///
36 /// assert_eq!(ConfigFormat::from_path("config.toml"), ConfigFormat::Toml);
37 /// assert_eq!(ConfigFormat::from_path("config.json5"), ConfigFormat::Json);
38 /// assert_eq!(ConfigFormat::from_path("config.unknown"), ConfigFormat::Yaml);
39 /// ```
40 pub fn from_path(path: impl AsRef<Path>) -> Self {
41 match path.as_ref().extension().and_then(OsStr::to_str) {
42 Some("toml") => Self::Toml,
43 Some("json" | "json5") => Self::Json,
44 Some("yaml" | "yml") | Some(_) | None => Self::Yaml,
45 }
46 }
47}