use anyhow::Result;
use serde::Serialize;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
Human,
Json,
Tsv,
}
impl OutputFormat {
pub fn auto() -> Self {
if atty_isatty() {
OutputFormat::Human
} else {
OutputFormat::Tsv
}
}
}
fn atty_isatty() -> bool {
use std::io::IsTerminal;
std::io::stdout().is_terminal()
}
pub fn write<T: Serialize + HumanDisplay>(value: &T, format: OutputFormat) -> Result<()> {
match format {
OutputFormat::Json => {
let json = serde_json::to_string_pretty(value)?;
println!("{}", json);
}
OutputFormat::Tsv => {
value.write_tsv(&mut std::io::stdout())?;
}
OutputFormat::Human => {
value.write_human(&mut std::io::stdout())?;
}
}
Ok(())
}
pub trait HumanDisplay {
fn write_human(&self, w: &mut dyn std::io::Write) -> Result<()>;
fn write_tsv(&self, w: &mut dyn std::io::Write) -> Result<()>;
}