1use anyhow::{anyhow, Context, Error, Result};
14use clap::ValueEnum;
15use core::str::FromStr;
16use serde::Serialize;
17
18#[derive(Clone, Copy, ValueEnum)]
19#[value(rename_all = "UPPERCASE")]
20pub enum Format {
21 Ron,
22 Json,
23 Yaml,
24}
25
26impl Format {
27 pub fn as_string<T: Serialize>(self, data: &T) -> Result<String> {
28 match self {
29 Format::Ron => ron::ser::to_string_pretty(
30 data,
31 ron::ser::PrettyConfig::new().separate_tuple_members(true),
32 )
33 .context("failed to serialize to RON format"),
34 Format::Json => {
35 serde_json::to_string_pretty(data).context("failed to serialize to JSON format")
36 }
37 Format::Yaml => serde_yaml::to_string(data).context("failed to serialize to YAML"),
38 }
39 }
40}
41
42impl FromStr for Format {
43 type Err = Error;
44
45 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
46 match s.to_uppercase().as_str() {
47 "RON" => Ok(Format::Ron),
48 "JSON" => Ok(Format::Json),
49 "YAML" => Ok(Format::Yaml),
50 _ => Err(anyhow!("unsupported output format '{}'", s)),
51 }
52 }
53}