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 {
#[arg(short = 'o', long, value_name = "PATH", default_value = "bloat.html")]
pub output: PathBuf,
#[arg(long)]
pub open: bool,
}
pub fn deliver(args: &RenderArgs, html: &str, data: &BloatJson) -> Result<()> {
let path = &args.output;
write_file(path, html.as_bytes())?;
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()))
}
fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
fn hyperlink(path: &Path) -> Hyperlink<String> {
match hyperlinks_wanted(style::effective()) {
true => Hyperlink::with_path(path),
false => Hyperlink::default(),
}
}
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),
}
}
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());
}
#[cfg(windows)]
const TMP: &str = r"C:\tmp";
#[cfg(not(windows))]
const TMP: &str = "/tmp";
#[test]
fn an_absolute_path_is_left_alone() {
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() {
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:#}");
assert!(line.contains("/tmp/my%20reports/bloat.html"), "{line:?}");
assert!(
line.ends_with("/tmp/my reports/bloat.html\u{1b}]8;;\u{1b}\\"),
"{line:?}"
);
}
}