mod json_formatter;
mod table_formatter;
mod yaml_formatter;
pub use json_formatter::JsonFormatter;
use serde::Serialize;
pub use table_formatter::TableFormatter;
pub use yaml_formatter::YamlFormatter;
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputFormat {
#[default]
Table,
Json,
Yaml,
}
impl From<&str> for OutputFormat {
fn from(s: &str) -> Self {
match s.to_lowercase().as_str() {
"json" => Self::Json,
"yaml" | "yml" => Self::Yaml,
_ => Self::Table,
}
}
}
pub trait Formatter {
fn format<T: Serialize>(&self, data: &T) -> String;
}
pub enum FormatterType {
Json(JsonFormatter),
Table(TableFormatter),
Yaml(YamlFormatter),
}
impl FormatterType {
pub fn format<T: Serialize>(&self, data: &T) -> String {
match self {
Self::Json(f) => f.format(data),
Self::Table(f) => f.format(data),
Self::Yaml(f) => f.format(data),
}
}
}
impl From<OutputFormat> for FormatterType {
fn from(format: OutputFormat) -> Self {
match format {
OutputFormat::Json => Self::Json(JsonFormatter),
OutputFormat::Table => Self::Table(TableFormatter),
OutputFormat::Yaml => Self::Yaml(YamlFormatter),
}
}
}
pub fn get_formatter(format: OutputFormat) -> FormatterType {
FormatterType::from(format)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn output_format_parses_json_case_insensitively() {
assert!(matches!(OutputFormat::from("json"), OutputFormat::Json));
assert!(matches!(OutputFormat::from("JSON"), OutputFormat::Json));
}
#[test]
fn output_format_parses_yaml_aliases_case_insensitively() {
assert!(matches!(OutputFormat::from("yaml"), OutputFormat::Yaml));
assert!(matches!(OutputFormat::from("YAML"), OutputFormat::Yaml));
assert!(matches!(OutputFormat::from("yml"), OutputFormat::Yaml));
assert!(matches!(OutputFormat::from("YML"), OutputFormat::Yaml));
}
#[test]
fn output_format_parses_table() {
assert!(matches!(OutputFormat::from("table"), OutputFormat::Table));
}
#[test]
fn output_format_defaults_to_table_for_unrecognized_input() {
assert!(matches!(OutputFormat::from("bogus"), OutputFormat::Table));
assert!(matches!(OutputFormat::from(""), OutputFormat::Table));
}
#[test]
fn output_format_default_is_table() {
assert!(matches!(OutputFormat::default(), OutputFormat::Table));
}
}