use clap::ArgMatches;
use serde::Serialize;
use crate::cmd::args::ARG_JSON;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
#[default]
Human,
Json
}
impl OutputFormat {
pub fn from_args(args: &ArgMatches) -> Self {
let json = args
.try_get_one::<bool>(ARG_JSON)
.ok()
.flatten()
.copied()
.unwrap_or(false);
if json {
Self::Json
} else {
Self::Human
}
}
}
pub fn print_json<T: Serialize>(value: &T) -> anyhow::Result<()> {
println!("{}", serde_json::to_string_pretty(value)?);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clap::{Arg, ArgAction, Command};
fn matches(argv: &[&str]) -> ArgMatches {
Command::new("test")
.arg(Arg::new(ARG_JSON).long("json").action(ArgAction::SetTrue))
.get_matches_from(argv)
}
#[test]
fn defaults_to_human_without_flag() {
assert_eq!(
OutputFormat::from_args(&matches(&["test"])),
OutputFormat::Human
);
}
#[test]
fn selects_json_with_flag() {
assert_eq!(
OutputFormat::from_args(&matches(&["test", "--json"])),
OutputFormat::Json
);
}
#[test]
fn defaults_to_human_when_flag_absent_from_matches() {
assert_eq!(
OutputFormat::from_args(&ArgMatches::default()),
OutputFormat::Human
);
}
}