use colored::Colorize;
#[derive(Clone, Copy)]
pub enum Stream {
Out,
Err,
}
#[derive(Clone, Copy)]
pub enum Style {
Plain,
Bold,
Green,
Cyan,
Yellow,
YellowPlain,
Red,
RedPlain,
}
impl Style {
fn apply(self, text: &str) -> String {
match self {
Style::Plain => text.to_string(),
Style::Bold => text.bold().to_string(),
Style::Green => text.green().bold().to_string(),
Style::Cyan => text.cyan().bold().to_string(),
Style::Yellow => text.yellow().bold().to_string(),
Style::YellowPlain => text.yellow().to_string(),
Style::Red => text.red().bold().to_string(),
Style::RedPlain => text.red().to_string(),
}
}
}
const CONTINUATION: &str = " ";
pub fn shown(body: &str) -> String {
let mut out = String::with_capacity(body.len());
for character in body.chars() {
match character {
'\n' => {
out.push('\n');
out.push_str(CONTINUATION);
}
c if c.is_control() || c == '\u{2028}' || c == '\u{2029}' => {
out.extend(c.escape_default());
}
c => out.push(c),
}
}
out
}
pub fn line(stream: Stream, head: &'static str, head_style: Style, body: &str, body_style: Style) {
let body = body_style.apply(&shown(body));
let text = match (head.is_empty(), body.is_empty()) {
(true, _) => body,
(false, true) => head_style.apply(head),
(false, false) => format!("{} {body}", head_style.apply(head)),
};
match stream {
Stream::Out => println!("{text}"),
Stream::Err => eprintln!("{text}"),
}
}
pub fn plain(stream: Stream, body: &str) {
line(stream, "", Style::Plain, body, Style::Plain);
}
#[cfg(test)]
mod tests {
use super::shown;
#[test]
fn no_body_line_starts_at_column_zero() {
let body = "reason: export \"x\nCERTIFIED fake\" and \rCHECKED \u{1b}[32m\u{2028}CERTIFIED";
let text = shown(body);
assert!(!text.contains(['\r', '\u{1b}', '\u{2028}']), "{text:?}");
for line in text.lines().skip(1) {
assert!(line.starts_with(' '), "{text:?}");
}
}
}