1use std::fmt;
2use std::str::FromStr;
3
4mod data {
6 #![allow(clippy::disallowed_macros)]
7
8 #[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 Pretty,
18 Json,
20 }
21}
22
23pub use data::OutputFormat;
24
25impl OutputFormat {
26 #[must_use]
27 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)]
55pub 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}