use std::io::{self, IsTerminal};
use serde_json::Value;
pub trait OutputRenderer {
fn render(&self, value: &Value) -> String;
}
pub struct JsonRenderer;
impl OutputRenderer for JsonRenderer {
fn render(&self, value: &Value) -> String {
serde_json::to_string(value).expect("JSON values always serialise")
}
}
pub struct HumanRenderer;
impl OutputRenderer for HumanRenderer {
fn render(&self, value: &Value) -> String {
match value {
Value::String(s) => s.clone(),
_ => serde_json::to_string_pretty(value)
.unwrap_or_else(|_| "{\n \"error\": \"rendering failed\"\n}".to_owned()),
}
}
}
pub fn render_json(value: &Value) -> String {
JsonRenderer.render(value)
}
fn colour_suppressed(json: bool) -> bool {
json || std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty())
}
#[must_use]
pub fn colour_on_stderr(json: bool) -> bool {
!colour_suppressed(json) && io::stderr().is_terminal()
}
#[must_use]
pub fn colour_on_stdout(json: bool) -> bool {
!colour_suppressed(json) && io::stdout().is_terminal()
}