use std::io::{self, Write};
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
#[allow(clippy::unwrap_used)]
pub fn log_error(header: impl AsRef<str>, body: impl AsRef<str>) {
let mut stream = StandardStream::stderr(ColorChoice::Always);
write_styled_message(
&mut stream,
format!("\n[Error: {}]", header.as_ref()),
ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true),
)
.unwrap();
write_styled_message(&mut stream, body, ColorSpec::new().set_fg(Some(Color::Red))).unwrap();
stream.flush().unwrap();
}
#[allow(clippy::unwrap_used)]
pub fn log_warning(header: impl AsRef<str>, body: impl AsRef<str>) {
let mut stream = StandardStream::stderr(ColorChoice::Always);
write_styled_message(
&mut stream,
format!("\n[Warning: {}]", header.as_ref()),
ColorSpec::new().set_fg(Some(Color::Yellow)).set_bold(true),
)
.unwrap();
write_styled_message(
&mut stream,
body,
ColorSpec::new().set_fg(Some(Color::Yellow)),
)
.unwrap();
stream.flush().unwrap();
}
#[allow(clippy::unwrap_used)]
pub fn log_header(title: impl AsRef<str>) {
let mut stream = StandardStream::stdout(ColorChoice::Always);
write_styled_message(
&mut stream,
format!("\n[{}]", title.as_ref()),
ColorSpec::new().set_fg(Some(Color::Magenta)).set_bold(true),
)
.unwrap();
stream.flush().unwrap();
}
#[allow(clippy::unwrap_used)]
pub fn log_info(message: impl AsRef<str>) {
println!("{}", message.as_ref());
std::io::stdout().flush().unwrap();
}
fn write_styled_message(
stream: &mut StandardStream,
message: impl AsRef<str>,
spec: &ColorSpec,
) -> io::Result<()> {
for line in message.as_ref().split('\n') {
stream.set_color(spec)?;
write!(stream, "{line}")?;
stream.reset()?;
writeln!(stream)?;
}
Ok(())
}