fn sgr(code: &str, text: &str, on: bool) -> String {
if on && !text.is_empty() {
format!("\x1b[{code}m{text}\x1b[0m")
} else {
text.to_string()
}
}
pub fn dim(text: &str, on: bool) -> String {
sgr("90", text, on)
}
pub fn white(text: &str, on: bool) -> String {
sgr("97", text, on)
}
pub fn accent(text: &str, on: bool) -> String {
sgr("36", text, on)
}
pub fn highlight(text: &str, on: bool) -> String {
sgr("96", text, on)
}
pub fn link(text: &str, on: bool) -> String {
sgr("4;36", text, on)
}
pub fn green(text: &str, on: bool) -> String {
sgr("92", text, on)
}
pub fn amber(text: &str, on: bool) -> String {
sgr("33", text, on)
}
pub fn red(text: &str, on: bool) -> String {
sgr("91", text, on)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tone {
Success,
Warn,
Fail,
}
impl Tone {
pub fn paint(self, text: &str, on: bool) -> String {
match self {
Self::Success => green(text, on),
Self::Warn => amber(text, on),
Self::Fail => red(text, on),
}
}
}
pub fn bold(text: &str, on: bool) -> String {
if on && !text.is_empty() {
format!("\x1b[1m{text}\x1b[22m")
} else {
text.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_palette_codes() {
assert_eq!(dim("x", true), "\x1b[90mx\x1b[0m");
assert_eq!(white("x", true), "\x1b[97mx\x1b[0m");
assert_eq!(accent("x", true), "\x1b[36mx\x1b[0m");
assert_eq!(highlight("x", true), "\x1b[96mx\x1b[0m");
assert_eq!(link("x", true), "\x1b[4;36mx\x1b[0m");
assert_eq!(green("x", true), "\x1b[92mx\x1b[0m");
assert_eq!(amber("x", true), "\x1b[33mx\x1b[0m");
assert_eq!(red("x", true), "\x1b[91mx\x1b[0m");
assert_eq!(
bold(&red("x", true), true),
"\x1b[1m\x1b[91mx\x1b[0m\x1b[22m"
);
assert_eq!(Tone::Success.paint("x", true), green("x", true));
assert_eq!(Tone::Warn.paint("x", true), amber("x", true));
assert_eq!(Tone::Fail.paint("x", true), red("x", true));
assert_eq!(dim("x", false), "x");
assert_eq!(dim("", true), "");
}
}