use std::io::{self, BufRead as _, IsTerminal as _, Write as _};
use crate::error::CliError;
use crate::redact::redact;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum OutputFormat {
#[default]
Human,
Json,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Output {
format: OutputFormat,
}
impl Output {
pub fn new(format: OutputFormat) -> Self {
Self { format }
}
pub fn format(&self) -> OutputFormat {
self.format
}
pub(crate) fn is_json(self) -> bool {
self.format == OutputFormat::Json
}
pub(crate) fn line(self, text: &str) -> Result<(), CliError> {
if self.is_json() {
return Ok(());
}
write_line(&mut io::stdout().lock(), text)
}
#[expect(
clippy::unused_self,
reason = "kept on Output so every terminal write goes through the one writer"
)]
pub(crate) fn value_line(self, text: &str) -> Result<(), CliError> {
write_line(&mut io::stdout().lock(), text)
}
pub(crate) fn json(self, value: &serde_json::Value) -> Result<(), CliError> {
if !self.is_json() {
return Ok(());
}
let text = serde_json::to_string_pretty(value)
.map_err(|err| CliError::Local(format!("encoding output failed: {err}")))?;
write_line(&mut io::stdout().lock(), &text)
}
#[expect(
clippy::unused_self,
reason = "kept on Output so every terminal write goes through the one writer"
)]
pub(crate) fn note(self, text: &str) -> Result<(), CliError> {
write_line(&mut io::stderr().lock(), text)
}
#[expect(
clippy::unused_self,
reason = "kept on Output so every terminal write goes through the one writer"
)]
pub(crate) fn confirm(self, question: &str) -> Result<Option<bool>, CliError> {
let stdin = io::stdin();
if !stdin.is_terminal() {
return Ok(None);
}
{
let mut err = io::stderr().lock();
write!(err, "{} [y/N] ", redact(question))
.and_then(|()| err.flush())
.map_err(|err| write_error(&err))?;
}
let mut answer = String::new();
stdin
.lock()
.read_line(&mut answer)
.map_err(|err| CliError::Local(format!("reading the answer failed: {err}")))?;
Ok(Some(matches!(
answer.trim(),
"y" | "Y" | "yes" | "YES" | "Yes"
)))
}
pub fn error(&self, error: &CliError) {
let message = chain(error);
let mut err = io::stderr().lock();
if self.is_json() {
let value = serde_json::json!({
"error": {
"code": error.code(),
"message": message,
"details": error.details(),
"hint": error.hint(),
},
"exit_code": error.exit_code(),
});
let _written = writeln!(err, "{}", redact(&value.to_string()));
} else {
let _written = writeln!(err, "{}", redact(&format!("error: {message}")));
for detail in error.details() {
let _detail = writeln!(err, "{}", redact(&format!(" {detail}")));
}
if let Some(hint) = error.hint() {
let _hint = writeln!(err, "hint: {hint}");
}
}
let _flushed = err.flush();
}
}
fn chain(error: &CliError) -> String {
let mut message = error.to_string();
let mut source = std::error::Error::source(error);
while let Some(cause) = source {
message.push_str(": ");
message.push_str(&cause.to_string());
source = cause.source();
}
message
}
fn write_line(out: &mut impl io::Write, text: &str) -> Result<(), CliError> {
writeln!(out, "{}", redact(text))
.and_then(|()| out.flush())
.map_err(|err| write_error(&err))
}
fn write_error(err: &io::Error) -> CliError {
CliError::Local(format!("writing output failed: {err}"))
}
pub(crate) fn sanitize(text: &str) -> String {
let mut clean = String::with_capacity(text.len());
for c in text.chars() {
if c.is_control() && c != '\n' && c != '\t' {
clean.extend(c.escape_default());
} else {
clean.push(c);
}
}
clean
}