use std::io::IsTerminal as _;
pub(crate) fn report(err: &anyhow::Error) {
let colored = std::io::stderr().is_terminal()
&& std::env::var_os("NO_COLOR").is_none_or(|v| v.is_empty());
let mut out = String::new();
push_block(&mut out, &format!("Error: {err}"), "", colored);
let mut causes = err.chain().skip(1).peekable();
if causes.peek().is_some() {
out.push('\n');
if colored {
out.push_str(&nitr::diag::paint_line("Caused by:"));
} else {
out.push_str("Caused by:");
}
out.push('\n');
for cause in causes {
push_block(&mut out, &cause.to_string(), " ", colored);
}
}
eprint!("{out}");
}
fn push_block(out: &mut String, text: &str, indent: &str, colored: bool) {
for line in text.lines() {
out.push_str(indent);
if colored {
out.push_str(&nitr::diag::paint_line(line));
} else {
out.push_str(line);
}
out.push('\n');
}
}
pub(crate) struct PaintedFormat<F>(pub(crate) F);
impl<S, N, F> tracing_subscriber::fmt::FormatEvent<S, N> for PaintedFormat<F>
where
S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
N: for<'a> tracing_subscriber::fmt::FormatFields<'a> + 'static,
F: tracing_subscriber::fmt::FormatEvent<S, N>,
{
fn format_event(
&self,
ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
mut writer: tracing_subscriber::fmt::format::Writer<'_>,
event: &tracing::Event<'_>,
) -> std::fmt::Result {
let mut buf = String::new();
self.0.format_event(
ctx,
tracing_subscriber::fmt::format::Writer::new(&mut buf),
event,
)?;
if !buf.trim_end_matches('\n').contains('\n') {
return writer.write_str(&buf);
}
let mut lines = buf.lines().peekable();
while let Some(line) = lines.next() {
writer.write_str(&nitr::diag::paint_line(line))?;
if lines.peek().is_some() {
writer.write_char('\n')?;
}
}
if buf.ends_with('\n') {
writer.write_char('\n')?;
}
Ok(())
}
}