slimwasm 0.1.0

A WASM size profiler for wasm32-unknown-unknown and wasm32-wasip2 binaries
Documentation
//! Implementation of the `top` command

use crate::analysis::RetainedSizeAnalyzer;
use crate::parser::parse_wasm;
use anyhow::{Context, Result};
use colored::Colorize;
use humansize::{format_size, BINARY};
use std::path::Path;

/// Run the top command
pub fn run(path: &Path, limit: usize, retained: bool, json: bool) -> Result<()> {
    let parsed = parse_wasm(path).context("Failed to parse WASM file")?;
    let analyzer = RetainedSizeAnalyzer::new(parsed);
    let analysis = analyzer.analyze(retained);

    if json {
        output_json(&analysis, limit, retained)?;
    } else {
        output_human(&analysis, limit, retained, path)?;
    }

    Ok(())
}

fn output_json(
    analysis: &crate::analysis::WasmAnalysis,
    limit: usize,
    retained: bool,
) -> Result<()> {
    let mut items = analysis.items.clone();

    // Sort by appropriate size metric
    if retained {
        items.sort_by_key(|b| std::cmp::Reverse(b.retained_size));
    } else {
        items.sort_by_key(|b| std::cmp::Reverse(b.shallow_size));
    }

    // Filter to items with non-zero size and limit
    let top_items: Vec<_> = items
        .into_iter()
        .filter(|item| item.shallow_size > 0 || item.retained_size > 0)
        .take(limit)
        .collect();

    #[derive(serde::Serialize)]
    struct JsonOutput {
        total_size: u64,
        is_component: bool,
        items: Vec<crate::analysis::ItemInfo>,
        section_sizes: std::collections::HashMap<String, u64>,
    }

    let output = JsonOutput {
        total_size: analysis.total_size,
        is_component: analysis.is_component,
        items: top_items,
        section_sizes: analysis.section_sizes.clone(),
    };

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

fn output_human(
    analysis: &crate::analysis::WasmAnalysis,
    limit: usize,
    retained: bool,
    path: &Path,
) -> Result<()> {
    let mut items = analysis.items.clone();

    // Sort by appropriate size metric
    if retained {
        items.sort_by_key(|b| std::cmp::Reverse(b.retained_size));
    } else {
        items.sort_by_key(|b| std::cmp::Reverse(b.shallow_size));
    }

    // Filter to items with non-zero size
    let items: Vec<_> = items
        .into_iter()
        .filter(|item| item.shallow_size > 0 || item.retained_size > 0)
        .collect();

    // Header
    println!();
    println!(
        "{}",
        format!(
            " {} - {} ",
            path.file_name().unwrap_or_default().to_string_lossy(),
            format_size(analysis.total_size, BINARY)
        )
        .bold()
        .white()
        .on_blue()
    );
    println!();

    if analysis.is_component {
        println!("{}", "  [Component Model Binary]".cyan());
        println!();
    }

    // Section sizes
    println!("{}", "Sections:".bold());
    let mut sections: Vec<_> = analysis.section_sizes.iter().collect();
    sections.sort_by(|a, b| b.1.cmp(a.1));
    for (name, size) in sections.iter().take(10) {
        let pct = (**size as f64 / analysis.total_size as f64) * 100.0;
        println!(
            "  {:>10}  {:>6.1}%  {}",
            format_size(**size, BINARY).yellow(),
            pct,
            name
        );
    }
    println!();

    // Top items
    let size_label = if retained { "Retained" } else { "Shallow" };
    println!("{} (top {}):", format!("{} Size", size_label).bold(), limit);

    let display_count = std::cmp::min(limit, items.len());
    for item in items.iter().take(display_count) {
        let size = if retained {
            item.retained_size
        } else {
            item.shallow_size
        };
        let pct = (size as f64 / analysis.total_size as f64) * 100.0;

        let kind_str = format!("[{}]", item.kind);
        let kind_colored = match item.kind {
            crate::parser::WasmItemKind::Function => kind_str.green(),
            crate::parser::WasmItemKind::Data => kind_str.yellow(),
            crate::parser::WasmItemKind::Custom => kind_str.cyan(),
            _ => kind_str.white(),
        };

        // Truncate long names
        let name = if item.name.len() > 60 {
            format!("{}...", &item.name[..57])
        } else {
            item.name.clone()
        };

        println!(
            "  {:>10}  {:>6.1}%  {}  {}",
            format_size(size, BINARY).yellow(),
            pct,
            kind_colored,
            name
        );
    }

    if items.len() > display_count {
        println!(
            "\n  {} more items not shown. Use -n {} to see more.",
            items.len() - display_count,
            items.len()
        );
    }

    println!();
    Ok(())
}