rhaiper 0.2.0

Minifier for Rhai scripts, with Source Map v3 output
Documentation
//! Command line interface for rhaiper.

use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};
use rhaiper::map::{MapOptions, SourceMap};
use rhaiper::{Options, minify};

#[derive(Parser)]
#[command(
    name = "rhaiper",
    about = "Minify Rhai scripts and map positions back to source"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Minify a script, optionally writing a source map beside it.
    Minify {
        /// Script to minify.
        input: PathBuf,
        /// Where to write the minified script. Defaults to standard output.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Where to write the Source Map v3 document.
        #[arg(long, value_name = "PATH")]
        source_map: Option<PathBuf>,
        /// Omit the original source from the map, making it smaller but not standalone.
        #[arg(long)]
        no_sources_content: bool,
        /// Append a `//# sourceMappingURL=` comment. Off by default, since it costs flash.
        #[arg(long)]
        source_map_url: bool,
        /// Maximum characters per output line.
        #[arg(long, default_value_t = 200, value_name = "N")]
        max_line_len: usize,
        /// Also shorten local variable names, where the script can be shown to allow it.
        #[arg(long)]
        rename: bool,
        /// Expression nesting limit, to match a host that raised rhai's default of 32.
        #[arg(long, value_name = "N")]
        max_expr_depth: Option<usize>,
        /// Expression nesting limit inside functions, default 16.
        #[arg(long, value_name = "N")]
        max_function_expr_depth: Option<usize>,
    },
    /// Map one position in a minified script back to the original.
    Resolve {
        #[command(flatten)]
        map: MapArgs,
        /// Line number as reported by rhai, 1-based.
        #[arg(long)]
        line: u32,
        /// Character position as reported by rhai, 1-based.
        #[arg(long, visible_alias = "column")]
        pos: u32,
    },
    /// Rewrite every `line N, position M` on standard input to its original position.
    Remap {
        #[command(flatten)]
        map: MapArgs,
    },
    /// Report where a script's bytes go.
    Stats {
        /// Script to measure.
        input: PathBuf,
    },
}

#[derive(Args)]
struct MapArgs {
    /// Source map produced by `rhaiper minify`.
    #[arg(long, value_name = "PATH")]
    map: PathBuf,
    /// The minified script. Needed only if it contains astral-plane characters such as emoji,
    /// because map columns are UTF-16 units while rhai counts characters.
    #[arg(long, value_name = "PATH")]
    script: Option<PathBuf>,
}

impl MapArgs {
    fn load(&self) -> Result<(SourceMap, String), String> {
        let json = read(&self.map)?;
        let map = SourceMap::from_json(&json)?;
        let script = match &self.script {
            Some(path) => read(path)?,
            None => String::new(),
        };
        Ok((map, script))
    }
}

fn read(path: &Path) -> Result<String, String> {
    std::fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))
}

fn main() -> ExitCode {
    match run(Cli::parse()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(message) => {
            eprintln!("rhaiper: {message}");
            ExitCode::FAILURE
        }
    }
}

