use std::ffi::OsString;
use anstream::ColorChoice;
use anstyle::{AnsiColor, Effects, Style};
use clap::ValueEnum;
use clap::builder::Styles;
const HEADER: Style = AnsiColor::Green.on_default().effects(Effects::BOLD);
const LITERAL: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
const PLACEHOLDER: Style = AnsiColor::Cyan.on_default();
const ERROR: Style = AnsiColor::Red.on_default().effects(Effects::BOLD);
const NOTE: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
const INVALID: Style = AnsiColor::Yellow.on_default().effects(Effects::BOLD);
pub const STATUS: Style = HEADER;
pub fn clap_styles() -> Styles {
Styles::styled()
.header(HEADER)
.usage(HEADER)
.literal(LITERAL)
.placeholder(PLACEHOLDER)
.error(ERROR)
.valid(LITERAL)
.invalid(INVALID)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum ColorWhen {
Auto,
Always,
Never,
}
impl From<ColorWhen> for ColorChoice {
fn from(when: ColorWhen) -> Self {
match when {
ColorWhen::Auto => ColorChoice::Auto,
ColorWhen::Always => ColorChoice::Always,
ColorWhen::Never => ColorChoice::Never,
}
}
}
pub fn init(flag: Option<ColorWhen>) {
ColorChoice::from(flag.unwrap_or(ColorWhen::Auto)).write_global();
}
pub fn effective() -> ColorChoice {
anstream::AutoStream::choice(&std::io::stderr())
}
pub fn peek(args: &[OsString]) -> Option<ColorWhen> {
let mut args = args.iter().map(|arg| arg.to_str());
while let Some(arg) = args.next() {
let Some(arg) = arg else { continue };
if arg == "--" {
return None;
}
let when = match arg.strip_prefix("--color") {
Some("") => args.next().flatten(),
Some(rest) => match rest.strip_prefix('=') {
Some(value) => Some(value),
None => continue,
},
None => continue,
};
return when.and_then(|when| ColorWhen::from_str(when, true).ok());
}
None
}
pub fn report(err: &anyhow::Error) {
let mut causes = err.chain();
let Some(head) = causes.next() else { return };
anstream::eprint!("{ERROR}error{ERROR:#}: ");
print_message(&head.to_string(), "");
let mut causes = causes.peekable();
if causes.peek().is_some() {
anstream::eprintln!("\nCaused by:");
for cause in causes {
anstream::eprint!(" ");
print_message(&cause.to_string(), " ");
}
}
}
fn print_message(message: &str, indent: &str) {
for (line_no, line) in message.lines().enumerate() {
let indent = match line_no {
0 => "",
_ => indent,
};
match line.strip_prefix("help:") {
Some(rest) => anstream::eprintln!("{indent}{NOTE}help{NOTE:#}:{rest}"),
None => anstream::eprintln!("{indent}{line}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn peeked(args: &[&str]) -> Option<ColorWhen> {
let args: Vec<OsString> = args.iter().map(OsString::from).collect();
peek(&args)
}
#[test]
fn an_attached_value_is_found() {
assert_eq!(
peeked(&["bloat-show", "--color=always"]),
Some(ColorWhen::Always)
);
}
#[test]
fn a_separate_value_is_found() {
assert_eq!(
peeked(&["bloat-show", "bloat.json", "--color", "never"]),
Some(ColorWhen::Never)
);
}
#[test]
fn no_flag_means_no_answer() {
assert_eq!(peeked(&["bloat-show", "bloat.json"]), None);
}
#[test]
fn an_unknown_value_is_left_for_clap() {
assert_eq!(peeked(&["bloat-show", "--color=purple"]), None);
assert_eq!(peeked(&["bloat-show", "--color"]), None);
}
#[test]
fn a_lookalike_flag_is_not_mistaken_for_it() {
assert_eq!(peeked(&["bloat-show", "--colorize", "always"]), None);
}
}