bloat-show-cli 0.1.0

The `bloat-show` command line tool: render `cargo bloat` JSON output as an interactive HTML treemap
//! Input and output plumbing.

use std::path::{Path, PathBuf};

use anstream::ColorChoice;
use anstyle_hyperlink::Hyperlink;
use anyhow::{Context as _, Result};
use bloat_show::BloatJson;
use clap::Args;

use crate::style::{self, STATUS};

#[derive(Debug, Clone, Args)]
pub struct RenderArgs {
    /// Write the HTML report to this path
    #[arg(short = 'o', long, value_name = "PATH", default_value = "bloat.html")]
    pub output: PathBuf,

    /// Open the generated report in the default browser
    #[arg(long)]
    pub open: bool,
}

/// Writes `html` and opens it if requested.
pub fn deliver(args: &RenderArgs, html: &str, data: &BloatJson) -> Result<()> {
    let path = &args.output;
    write_file(path, html.as_bytes())?;

    // stderr keeps stdout free. Path last, so terminals linkify it without
    // swallowing trailing text, and so the closing escape lands at end of line.
    anstream::eprintln!(
        "{STATUS}{:>12}{STATUS:#} {} functions in {} crates, {} report",
        "Analyzed",
        data.functions.len(),
        data.crate_count(),
        human_size(html.len() as u64),
    );
    let printed = absolute(path);
    let link = hyperlink(&printed);
    anstream::eprintln!(
        "{STATUS}{:>12}{STATUS:#} {link}{}{link:#}",
        "Generated",
        printed.display()
    );

    if args.open {
        opener::open(path).with_context(|| format!("failed to open `{}`", path.display()))?;
    }
    Ok(())
}

fn write_file(path: &Path, contents: &[u8]) -> Result<()> {
    if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
        std::fs::create_dir_all(dir)
            .with_context(|| format!("failed to create `{}`", dir.display()))?;
    }
    std::fs::write(path, contents).with_context(|| format!("failed to write `{}`", path.display()))
}

/// Absolute, not canonical: keeps symlinks unresolved so the path reads as typed.
fn absolute(path: &Path) -> PathBuf {
    std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}

/// An OSC 8 link for `path`.
///
/// The default link renders as nothing in both `{}` and `{:#}` form, so the
/// plain path survives pipes, dumb terminals and `NO_COLOR` is untouched.
fn hyperlink(path: &Path) -> Hyperlink<String> {
    match hyperlinks_wanted(style::effective()) {
        true => Hyperlink::with_path(path),
        false => Hyperlink::default(),
    }
}

/// Mirrors Cargo, which ties hyperlinks to the colour choice: an explicit choice
/// decides, otherwise it takes a terminal known to render OSC 8.
fn hyperlinks_wanted(choice: ColorChoice) -> bool {
    match choice {
        ColorChoice::Never => false,
        ColorChoice::Always | ColorChoice::AlwaysAnsi => true,
        ColorChoice::Auto => supports_hyperlinks::on(supports_hyperlinks::Stream::Stderr),
    }
}

/// Reads from a path, or stdin given `-`. Returns the parsed data and the raw text.
pub fn read_input(path: &Path) -> Result<(BloatJson, String)> {
    let from_stdin = path == Path::new("-");
    let json = match from_stdin {
        true => std::io::read_to_string(std::io::stdin().lock()).context("failed to read stdin")?,
        false => std::fs::read_to_string(path)
            .with_context(|| format!("failed to read `{}`", path.display()))?,
    };
    let data = BloatJson::from_json_str(&json).map_err(|err| {
        let source = match from_stdin {
            true => "stdin".to_owned(),
            false => format!("`{}`", path.display()),
        };
        anyhow::Error::new(err).context(format!("invalid `cargo bloat` JSON on {source}"))
    })?;
    Ok((data, json))
}

pub fn human_size(bytes: u64) -> String {
    const UNIT: f64 = 1024.0;
    let bytes = bytes as f64;
    if bytes < UNIT {
        return format!("{bytes:.0} B");
    }
    if bytes < UNIT * UNIT {
        return format!("{:.1} KiB", bytes / UNIT);
    }
    format!("{:.2} MiB", bytes / (UNIT * UNIT))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sizes_are_human_readable() {
        assert_eq!(human_size(512), "512 B");
        assert_eq!(human_size(2048), "2.0 KiB");
        assert_eq!(human_size(5 * 1024 * 1024), "5.00 MiB");
    }

    #[test]
    fn a_relative_path_is_made_absolute() {
        let path = absolute(Path::new("bloat.html"));
        assert!(path.is_absolute(), "{}", path.display());
        assert!(path.ends_with("bloat.html"), "{}", path.display());
    }

    /// An absolute directory, spelled per platform: on Windows a leading `\` is
    /// only root-relative, so `absolute` would still prepend the current drive.
    #[cfg(windows)]
    const TMP: &str = r"C:\tmp";
    #[cfg(not(windows))]
    const TMP: &str = "/tmp";

    #[test]
    fn an_absolute_path_is_left_alone() {
        // A printed path is not a URL; escaping would break copy-paste.
        let input = Path::new(TMP)
            .join("my reports")
            .join("gr\u{fc}\u{df}e.html");
        assert_eq!(absolute(&input), input);
    }

    #[test]
    fn symlinks_are_not_resolved() {
        // `/tmp` is a symlink to `/private/tmp` on macOS.
        let input = Path::new(TMP).join("bloat.html");
        assert_eq!(absolute(&input), input);
    }

    #[test]
    fn the_colour_choice_decides_before_the_terminal_does() {
        assert!(hyperlinks_wanted(ColorChoice::Always));
        assert!(hyperlinks_wanted(ColorChoice::AlwaysAnsi));
        assert!(!hyperlinks_wanted(ColorChoice::Never));
    }

    #[test]
    fn a_suppressed_hyperlink_leaves_the_line_alone() {
        let link = Hyperlink::<String>::default();
        assert_eq!(
            format!("   Generated {link}/tmp/bloat.html{link:#}"),
            "   Generated /tmp/bloat.html"
        );
    }

    #[test]
    fn a_hyperlink_wraps_the_path_in_osc_8() {
        let link = Hyperlink::with_path(Path::new("/tmp/my reports/bloat.html"));
        let line = format!("{link}/tmp/my reports/bloat.html{link:#}");
        // Escaped for the URL, plain for the eye.
        assert!(line.contains("/tmp/my%20reports/bloat.html"), "{line:?}");
        assert!(
            line.ends_with("/tmp/my reports/bloat.html\u{1b}]8;;\u{1b}\\"),
            "{line:?}"
        );
    }
}