use crate::cli::OutputFormat;
use crate::error::{Error, Result};
use serde::Serialize;
use std::fmt;
pub const SCHEMA_VERSION: u32 = 1;
#[derive(Serialize)]
struct SuccessEnvelope<'a, T> {
schema_version: u32,
ok: bool,
data: &'a T,
}
#[derive(Serialize)]
struct ErrorEnvelope<'a> {
schema_version: u32,
ok: bool,
error: ErrorBody<'a>,
}
#[derive(Serialize)]
struct ErrorBody<'a> {
code: &'static str,
message: &'a str,
}
#[derive(Debug)]
pub struct CliError {
format: OutputFormat,
source: Error,
}
impl CliError {
#[must_use]
pub const fn new(format: OutputFormat, source: Error) -> Self {
Self { format, source }
}
}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.format == OutputFormat::Json {
let message = self.source.to_string();
let envelope = ErrorEnvelope {
schema_version: SCHEMA_VERSION,
ok: false,
error: ErrorBody {
code: self.source.code(),
message: &message,
},
};
let rendered = serde_json::to_string(&envelope).map_err(|_| fmt::Error)?;
f.write_str(&rendered)
} else {
write!(f, "Error: {}", self.source)
}
}
}
impl std::error::Error for CliError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
pub fn print_success<T: Serialize>(data: &T) -> Result<()> {
let envelope = SuccessEnvelope {
schema_version: SCHEMA_VERSION,
ok: true,
data,
};
let rendered = serde_json::to_string_pretty(&envelope)
.map_err(|error| Error::JsonOutput(error.to_string()))?;
println!("{rendered}");
Ok(())
}
#[cfg(test)]
mod tests;