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 {
input: PathBuf,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, value_name = "PATH")]
source_map: Option<PathBuf>,
#[arg(long)]
no_sources_content: bool,
#[arg(long)]
source_map_url: bool,
#[arg(long, default_value_t = 200, value_name = "N")]
max_line_len: usize,
#[arg(long)]
rename: bool,
#[arg(long, value_name = "N")]
max_expr_depth: Option<usize>,
#[arg(long, value_name = "N")]
max_function_expr_depth: Option<usize>,
},
Resolve {
#[command(flatten)]
map: MapArgs,
#[arg(long)]
line: u32,
#[arg(long, visible_alias = "column")]
pos: u32,
},
Remap {
#[command(flatten)]
map: MapArgs,
},
Stats {
input: PathBuf,
},
}
#[derive(Args)]
struct MapArgs {
#[arg(long, value_name = "PATH")]
map: PathBuf,
#[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(())
}
}
}
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
}
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"
);
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);
}
}