1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use anyhow::{bail, Result};
use serde::Serialize;

#[derive(Debug)]
pub enum ConfigType {
    Json,
    Yaml,
    Toml,
    Hcl,
}

#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ParsedInput {
    Json(serde_json::Value),
    Yaml(serde_yaml::Value),
    Toml(toml::Value),
    Hcl(hcl::Body),
}

pub fn try_parse_all(input: &str) -> Result<ParsedInput> {
    if let Ok(parsed) = serde_json::from_str(input) {
        Ok(ParsedInput::Json(parsed))
    } else if let Ok(parsed) = serde_yaml::from_str(input) {
        Ok(ParsedInput::Yaml(parsed))
    } else if let Ok(parsed) = toml::from_str(input) {
        Ok(ParsedInput::Toml(parsed))
    } else if let Ok(parsed) = hcl::from_str(input) {
        Ok(ParsedInput::Hcl(parsed))
    } else {
        bail!(format!(
            "Failed to parse following input as valid json, yaml, or toml: {:?}",
            input
        ))
    }
}