retrace-cli 0.0.1

Command-line retrace for R8 and ProGuard mappings, compatible with R8's retrace
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! A command-line retrace compatible with R8's `retrace`:
//!
//! ```text
//! retrace [options] <proguard-map> [stack-trace-file]
//! ```
//!
//! The stack trace is read from standard input when no file is given. Output
//! goes to standard output, one line per retraced line, and diagnostics go to
//! standard error.

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 {
    /// A mapping file generated by R8 or ProGuard.
    #[arg(value_name = "proguard-map")]
    mapping: PathBuf,

    /// The stack trace to retrace. Read from standard input when omitted.
    #[arg(value_name = "stack-trace-file")]
    stack_trace: Option<PathBuf>,

    /// Get verbose retraced output.
    #[arg(long)]
    verbose: bool,

    /// Write information messages to stdout.
    #[arg(long)]
    info: bool,

    /// Silence ordinary messages printed to stdout.
    #[arg(long)]
    quiet: bool,

    /// Print version.
    #[arg(short = 'v', long, action = ArgAction::Version)]
    version: Option<bool>,

    // R8 options that this implementation does not support. They are accepted
    // so that the error names the option instead of reporting a parse error.
    #[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
        }
    }
}

/// Like R8, accepts single-dash long options such as `-verbose`.
fn r8_style_arguments(arguments: impl Iterator<Item = OsString>) -> Vec<OsString> {
    let mut arguments = arguments.collect::<Vec<_>>();
    // Skip the program name and stop at the `--` separator.
    for argument in arguments.iter_mut().skip(1) {
        let Some(text) = argument.to_str() else {
            continue;
        };
        if text == "--" {
            break;
        }
        // Single-letter options such as `-v` and `-h` stay short options.
        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()
        ));
    }

    // Read the stack trace before loading the mapping, as R8 does.
    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 {
        // A closed pipe, as in `retrace map.txt trace.txt | head`, is not an error.
        Err(error) if error.kind() != io::ErrorKind::BrokenPipe => {
            Err(format!("standard output: {error}"))
        }
        _ => Ok(()),
    }
}

/// Splits lines as R8 reads them. Files use Java's `readAllLines`, which
/// splits on `\n`, `\r\n`, and `\r`. Standard input uses `Scanner`, which also
/// splits on U+0085, U+2028, and U+2029, and stops once only whitespace is left.
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
}

/// `Character.isWhitespace` in Java.
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();
    }
}