bloat-show-cli 0.1.0

The `bloat-show` command line tool: render `cargo bloat` JSON output as an interactive HTML treemap
//! Terminal colour, in Cargo's palette and with Cargo's precedence.
//!
//! One decision drives everything we emit: our own status lines, clap's help and
//! errors, and the OSC 8 links. It is written to [`anstream`]'s global choice
//! before anything prints, and the `anstream::eprintln!` macros strip the escapes
//! back out when colour is off.

use std::ffi::OsString;

use anstream::ColorChoice;
use anstyle::{AnsiColor, Effects, Style};
use clap::ValueEnum;
use clap::builder::Styles;

// Cargo's palette, so a report reads as part of the build that produced it.
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);

/// The style for the verb that opens a status line, as in Cargo's `Compiling`.
pub const STATUS: Style = HEADER;

/// Cargo's `--help` colours, in place of clap's own.
pub fn clap_styles() -> Styles {
    Styles::styled()
        .header(HEADER)
        .usage(HEADER)
        .literal(LITERAL)
        .placeholder(PLACEHOLDER)
        .error(ERROR)
        .valid(LITERAL)
        .invalid(INVALID)
}

/// The `--color` values Cargo accepts.
#[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,
        }
    }
}

/// Publishes the colour choice, before argv is parsed and before anything prints.
///
/// `Auto` is left for [`anstream`] to settle per stream, which is where `NO_COLOR`,
/// `CLICOLOR_FORCE`, `TERM` and the tty check live.
pub fn init(flag: Option<ColorWhen>) {
    ColorChoice::from(flag.unwrap_or(ColorWhen::Auto)).write_global();
}

/// The choice as it applies to stderr, with `Auto` already settled.
pub fn effective() -> ColorChoice {
    anstream::AutoStream::choice(&std::io::stderr())
}

/// Reads `--color` out of raw argv, since clap needs the answer before it parses.
///
/// An unknown value is left for clap to reject, so the error text stays clap's.
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 };
        // Past `--` nothing is a flag of ours any more.
        if arg == "--" {
            return None;
        }
        let when = match arg.strip_prefix("--color") {
            Some("") => args.next().flatten(),
            // `--colorize` and friends are somebody else's flag.
            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
}

/// Prints an error the way Cargo does: `error:` first, then the causes, with any
/// `help:` line the message carries picked out.
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(), "  ");
        }
    }
}

/// Writes a message block at `indent`, styling any `help:` line it carries. The
/// first line lands after whatever prefix is already on the line, so it is written
/// without the indent.
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);
    }
}