Skip to main content

rvaultlib/typedetect/
mod.rs

1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub enum FileFormat {
3    Json,
4    Yaml,
5}
6
7/// Detect the format of a file.
8/// Tries the file extension first (fast path), then falls back to content-based detection.
9pub fn detect_format(file: &str) -> Result<FileFormat, Box<dyn std::error::Error>> {
10    match std::path::Path::new(file)
11        .extension()
12        .and_then(|e| e.to_str())
13    {
14        Some("json") => return Ok(FileFormat::Json),
15        Some("yaml") | Some("yml") => return Ok(FileFormat::Yaml),
16        _ => {}
17    }
18
19    let content = std::fs::read_to_string(file)?;
20    if serde_json::from_str::<serde_json::Value>(&content).is_ok() {
21        return Ok(FileFormat::Json);
22    }
23    if serde_yaml::from_str::<serde_yaml::Value>(&content).is_ok() {
24        return Ok(FileFormat::Yaml);
25    }
26
27    Err(format!("Cannot detect format of file '{}': not valid JSON or YAML", file).into())
28}