Skip to main content

ctl_core/
format.rs

1use std::fmt;
2use std::str::FromStr;
3
4/// Hosts `JsonSchema`. schemars expands `concat!`; this module is the allow.
5mod data {
6    #![allow(clippy::disallowed_macros)]
7
8    /// Output representation. Models serialize first; views pick one of these.
9    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
10    #[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
11    #[cfg_attr(feature = "json", derive(serde::Deserialize, serde::Serialize))]
12    #[cfg_attr(feature = "json", serde(rename_all = "lowercase"))]
13    #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
14    pub enum OutputFormat {
15        #[default]
16        /// Human text, optionally colored.
17        Pretty,
18        /// Machine JSON. Never contains ANSI.
19        Json,
20    }
21}
22
23pub use data::OutputFormat;
24
25impl OutputFormat {
26    #[must_use]
27    /// `true` when this view is JSON.
28    pub fn is_json(self) -> bool {
29        self == Self::Json
30    }
31}
32
33impl FromStr for OutputFormat {
34    type Err = ParseFormatError;
35
36    fn from_str(value: &str) -> Result<Self, Self::Err> {
37        match value {
38            "pretty" => Ok(Self::Pretty),
39            "json" => Ok(Self::Json),
40            _ => Err(ParseFormatError),
41        }
42    }
43}
44
45impl fmt::Display for OutputFormat {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.write_str(match self {
48            Self::Pretty => "pretty",
49            Self::Json => "json",
50        })
51    }
52}
53
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55/// Unknown format token.
56pub struct ParseFormatError;
57
58impl fmt::Display for ParseFormatError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str("expected pretty or json")
61    }
62}
63
64impl std::error::Error for ParseFormatError {}
65
66#[cfg(test)]
67mod tests {
68    use super::OutputFormat;
69
70    #[test]
71    fn json_predicate() {
72        assert!(OutputFormat::Json.is_json());
73        assert!(!OutputFormat::Pretty.is_json());
74        assert_eq!("json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
75    }
76}