use std::ffi::OsString;
use std::fs;
use std::io::{self, BufWriter, Read, Write};
use std::path::PathBuf;
use std::process::ExitCode;
use clap::{ArgAction, Parser};
use rs_retrace::{RetraceContext, RetraceOptions, Retracer};
#[derive(Debug, Parser)]
#[command(
name = "retrace",
version,
disable_version_flag = true,
about = "Retrace a JVM or Android stack trace with an R8 or ProGuard mapping file."
)]
struct Cli {
#[arg(value_name = "proguard-map")]
mapping: PathBuf,
#[arg(value_name = "stack-trace-file")]
stack_trace: Option<PathBuf>,
#[arg(long)]
verbose: bool,
#[arg(long)]
info: bool,
#[arg(long)]
quiet: bool,
#[arg(short = 'v', long, action = ArgAction::Version)]
version: Option<bool>,
#[arg(long, alias = "r", value_name = "regexp", hide = true)]
regex: Option<String>,
#[arg(long, alias = "p", value_name = "file", hide = true)]
partition_map: Option<PathBuf>,
#[arg(long, hide = true)]
verify_mapping_file_hash: bool,
}
fn main() -> ExitCode {
let cli = Cli::parse_from(r8_style_arguments(std::env::args_os()));
match run(&cli) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("Error: {message}");
ExitCode::FAILURE
}
}
}
fn r8_style_arguments(arguments: impl Iterator<Item = OsString>) -> Vec<OsString> {
let mut arguments = arguments.collect::<Vec<_>>();
for argument in arguments.iter_mut().skip(1) {
let Some(text) = argument.to_str() else {
continue;
};
if text == "--" {
break;
}
if text.len() > 2 && text.starts_with('-') && !text.starts_with("--") {
*argument = format!("-{text}").into();
}
}
arguments
}
fn run(cli: &Cli) -> Result<(), String> {
let unsupported = [
(cli.regex.is_some(), "--regex"),
(cli.partition_map.is_some(), "--partition-map"),
(cli.verify_mapping_file_hash, "--verify-mapping-file-hash"),
];
if let Some((_, option)) = unsupported.iter().find(|(set, _)| *set) {
return Err(format!("{option} is not supported"));
}
if !cli.mapping.exists() {
return Err(format!(
"Could not find mapping file '{}'.",
cli.mapping.display()
));
}
let (input, from_stdin) = match &cli.stack_trace {
Some(path) => (
fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?,
false,
),
None => {
if !cli.quiet {
println!("Waiting for stack-trace input...");
}
let mut bytes = Vec::new();
io::stdin()
.read_to_end(&mut bytes)
.map_err(|error| format!("standard input: {error}"))?;
(String::from_utf8_lossy(&bytes).into_owned(), true)
}
};
let retracer = Retracer::from_path(&cli.mapping)
.map_err(|error| format!("{}: {error}", cli.mapping.display()))?;
for warning in retracer.warnings() {
eprintln!(
"Warning: mapping line {}: {}",
warning.line, warning.message
);
}
let options = RetraceOptions {
verbose: cli.verbose,
};
let mut context = RetraceContext::default();
let mut output = BufWriter::new(io::stdout().lock());
let written = split_lines(&input, from_stdin)
.into_iter()
.try_for_each(|line| {
retracer
.retrace_line(line, &mut context, options)
.iter()
.try_for_each(|retraced| writeln!(output, "{retraced}"))
})
.and_then(|()| output.flush());
match written {
Err(error) if error.kind() != io::ErrorKind::BrokenPipe => {
Err(format!("standard output: {error}"))
}
_ => Ok(()),
}
}
fn split_lines(text: &str, scanner: bool) -> Vec<&str> {
let mut lines = Vec::new();
let mut start = 0;
let mut characters = text.char_indices().peekable();
while let Some((index, character)) = characters.next() {
let separator = match character {
'\n' | '\r' => true,
'\u{85}' | '\u{2028}' | '\u{2029}' => scanner,
_ => false,
};
if !separator {
continue;
}
lines.push(&text[start..index]);
start = index + character.len_utf8();
if character == '\r' && characters.next_if(|&(_, next)| next == '\n').is_some() {
start += 1;
}
}
if start < text.len() {
lines.push(&text[start..]);
}
if scanner {
while lines
.last()
.is_some_and(|line| line.chars().all(is_java_whitespace))
{
lines.pop();
}
}
lines
}
fn is_java_whitespace(character: char) -> bool {
matches!(character, '\u{1c}'..='\u{1f}')
|| (character.is_whitespace()
&& !matches!(character, '\u{85}' | '\u{a0}' | '\u{2007}' | '\u{202f}'))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_lines_like_java() {
assert_eq!(split_lines("", false), Vec::<&str>::new());
assert_eq!(split_lines("a\r\nb\rc\nd", false), ["a", "b", "c", "d"]);
assert_eq!(split_lines("a\n\nb\n", false), ["a", "", "b"]);
assert_eq!(
split_lines("a\u{2028}b\n \n\t\n", false),
["a\u{2028}b", " ", "\t"]
);
assert_eq!(split_lines("a\u{2028}b\n \n\t\n", true), ["a", "b"]);
assert_eq!(split_lines("a\n\u{a0}\n", true), ["a", "\u{a0}"]);
}
#[test]
fn accepts_single_dash_long_options() {
let arguments = ["retrace", "-verbose", "-v", "--quiet", "-", "--", "-x"];
let translated = r8_style_arguments(arguments.iter().map(OsString::from));
assert_eq!(
translated,
["retrace", "--verbose", "-v", "--quiet", "-", "--", "-x"].map(OsString::from)
);
}
#[test]
fn verifies_the_command_definition() {
use clap::CommandFactory;
Cli::command().debug_assert();
}
}