fn run(cli: Cli) -> Result<(), String> {
    match cli.command {
        Command::Minify {
            input,
            output,
            source_map,
            no_sources_content,
            source_map_url,
            max_line_len,
            rename,
            max_expr_depth,
            max_function_expr_depth,
        } => {
            let src = read(&input)?;
            let depths = match (max_expr_depth, max_function_expr_depth) {
                (None, None) => None,
                (global, function) => Some((global.unwrap_or(32), function.unwrap_or(16))),
            };
            let opts = Options {
                max_line_len,
                rename,
                max_expr_depth: depths,
            };
            let out = minify(&src, &opts).map_err(|e| e.to_string())?;
            for reason in &out.rename_declined {
                eprintln!("rhaiper: not renaming: {reason}");
            }

            let mut text = out.text.clone();
            if let Some(path) = source_map.as_ref().filter(|_| source_map_url) {
                let name = path.file_name().unwrap_or(path.as_os_str());
                text.push_str(&format!(
                    "\n//# sourceMappingURL={}",
                    name.to_string_lossy()
                ));
            }

            if let Some(path) = &source_map {
                let opts = MapOptions {
                    file: output.as_ref().map(|p| p.display().to_string()),
                    source_name: input.display().to_string(),
                    include_sources_content: !no_sources_content,
                };
                let json = out.to_source_map(&src, &opts);
                std::fs::write(path, json)
                    .map_err(|e| format!("cannot write {}: {e}", path.display()))?;
            }

            match &output {
                Some(path) => std::fs::write(path, &text)
                    .map_err(|e| format!("cannot write {}: {e}", path.display()))?,
                None => print!("{text}"),
            }

            if output.is_some() {
                let saved = src.len().saturating_sub(text.len());
                let percent = if src.is_empty() {
                    0.0
                } else {
                    saved as f64 / src.len() as f64 * 100.0
                };
                eprintln!(
                    "{} -> {} bytes ({saved} saved, {percent:.1}%){}",
                    src.len(),
                    text.len(),
                    match out.renamed_bindings {
                        0 => String::new(),
                        n => format!(", {n} bindings renamed"),
                    }
                );
            }
            Ok(())
        }

        Command::Resolve { map, line, pos } => {
            let (map, script) = map.load()?;
            match map.resolve(&script, line, pos) {
                Some(o) => {
                    println!("{}:{}:{}", o.source, o.line, o.column);
                    Ok(())
                }
                None => Err(format!("no mapping covers line {line}, position {pos}")),
            }
        }

        Command::Remap { map } => {
            let (map, script) = map.load()?;
            let mut input = String::new();
            std::io::stdin()
                .read_to_string(&mut input)
                .map_err(|e| format!("cannot read standard input: {e}"))?;

            let out = remap(&map, &script, &input);
            std::io::stdout()
                .write_all(out.as_bytes())
                .map_err(|e| format!("cannot write standard output: {e}"))
        }

        Command::Stats { input } => {
            let src = read(&input)?;
            let toks = rhaiper::lex::tokenize(&src).map_err(|e| e.to_string())?;

            let comments: usize = toks
                .iter()
                .filter(|t| t.is_comment())
                .map(|t| t.span.len())
                .sum();
            let code: usize = toks
                .iter()
                .filter(|t| !t.is_comment())
                .map(|t| t.span.len())
                .sum();
            let whitespace = src.len().saturating_sub(comments + code);
            let minified = minify(&src, &Options::default())
                .map_err(|e| e.to_string())?
                .text
                .len();

            let pct = |n: usize| {
                if src.is_empty() {
                    0.0
                } else {
                    n as f64 / src.len() as f64 * 100.0
                }
            };
            println!("{:<12}{:>9}", "total", src.len());
            println!("{:<12}{:>9}  {:>5.1}%", "code", code, pct(code));
            println!("{:<12}{:>9}  {:>5.1}%", "comments", comments, pct(comments));
            println!(
                "{:<12}{:>9}  {:>5.1}%",
                "whitespace",
                whitespace,
                pct(whitespace)
            );
            println!("{:<12}{:>9}  {:>5.1}%", "minified", minified, pct(minified));
            Ok(())
        }
    }
}

/// Rewrites rhai's `line N, position M` phrasing in place, leaving everything else untouched.
fn remap(map: &SourceMap, script: &str, input: &str) -> String {
    const PREFIX: &str = "line ";
    const MIDDLE: &str = ", position ";

    let mut out = String::with_capacity(input.len());
    let mut rest = input;

    while let Some(at) = rest.find(PREFIX) {
        out.push_str(&rest[..at]);
        let after_prefix = &rest[at + PREFIX.len()..];

        let parsed = split_number(after_prefix)
            .and_then(|(line, tail)| {
                let tail = tail.strip_prefix(MIDDLE)?;
                let (pos, tail) = split_number(tail)?;
                Some((line, pos, tail))
            })
            .and_then(|(line, pos, tail)| map.resolve(script, line, pos).map(|o| (o, tail)));

        match parsed {
            Some((original, tail)) => {
                out.push_str(&format!(
                    "line {}, position {} [{}]",
                    original.line, original.column, original.source
                ));
                rest = tail;
            }
            None => {
                out.push_str(PREFIX);
                rest = after_prefix;
            }
        }
    }
    out.push_str(rest);
    out
}

/// Splits a leading run of digits off `s`.
fn split_number(s: &str) -> Option<(u32, &str)> {
    let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
    if end == 0 {
        return None;
    }
    s[..end].parse().ok().map(|n| (n, &s[end..]))
}

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

    fn fixture() -> (SourceMap, String) {
        let src = "let alpha = 1;\nlet beta = alpha + 2;\nbeta\n";
        let out = minify(src, &Options::default()).unwrap();
        let json = out.to_source_map(src, &MapOptions::default());
        (SourceMap::from_json(&json).unwrap(), out.text)
    }

    #[test]
    fn remaps_a_position_inside_a_message() {
        let (map, script) = fixture();
        let got = remap(
            &map,
            &script,
            "Variable not found: beta (line 1, position 1)\n",
        );
        assert!(
            got.starts_with("Variable not found: beta (line 1, position 1 ["),
            "got {got:?}"
        );
    }

    #[test]
    fn leaves_unrelated_text_alone() {
        let (map, script) = fixture();
        assert_eq!(
            remap(&map, &script, "no positions here"),
            "no positions here"
        );
        // A phrase that starts like a position but is not one.
        assert_eq!(
            remap(&map, &script, "line up the parts"),
            "line up the parts"
        );
        assert_eq!(remap(&map, &script, "line 4"), "line 4");
    }

    #[test]
    fn passes_through_positions_with_no_mapping() {
        let (map, script) = fixture();
        let input = "oops (line 99, position 1)";
        assert_eq!(remap(&map, &script, input), input);
    }

    #[test]
    fn splits_numbers() {
        assert_eq!(split_number("12abc"), Some((12, "abc")));
        assert_eq!(split_number("7"), Some((7, "")));
        assert_eq!(split_number("abc"), None);
    }
}