Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
use rust_anything::walk::Canonical;
use std::io::Write as _;
use std::path::PathBuf;
use std::process::ExitCode;
/// `println!` that stops quietly when stdout is closed (`rust-anything ... | head`).
macro_rules! say {
($($arg:tt)*) => {{
let _ = writeln!(std::io::stdout().lock(), $($arg)*);
}};
}
macro_rules! say_raw {
($($arg:tt)*) => {{
let _ = write!(std::io::stdout().lock(), $($arg)*);
}};
}
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use rust_anything::{
analyze, app, app_shadow, bridge, drift, front_door, gate, harness, lift, mcp, report, shadow,
};
#[derive(Parser)]
#[command(
name = "rust-anything",
version,
about = "Rewrite TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C#, PowerShell or Swift apps in Rust, one verified piece at a time",
after_help = "Loop per unit: analyze -> bridge -> record -> port src/port.rs -> build -> diff -> shadow (skip for PHP, C#, PowerShell, and Swift) -> gate\nOnly the slow part: go --agent claude -- <workload>, then enable/disable and report"
)]
struct Cli {
#[command(subcommand)]
command: Cmd,
}
#[derive(Clone, Copy, ValueEnum)]
enum KindArg {
Napi,
Wasm,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
enum Profile {
/// Run on this machine.
Host,
/// Run on Android: the JNI library for the ABIs in `jniLibs/`, and on a connected device when
/// replaying.
Android,
}
#[derive(Subcommand)]
enum Cmd {
/// 1. Map a repository and write a ranked, ordered migration plan.
Analyze {
/// Repository root.
#[arg(default_value = ".")]
root: PathBuf,
/// Print the machine-readable report (schema `rust-anything/analyze@1`) instead of Markdown.
#[arg(long)]
json: bool,
/// Write to this file instead of stdout.
#[arg(long, short)]
out: Option<PathBuf>,
/// Source language; detected from the repository when omitted.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// Plan a whole-app port: entry points and shape, every dependency (imported or
/// declared) with its crate, pieces in port order, and decisions for the user.
#[arg(long)]
whole_app: bool,
},
/// 2. Scaffold a Rust crate with bindings for one unit.
Bridge {
/// Repository root.
root: PathBuf,
/// Unit id from `analyze`, or a source file inside a unit to bridge on its own.
unit: String,
/// TS/JS units: napi or wasm; defaults to the plan's choice. Other languages have
/// their own bridge.
#[arg(long, value_enum)]
kind: Option<KindArg>,
/// Crate folder; defaults to `<root>/rust/<name>`.
#[arg(long, short)]
out: Option<PathBuf>,
/// Crate name; defaults to `<unit>-rs`.
#[arg(long)]
name: Option<String>,
/// Bridge a unit the plan marks blocked or keep.
#[arg(long)]
force: bool,
/// Keep an export in the original language: `name` or `"name: reason"`. Repeatable.
#[arg(long)]
keep: Vec<String>,
/// Add a batch class: `function:param` runs `function` over many `param` values kept in
/// Rust, on all cores (what `profile` recommends for leaves called in loops).
#[arg(long)]
batch: Vec<String>,
/// TS/JS units: bridge a type parameter as JSON values (`--as-json T`) when the app only
/// fills it with data, instead of keeping the generic export in TS. Repeatable.
#[arg(long, value_name = "TYPE_PARAM")]
as_json: Vec<String>,
/// Global allocator for crates with batches: `mimalloc` (C; wasm keeps Rust's default)
/// or `rusty_alloc` (pure Rust, no C compiler; wasm too). Kept in `rust-anything.json`.
#[arg(long, value_enum, default_value = "mimalloc")]
allocator: bridge::Allocator,
/// What the bindings are for once the port is done: `replace` (the original is deleted
/// after cut-over), `bindings` (callers keep importing it: public API) or `scaffold`
/// (the bindings are deleted at cut-over). Kept in `rust-anything.json`.
#[arg(long, value_enum)]
end_state: Option<bridge::EndState>,
},
/// 2b. Regenerate the bindings and the language wrapper from the signatures in `port.rs`.
Refresh {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Add a batch class: `function:param` runs `function` over many `param` values kept in
/// Rust, on all cores. Repeat for more.
#[arg(long)]
batch: Vec<String>,
},
/// 3a. Record what the original's functions return on generated and given inputs.
Record {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Generated cases per function.
#[arg(long, default_value_t = 200)]
count: usize,
/// Extra cases: JSONL of `{"fn": name, "args": [...]}`, plus `"kwargs": {...}` for Python
/// and Ruby arguments passed by keyword.
#[arg(long)]
inputs: Option<PathBuf>,
/// Import the original from this JS module (e.g. built output) instead of the TS source.
#[arg(long)]
module: Option<PathBuf>,
/// Resolve npm packages from this folder's `node_modules` (when the repo has none installed).
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
/// Floats match when they differ by at most this times the larger magnitude (absolute
/// below 1), e.g. 1e-9 for numeric code. Saved with the crate for diff and gate; 0 removes it.
#[arg(long, allow_negative_numbers = true)]
float_tolerance: Option<f64>,
/// Allow a --float-tolerance above 1e-6, which forgives differences that are not rounding.
#[arg(long)]
allow_large_tolerance: bool,
/// Compare objects regardless of key order, now and in every later `diff`, `gate`, `enable`
/// and `report`. `--no-ignore-key-order` saves the opposite.
#[arg(long, overrides_with = "no_ignore_key_order")]
ignore_key_order: bool,
/// Save "keep the original's key order", undoing an earlier `--ignore-key-order`.
#[arg(long, overrides_with = "ignore_key_order")]
no_ignore_key_order: bool,
/// Compare error messages as well as error classes, now and in every later `diff` and
/// `gate`. Off by default: a thrown error matches on its class only. `--no-messages` saves
/// the opposite.
#[arg(long, overrides_with = "no_messages")]
messages: bool,
/// Save "compare errors by class only", undoing an earlier `--messages`.
#[arg(long, overrides_with = "messages")]
no_messages: bool,
/// Also record every call the original's own test suite makes to the unit's functions:
/// `--from-tests -- npx jest` (TS/JS, any runner) or `-- pytest` (Python).
#[arg(long)]
from_tests: bool,
/// The test command for `--from-tests`, after `--`; it runs in the original's folder.
#[arg(last = true)]
test_command: Vec<String>,
/// Target: this machine, or a connected Android device (for JVM crates).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android device serial; picked automatically when only one is connected.
#[arg(long)]
device: Option<String>,
/// Pin the clock and random numbers while recording and diffing (TS/JS with napi,
/// Python): sets `TZ=UTC` for the original and the port (so naive `datetime.now()`/
/// `today()` and `date.today()` record in UTC), and pins `Date.now()`, `new Date()` and
/// `Math.random` in JS, and `time.time()`, `time.time_ns()`, `datetime.now()`/`today()`,
/// `datetime.utcnow()`, `date.today()` and `random` (`pinned::random()` for
/// `random.random()`, `pinned::randbelow()` / `getrandbits()` for `randint`, `randrange`,
/// `choice` and `shuffle`) in Python, saved in `pinned.json` and read by the port from
/// `src/port/pinned.rs`. Kept for later runs until `--no-pin-clock`.
#[arg(long, conflicts_with = "no_pin_clock")]
pin_clock: bool,
/// Stop pinning the clock and random numbers.
#[arg(long)]
no_pin_clock: bool,
/// Run the original with no network, its repository read-only and a CPU limit and, on Linux only, a memory limit
/// (RUST_ANYTHING_SANDBOX_CPU seconds, 600 by default; RUST_ANYTHING_SANDBOX_MEMORY_MB,
/// 4096, Linux only): bubblewrap on Linux, sandbox-exec on macOS. Fails when the tool
/// is missing rather than recording unsandboxed.
#[arg(long)]
sandbox: bool,
/// Let `record` leave out up to N generated inputs it could not record (the original's
/// result could not be encoded, or it ended the run). Without it, `record` fails and keeps
/// the old recording; `gate` then needs `--accept-dropped N` for the ones that were left out.
#[arg(long, value_name = "N")]
allow_dropped: Option<usize>,
},
/// 3b. Build the crate's native module for its language (napi-rs `.node` or wasm-bindgen output
/// for TS/JS, a PyO3 extension for Python, a shared library for the others) or, with
/// `--profile android`, the JNI library for Android ABIs into `jniLibs/`.
Build {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Target: this machine, or Android (needs the NDK and the Rust Android targets).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android ABI to build; repeatable. Defaults to arm64-v8a, armeabi-v7a and x86_64.
#[arg(long)]
abi: Vec<String>,
/// Android API level the libraries target (at least 26; defaults to 26).
#[arg(long)]
api: Option<u32>,
/// Android NDK root; found from ANDROID_NDK_HOME or the SDK when omitted.
#[arg(long)]
ndk: Option<PathBuf>,
/// Where to install the Android libraries; defaults to `<crate>/jniLibs`.
#[arg(long)]
jni_libs: Option<PathBuf>,
},
/// 3c. Replay recorded cases against the Rust module.
Diff {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Target: this machine, or a connected Android device (for JVM crates).
#[arg(long, value_enum, default_value_t = Profile::Host)]
profile: Profile,
/// Android device serial; picked automatically when only one is connected.
#[arg(long)]
device: Option<String>,
/// Android libraries folder to diff; defaults to `<crate>/jniLibs`.
#[arg(long)]
jni_libs: Option<PathBuf>,
/// Test this JS module instead of the crate's `index.cjs`.
#[arg(long)]
module: Option<PathBuf>,
/// Compare objects regardless of key order.
#[arg(long)]
ignore_key_order: bool,
/// Floats match within this tolerance for this run (the one saved by `record` otherwise).
#[arg(long, allow_negative_numbers = true)]
float_tolerance: Option<f64>,
/// Allow a --float-tolerance above 1e-6, which forgives differences that are not rounding.
#[arg(long)]
allow_large_tolerance: bool,
/// Print mismatches as shapes only: where they differ, types, lengths and hashes, never
/// values or arguments; safe to paste into an issue or hand to another agent.
#[arg(long)]
redact: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// 3d. Time the recorded cases on the original and on Rust, bridge included.
Bench {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Minimum measured time per function and side, in milliseconds.
#[arg(long, default_value_t = 200)]
min_ms: u64,
/// Resolve npm packages the original imports from this folder's `node_modules`.
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// 3e. Run fresh inputs from a new seed through the original and the port and report where
/// they differ: what the recorded cases did not cover.
Fuzz {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Fresh cases per function (and scenarios per class) in each round.
#[arg(long, default_value_t = 200)]
cases: usize,
/// Seed of the first round; random (and printed) when omitted. Later rounds count up.
#[arg(long)]
seed: Option<u64>,
/// Keep running new rounds until this many seconds have passed (one round otherwise).
#[arg(long, value_name = "SECS", allow_negative_numbers = true)]
time: Option<f64>,
/// Append the mismatching cases (`--keep`) or every fresh case (`--keep=all`) to
/// `cases.jsonl`, so the next diff and gate check them.
#[arg(long, value_enum, num_args = 0..=1, require_equals = true, default_missing_value = "mismatches")]
keep: Option<rust_anything::fuzz::Keep>,
/// Resolve npm packages the original imports from this folder's `node_modules`.
#[arg(long)]
resolve_from: Option<PathBuf>,
/// Run the original in every round as `record --sandbox` does: no network, its repository
/// read-only and a CPU limit and, on Linux only, a memory limit. Fails when bubblewrap
/// (Linux) or sandbox-exec (macOS) is missing rather than fuzzing unsandboxed.
#[arg(long)]
sandbox: bool,
/// Command that prints each round's inputs in `record --inputs` format, in place of the
/// built-in generator. It runs with `RUST_ANYTHING_SEED` (the round's seed) and
/// `RUST_ANYTHING_CASES` set; a non-zero exit or a bad line fails the run.
#[arg(long, value_name = "COMMAND")]
generator: Option<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
},
/// Run a real workload under the language's profiler and say what to port: hot functions,
/// their callers, and loops to batch. `rust-anything profile <repo> -- node bench.mjs` (also
/// `python3 x.py`, `go test -bench . ./pkg`, `java ...`, `ruby x.rb`)
Profile {
/// Repository root.
root: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Source language: ts, python, go, java or ruby; detected from the repository when
/// omitted. Any other language stops with the profiler to use instead.
#[arg(long, value_enum, hide_possible_values = true)]
lang: Option<rust_anything::lang::Lang>,
/// The workload, after `--`.
#[arg(last = true, required = true)]
command: Vec<String>,
},
/// The hot-path loop in one command: profile the workload, bridge the top portable function,
/// record it, hand the port to an agent, then build, diff and gate it, and switch it on only
/// when everything matches. `rust-anything go --agent claude -- python3 app.py`
Go {
/// Repository root, as `profile` takes it.
#[arg(value_name = "ROOT", conflicts_with = "root")]
path: Option<PathBuf>,
/// Repository root.
#[arg(long)]
root: Option<PathBuf>,
/// `claude`, `codex`, or any command that reads a prompt on stdin. Without it, `go` writes
/// the crate's TASK.md and stops; run it again once `src/port.rs` is ported.
#[arg(long)]
agent: Option<String>,
/// Port this function instead of the profile's pick.
#[arg(long)]
function: Option<String>,
/// Source language: ts, python, go, java or ruby; detected from the repository when
/// omitted. Any other language stops with the profiler to use instead.
#[arg(long, value_enum, hide_possible_values = true)]
lang: Option<rust_anything::lang::Lang>,
/// Generated cases per function, on top of the calls the workload makes.
#[arg(long, default_value_t = 200)]
count: usize,
/// Agent turns: the port, then one more per failing diff or gate (default: 3).
#[arg(long)]
rounds: Option<usize>,
/// Recorded cases that did not throw in the original, at least, before the port goes to
/// an agent or is switched on. Lower it for a function with few possible inputs.
#[arg(long, default_value_t = rust_anything::go::DEFAULT_MIN_CASES)]
min_cases: usize,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// The workload, after `--`.
#[arg(last = true, required = true)]
command: Vec<String>,
},
/// Switch a ported unit on: one marked block in the original source files rebinds its
/// functions to the Rust module, for every caller (TS/JS, Python and PowerShell). `disable` removes it.
Enable {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Switch on only these exported functions (repeatable).
#[arg(long = "only")]
only: Vec<String>,
/// Switch on only the functions whose recorded cases all match; leave the rest in the original.
#[arg(long, conflicts_with_all = ["only", "force"])]
partial: bool,
/// Switch it on even when recorded cases differ.
#[arg(long)]
force: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Switch a unit off: removes exactly the lines `enable` added.
Disable {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Write a unit's result for a pull request or README: REPORT.md and card.svg with the
/// recorded cases matched, the speedup from bench, the fallback rate and the machine.
Report {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Output folder; defaults to `<crate>/report`.
#[arg(long, short, value_parser = absolute)]
out: Option<PathBuf>,
/// Minimum measured time per function and side, in milliseconds.
#[arg(long, default_value_t = 200)]
min_ms: u64,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
/// Resolve npm packages the original imports from this folder's `node_modules`.
#[arg(long, value_parser = absolute)]
resolve_from: Option<PathBuf>,
},
/// Remove the build cache every port and bridge shares (CARGO_TARGET_DIR when set, else
/// rust-anything/target in your cache folder). Ports rebuild on their next build.
Clean {
/// Only print the folder and its size.
#[arg(long)]
dry_run: bool,
/// Remove it even when CARGO_TARGET_DIR names it (other cargo projects may build there).
#[arg(long)]
force: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// 4. Generate a drop-in module that runs the original and Rust side by side.
Shadow {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Where to write the module. The default depends on the language:
/// `<crate>/shadow/<name>.shadow.ts` (TypeScript), `<crate>/shadow/<name>_shadow.py`
/// (Python), `<crate>/shadow/<name>_shadow.c` (C), `<crate>/go/shadow/<pkg>.go` (Go),
/// `<crate>/ruby/<lib>_shadow.rb` (Ruby), and a folder, `<crate>/java/`, for Java and
/// Kotlin. PHP, C#, PowerShell and Swift have no shadow module yet and stop with an error.
#[arg(long, short)]
out: Option<PathBuf>,
},
/// 5. Check the definition of done for a port.
Gate {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// Print each check as a JSON line as soon as it is known, then a `result` line.
#[arg(long, conflicts_with = "json")]
json_events: bool,
/// Fresh inputs per function (and as many perturbed recorded ones) the held-out check
/// runs after `behavior` passes, from a seed taken from the clock; 0 turns it off.
#[arg(long, default_value_t = rust_anything::gate::HELD_OUT_CASES, value_name = "N")]
held_out_cases: usize,
/// Draw the held-out inputs from this seed, to replay a failing run (printed with it).
#[arg(long, value_name = "SEED")]
held_out_seed: Option<u64>,
/// Extra arguments for node, e.g. `--node-arg=--import=tsx`.
#[arg(long = "node-arg", allow_hyphen_values = true)]
node_args: Vec<String>,
/// Number of entries added to known-diffs.jsonl since the last passing gate, or, when
/// the entries accept more than a tenth of the cases, the number of cases they accept.
/// Without it, those fail the gate.
#[arg(long, value_name = "N")]
accept_known_diffs: Option<usize>,
/// The recording has fewer cases than at the last passing gate, and that is meant.
#[arg(long)]
accept_smaller_recording: bool,
/// `record` could not record this many generated cases, and you have looked at them.
#[arg(long, value_name = "N")]
accept_dropped: Option<u64>,
},
/// Check the checking: plant deliberately wrong ports (and tamper with the recording) against
/// a tiny built-in original in a scratch folder, and require `diff` or `gate` to refuse
/// each one and to pass one correct port. Prints each planted bug and whether it was caught.
Selftest {
/// Languages to test; every one whose toolchain is on PATH when omitted.
#[arg(long, value_enum)]
lang: Vec<rust_anything::lang::Lang>,
/// Leave the scratch folder in place and print where it is.
#[arg(long)]
keep: bool,
/// Fail on a documented known gap too, not only on a bug that should have been caught.
#[arg(long)]
strict: bool,
/// Run only the planted bugs with these ids (`hard-coded-table`, `delete-cases`, ...).
#[arg(long)]
only: Vec<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// 6. Lay out installable packages and a CI workflow for every platform; never publishes.
Package {
/// Crate folder made by `bridge`.
#[arg(default_value = ".", value_parser = absolute)]
crate_dir: PathBuf,
/// Package name on npm or PyPI; defaults to the crate name.
#[arg(long)]
name: Option<String>,
/// Package version; defaults to the original package's.
#[arg(long)]
version: Option<String>,
/// Output folder; defaults to `<crate>/package`.
#[arg(long, short, value_parser = absolute)]
out: Option<PathBuf>,
/// napi: the module to load where no binary fits (defaults to the original file when it
/// imports nothing).
#[arg(long)]
fallback: Option<String>,
/// CLI front door: a command the package installs (repeat for more); defaults to the
/// package name without its scope.
#[arg(long = "bin")]
bin: Vec<String>,
/// CLI front door: the original npm package it falls back to, as <name>@<version>;
/// defaults to the one in the repository's node_modules.
#[arg(long)]
original: Option<String>,
/// List the files, write nothing.
#[arg(long)]
dry_run: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Record the whole app's behavior and replay any build against it (CLIs and servers).
App {
#[command(subcommand)]
command: Box<AppCmd>,
},
/// Serve every step as MCP tools over stdio.
Mcp,
/// Register rust-anything with your coding agents (Claude Code, Codex, Cursor, Gemini CLI,
/// OpenCode): the MCP server and, where the agent reads skills, the workflow skill. Keeps your
/// other settings; run it again any time.
Setup {
/// Agents to set up (repeatable); every agent found by default.
#[arg(long = "agent", value_enum)]
agents: Vec<rust_anything::setup::Agent>,
/// Take the rust-anything entries out again.
#[arg(long)]
remove: bool,
/// Show what would change, write nothing.
#[arg(long)]
dry_run: bool,
/// Change settings files in place without saving a `.rust-anything.bak` copy first.
#[arg(long)]
no_backup: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Map the port: every unit of the original, the crate that ports it, its cases and last
/// diff, its last switch from the audit log, the whole app's glue, and which recordings the
/// original changed past since they were made. Commit the map (`--write`) to see upstream changes in it.
Map {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Also look for crates in this folder (crates kept outside the repository).
#[arg(long = "crates")]
crates: Vec<PathBuf>,
/// Write the map to rust/PORT_MAP.md in the repository instead of printing it.
#[arg(long, conflicts_with = "json")]
write: bool,
/// Exit 1 when the original changed since any port was recorded, or when a recording
/// cannot be trusted (fingerprint missing, cases edited, removed or dropped).
#[arg(long)]
check: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// The audit log (rust/audit.jsonl): every enable, disable, app wire and app lift, and each
/// gate result, oldest first, with the time, the version and the commit.
Log {
/// Repository root, or a crate folder made by `bridge`.
#[arg(default_value = ".")]
repo: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// List what the original offers, read from its source: exports, commands, flags, routes,
/// environment variables and the places where it fails on purpose. A family that could not
/// be listed in full says so, and only exports are ever called complete: commands, flags,
/// routes and environment variables list what the detectors recognise, for a person to
/// attest. Inventory only: the exit code is 0, except with `--check`. `obligations waive` and
/// `obligations attest` record the decisions that `app lift` asks for.
#[command(args_conflicts_with_subcommands = true)]
Obligations {
#[command(subcommand)]
action: Option<ObligationsCmd>,
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Say what blocks `app lift` in this repository and how to unblock it, and exit 1 when
/// anything does: an obligation no recorded case exercises that nobody waived, a family
/// that is not complete and that nobody attested (or whose attestation no longer matches
/// the ledger), an expected output file with a `...` line that matches any number of
/// lines or that cannot be opened, and an entry of rust/obligations-fallbacks.jsonl that no
/// recorded case, no registry entry and no waiver covers. It is an error when rust/obligations-bindings.toml or
/// rust/obligations-decisions.toml is invalid. With `--json` it prints the standing
/// (schema `rust-anything/standing@1`).
#[arg(long, conflicts_with_all = ["write", "evidence"])]
check: bool,
/// Source language; rust/obligations-source.toml gives it when omitted, or it is detected
/// from the repository. With `--check` it must match that file, which `app lift` reads
/// too. The same file names the original's executables (`entry`, read even when ignored
/// or extensionless) and the commands and flags no detector can see.
#[arg(long, value_enum)]
lang: Option<rust_anything::lang::Lang>,
/// Write the ledger to rust/OBLIGATIONS.json in the repository instead of printing it.
#[arg(long, conflicts_with = "json")]
write: bool,
/// Print the machine-readable ledger (schema `rust-anything/obligations@1`).
#[arg(long)]
json: bool,
/// Link each obligation to the recorded cases that exercise it, and list the ones with
/// no case, each with a candidate input. With `--json` it prints the evidence (schema
/// `rust-anything/evidence@1`); with `--write` it also writes
/// rust/OBLIGATIONS.evidence.json. Only recorded files are read and nothing runs. A file
/// that does not open (a link that leaves the repository, a link to nothing) or that is
/// not text is listed under "Not read", and the exit code stays 0, as it does when cases
/// are missing; so is a `.toml` that is not a regular file. It is an error when
/// rust/obligations-bindings.toml does not open or is invalid, or when a recorded case
/// `.toml` that opens does not parse as a case. A CLI case is read only when all four hold:
/// it records exit code 0 (a missing `status` is 0); it has no help or version spelling
/// (`--help`, `-h`, `--version`, `-V`), even declared; every option before `--` is declared
/// for its command; and, when the project declares commands, its first argument is a
/// declared command or alias, followed by a declared subcommand when it has any. The
/// others are listed in the notes with the reason; an explicit binding still holds.
#[arg(long)]
evidence: bool,
},
/// Check the language runtimes, the agent setup and the MCP server, with the command that
/// fixes each problem. Exits 1 when something required is missing.
Doctor {
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Start a new app in Rust, spec first: a binary crate with `spec/` (SPEC.md, cases the app
/// must pass) and a `main` that fails them until the app is written.
/// `rust-anything new my-tool`
New {
/// Folder for the app: empty or not there yet.
#[arg(value_parser = absolute)]
dir: PathBuf,
/// Package and binary name; defaults to the folder's name.
#[arg(long)]
name: Option<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// A new app's spec: the user approves its cases, and `check` says whether the app is done.
Spec {
#[command(subcommand)]
command: SpecCmd,
},
/// Show the port rules every agent prompt includes (rust/RULES.md), or add one: behavior the
/// port must keep exactly, learned from a correction.
Rules {
/// Repository root, or a crate folder made by `bridge`.
#[arg(default_value = ".")]
root: PathBuf,
/// Append a rule (repeatable); an exact duplicate is skipped.
#[arg(long = "add", value_name = "TEXT")]
add: Vec<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand)]
enum SpecCmd {
/// The user's step: approve the cases in spec/cases (all, or those named with --case). An
/// approved case counts toward done; editing it later fails `spec check` until it is
/// approved again. Not an MCP tool, so the approval stays with the user.
Approve {
/// The app's folder.
#[arg(default_value = ".", value_parser = absolute)]
dir: PathBuf,
/// Approve only this case (repeatable).
#[arg(long = "case", value_name = "NAME")]
case: Vec<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Build the app, run every case in spec/cases against it, run fmt, clippy, tests and the
/// unsafe audit, and say whether it is done: every case approved and passing, none changed
/// since its approval, no open question in SPEC.md. Otherwise it names the next step.
Check {
/// The app's folder.
#[arg(default_value = ".", value_parser = absolute)]
dir: PathBuf,
/// Run only this case.
#[arg(long)]
case: Option<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
}
/// What a person decides about the obligations `app lift` stops on.
#[derive(Subcommand)]
enum ObligationsCmd {
/// Waive obligations no recorded case exercises, with the reason: it writes an ADR in
/// rust/DECISIONS.md and an entry in rust/obligations-decisions.toml. An item is an exact id
/// or a pattern with `*`, expanded now into the ids that block today. It refuses (and writes
/// nothing) an item that is not blocking, that is already waived, or that names a file that
/// could not be opened, and a reason that is empty or on several lines.
Waive {
/// Obligation ids (`export:src/a.ts#f`) or patterns with `*` (`export:src/*`).
#[arg(required = true)]
items: Vec<String>,
/// Why these obligations need no recorded case; it goes in the ADR.
#[arg(long)]
reason: String,
/// Repository root.
#[arg(long, default_value = ".")]
repo: PathBuf,
},
/// Attest families the ledger cannot prove complete, with the reason: it writes an ADR and an
/// entry that holds the state and a fingerprint of the family, so it stops holding when the
/// ledger of that family changes. It refuses a family that is complete, one already attested
/// with the current ledger, and an empty reason.
Attest {
/// Families: export, command, flag, route, env or error-path.
#[arg(required = true)]
families: Vec<rust_anything::obligations::Family>,
/// Why a person vouches for the listed family; it goes in the ADR.
#[arg(long)]
reason: String,
/// Repository root.
#[arg(long, default_value = ".")]
repo: PathBuf,
},
/// Read the fallback journals a generated front door wrote (set `RUST_ANYTHING_FALLBACK_JOURNAL`
/// to a file when running it) and sort each distinct command line or request: refused by the
/// original (counted, not blocking), already recorded, explained by the registry, or outside
/// the registry. A journal with a bad line is refused whole, with every fault and its file:line.
/// `--write` stores the entries outside the registry in rust/obligations-fallbacks.jsonl,
/// where `app lift` stops on them until a case is recorded, the registry explains them, or
/// `waive` lifts them; that file holds command lines as typed, so review it before
/// committing. `--inputs` writes the lines `app record --inputs` reads for the entries outside
/// the registry and for the explained ones a case would cover; a stdin or a body is never in
/// the journal, so such an entry is listed to be completed by hand.
Fallbacks {
/// Journal files (JSON lines).
#[arg(required = true)]
journals: Vec<PathBuf>,
/// Repository root.
#[arg(long, default_value = ".")]
repo: PathBuf,
/// Store the entries outside the registry in rust/obligations-fallbacks.jsonl.
#[arg(long)]
write: bool,
/// Write `app record --inputs` lines to this file.
#[arg(long)]
inputs: Option<PathBuf>,
/// Print the machine-readable report (schema `rust-anything/fallbacks@1`).
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum AppCmd {
/// Run the original CLI or server on cases (its own examples, `--inputs`, semantic traps),
/// twice each, and store them in `<repo>/rust/app-cases/`: trycmd files for a CLI, HTTP
/// cases in `http/` for a server.
/// `rust-anything app record . -- python3 cli.py`
Record {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Extra cases: JSONL of `{"name", "args": [...], "stdin", "env": {...}, "files": {path: text},
/// "remove": [paths]}`. `remove` deletes paths from the `--fresh` copy before the case runs.
#[arg(long)]
inputs: Option<PathBuf>,
/// Normalizer: `timestamps`, `uuids`, `key-order`, or `name=regex` for your own. Repeatable;
/// saved with the cases.
#[arg(long)]
normalize: Vec<String>,
/// The name the app is invoked by in its docs (found from the command and manifests when omitted).
#[arg(long)]
name: Option<String>,
/// Leave out the semantic-trap inputs.
#[arg(long)]
no_traps: bool,
/// Seconds before a run is killed. Saved with the cases and used by replay; a later record
/// keeps the saved one (30 seconds unless it was changed).
#[arg(long)]
timeout: Option<u64>,
/// The app is a server: the command starts it, taking its port from PORT or `{port}`;
/// cases are requests (curl lines in its docs, `--inputs`, traps), kept in `http/`.
#[arg(long, conflicts_with = "no_http")]
http: bool,
/// Drop a saved server recording and record as a CLI again.
#[arg(long, conflicts_with_all = [
"http",
"port",
"server_args",
"pace",
"ready_timeout",
"ready",
])]
no_http: bool,
/// A port the server always listens on (implies --http); 0 removes a saved port.
#[arg(long)]
port: Option<u16>,
/// An argument every server start gets after its command, the original's and every
/// build's, so the Rust binary is started as the original is (`--arg db.json`).
/// Repeatable; implies --http; saved with the cases.
#[arg(
long = "arg",
value_name = "ARG",
allow_hyphen_values = true,
conflicts_with = "no_args"
)]
server_args: Vec<String>,
/// Clear the saved `--arg` server arguments.
#[arg(long = "no-args", alias = "no-arg", conflicts_with = "server_args")]
no_args: bool,
/// A file or folder of the repository the app reads or writes (a project tree, a
/// database file, a public folder): snapshotted into `files/` (`http/files/` for a
/// server) and copied into a fresh working directory before every case (CLIs) or start
/// (servers). A CLI's written files are what differs from it afterwards, and the files
/// it removed are compared too. Repeatable; saved with the cases.
#[arg(long, conflicts_with = "no_fresh")]
fresh: Vec<String>,
/// Clear the saved `--fresh` paths and remove the saved snapshot.
#[arg(long, conflicts_with = "fresh")]
no_fresh: bool,
/// Milliseconds to wait after each response before the next request, for work a server
/// does after answering (a file watcher reloading what it just wrote). Implies --http;
/// saved with the cases and used by replay; 0 removes it.
#[arg(long, value_name = "MS")]
pace: Option<u64>,
/// Seconds to wait for the server to accept connections before giving up (default 60).
/// Implies --http; saved with the cases and used by replay and the front door; 0 restores
/// the default.
#[arg(long, value_name = "SECS")]
ready_timeout: Option<u64>,
/// A request that says the server is ready once it answers 2xx, e.g. `GET /health`, for a
/// framework that opens its port before its routes work. Implies --http; saved with the
/// cases and used by replay and the front door.
#[arg(long, value_name = "METHOD PATH")]
ready: Option<String>,
/// Numbers in the output match when they differ by at most this times the larger
/// magnitude (absolute below 1), e.g. 1e-9 for numeric code. Saved with the cases; 0
/// removes it.
#[arg(long, allow_negative_numbers = true)]
float_tolerance: Option<f64>,
/// Allow a --float-tolerance above 1e-6, which forgives differences that are not rounding.
#[arg(long)]
allow_large_tolerance: bool,
/// A written file of raw floats, compared value by value within --float-tolerance
/// instead of byte for byte: `PATH=f32le` or `PATH=f64le`. Repeatable; saved with the
/// cases.
#[arg(long = "float-file", value_name = "PATH=FORMAT")]
float_files: Vec<String>,
/// Record what leaves the process too: `http` runs a local sink that answers every
/// request (set as HTTP_PROXY, http_proxy and RUST_ANYTHING_HTTP_SINK), `smtp` a local
/// mail server (SMTP_HOST, SMTP_PORT) recording decoded headers and MIME parts, and
/// `smtp-raw` the same server recording the raw MIME DATA. Each case stores what reached
/// them, in order, and replay compares it. Comma-separated or repeated. Saved with the cases.
#[arg(long, value_name = "KINDS")]
effects: Vec<String>,
/// Point one of the app's own settings at a sink: VAR=http-url, VAR=smtp-host,
/// VAR=smtp-port or VAR=smtp-url (e.g. WEBHOOK_URL=http-url). Implies that effect.
#[arg(long, value_name = "VAR=KIND")]
effect_env: Vec<String>,
/// Canned response for the HTTP effect sink: `METHOD /path=STATUS [BODY|@FILE]`
/// (e.g. `POST /v1/charges=201 @fixtures/charge.json` or `POST /hooks/*=500`).
/// Matched in order with `*` wildcards; unmatched requests get `200 {}`. Enables the
/// outbound HTTP effect (`--effects http`, not `--http` server mode); saved with the cases
/// so replay sees identical replies. Repeatable.
#[arg(long, value_name = "SPEC")]
effect_response: Vec<String>,
/// A shell command run before each case (CLIs) or each start (servers) that resets the
/// database to a known state. Cases then run one at a time. It runs in the folder the
/// case runs in; a script it names by a relative path with a script extension (`reset.py`,
/// `seed.sh`, `schema.sql`) is the repository's, other relative paths the case folder's.
#[arg(long, value_name = "COMMAND")]
db_reset: Option<String>,
/// A shell command that prints the database's state (e.g. `sqlite3 app.db .dump`), run
/// after each case or request in the folder the case runs in; its output is recorded
/// with the effects.
#[arg(long, value_name = "COMMAND")]
db_dump: Option<String>,
/// Run the original with no network, the repository read-only and a CPU limit and, on Linux only, a memory limit,
/// as `record --sandbox` does. On macOS loopback stays open for `--http` and the effect
/// sinks; on Linux (bubblewrap) they do not combine with it.
#[arg(long)]
sandbox: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
/// The command that runs the original, after `--`; paths are relative to the repository.
/// Taken from the saved cases when omitted.
#[arg(last = true)]
run: Vec<String>,
},
/// Run a build against `<repo>/rust/app-cases/`, print passed/total, write a report with a
/// diff per failing case; exits non-zero on any mismatch.
Replay {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Command line of the build to test (the original, the front door, the final binary);
/// the original when omitted.
#[arg(long)]
build: Option<String>,
/// Seconds before a run is killed (default: the one saved by `app record`, 30 seconds
/// unless it was changed).
#[arg(long)]
timeout: Option<u64>,
/// Servers: the port the build always listens on; otherwise it gets a free one through
/// PORT and `{port}`.
#[arg(long)]
port: Option<u16>,
/// Replay only this case, by the name the report gives it (a library: only this unit).
/// The fast, repeatable loop for fixing one mismatch.
#[arg(long)]
case: Option<String>,
/// Write the report and print mismatches as shapes only (no outputs, arguments or
/// request paths).
#[arg(long)]
redact: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Servers: put a proxy in front of the original and a build. Each request is answered by
/// the original; the build gets the same request and its answer is compared. The build's
/// outbound HTTP and mail go to local sinks and its files to a fresh copy, so no side effect
/// happens twice. Mismatches are logged to rust/app-cases/shadow/mismatches.jsonl as shapes
/// only (no values).
Shadow {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Command line of the build to compare (the front door, the final binary).
#[arg(long)]
build: String,
/// Port the proxy listens on (a free one, printed, when omitted).
#[arg(long, value_name = "PORT")]
listen: Option<u16>,
/// An original that is already running; otherwise the saved command starts it.
#[arg(long, value_name = "HOST:PORT")]
upstream: Option<String>,
/// Stop after this many requests (for tests and CI); runs until Ctrl-C otherwise.
#[arg(long, value_name = "N")]
requests: Option<usize>,
/// Seconds to wait for each answer (default: the one saved by `app record`, 30 seconds
/// unless it was changed).
#[arg(long)]
timeout: Option<u64>,
/// Append each mismatching request to rust/app-cases/shadow/inputs.jsonl in
/// `app record --inputs` format, so `app record --inputs` turns it into a case.
#[arg(long)]
keep: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Scaffold `<repo>/rust/app`, the Rust entry point for a CLI, server or library. A CLI gets
/// a clap parser for the recorded commands and flags, every command running the original
/// until a unit is wired; a server gets an axum app that starts the original and proxies
/// every route no unit answers; a library gets a crate re-exporting each wired unit's port.
/// Builds it and replays the cases (100% passed, 100% fallback).
FrontDoor {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Only write the files; skip the build and replay.
#[arg(long)]
no_check: bool,
/// Treat the repository as a library even if it has a `main`: the front door is a Rust
/// crate with the public API (found by default when there is no main and no server).
#[arg(long)]
library: bool,
/// Subcommands for the front door (skips command inference). Repeatable or comma-separated.
#[arg(long = "command", visible_alias = "commands", value_delimiter = ',')]
commands: Vec<String>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Hand commands to a unit's `port.rs` (after it passes gate): adds the crate to `rust/app`,
/// a glue file to write once, the routing and a kill switch
/// (`RUST_ANYTHING_UNIT_<NAME>=original`), then builds and replays.
Wire {
/// Repository root.
repo: PathBuf,
/// Unit crate: its folder, its name under `rust/`, or the unit id it was bridged from.
unit: String,
/// A command the unit answers. Repeatable; kept from the last wire when omitted.
#[arg(long = "command")]
commands: Vec<String>,
/// Servers: a route the unit answers, axum syntax (`GET /users/{id}`, `/path` for any
/// method, `*` for everything else). Repeatable; kept from the last wire when omitted.
#[arg(long = "route")]
routes: Vec<String>,
/// Do not run gate on the unit first (it just passed).
#[arg(long)]
skip_gate: bool,
/// Only write the files; skip the build and replay.
#[arg(long)]
no_check: bool,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Make `rust/app` a pure Rust app, once replay passes with fallback rate 0 and every unit
/// passes gate: removes the fallback and the kill switches, turns the units into plain
/// libraries, runs the lift checklist and replays the pure binary. Checked on a copy first;
/// the original stays in place. It also refuses while something the original offers is
/// undecided: an obligation no recorded case exercises that nobody waived, a family that is
/// not complete and that nobody attested (or whose attestation no longer matches), an
/// expected output file with a `...` line that matches any number of lines, or invalid
/// obligations files. Each line names the command that unblocks it
/// (`rust-anything obligations waive`, `rust-anything obligations attest`), and
/// `rust-anything obligations <repo> --check` lists them all.
Lift {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
/// Check that the recording still describes the original and the port still matches:
/// replays the original against rust/app-cases (cases it no longer matches changed upstream),
/// lists examples in its docs that no case records, and replays the build. Writes
/// rust/app-cases/drift-report.md; exits 1 on any change. For CI after a lift.
Drift {
/// Repository root.
#[arg(default_value = ".")]
repo: PathBuf,
/// Build to check; defaults to rust/app, built with cargo, when it exists.
#[arg(long)]
build: Option<String>,
/// Seconds before a run is killed (default: the one saved by `app record`, 30 seconds
/// unless it was changed).
#[arg(long)]
timeout: Option<u64>,
/// Print the machine-readable report as JSON.
#[arg(long)]
json: bool,
},
}
/// `3 distinct differences in 41 cases:` and a line per difference, most cases first.
/// `cases` is the number of distinct failing cases: one case can differ in two ways, so it
/// cannot be summed from the groups.
fn group_lines(groups: &[rust_anything::mismatch::Group], cases: usize) -> Vec<String> {
if groups.is_empty() {
return Vec::new();
}
let mut lines = vec![format!(
"{} in {}:",
counted(groups.len(), "distinct difference"),
counted(cases, "case")
)];
for g in groups {
lines.push(format!(" {:>4} {} {}", g.cases, g.id, g.label()));
}
lines
}
fn say_groups(groups: &[rust_anything::mismatch::Group], cases: usize) {
for line in group_lines(groups, cases) {
say!("{line}");
}
}
fn diff_group_lines(d: &harness::DiffOutcome) -> Vec<String> {
group_lines(&d.groups, d.failed)
}
fn say_replay(replay: &app::ReplayOutcome) {
say!("{}/{} cases passed", replay.passed, replay.total);
if let Some(f) = &replay.fallback {
say!(
"Fallback rate: {:.1}% ({}/{})",
f.rate * 100.0,
f.cases,
f.total
);
}
say_groups(&replay.groups, replay.failures.len());
for f in replay.failures.iter().take(20) {
let fields: Vec<String> = f
.problems
.iter()
.map(|p| {
p.at.as_ref()
.map_or_else(|| p.field.clone(), |at| at.label())
})
.collect();
say!("- {}: {}", f.case, fields.join(", "));
}
if replay.failures.len() > 20 {
say!("- ... and {} more", replay.failures.len() - 20);
}
say!("Report: {}", replay.report.display());
}
/// Summary lines printed below the `bench` table.
fn bench_summary_lines(
rows: &[harness::BenchRow],
v: &harness::Verdict,
crate_dir: &std::path::Path,
) -> Vec<String> {
let compared = rows.len().saturating_sub(v.left_out.len());
let mut lines = vec![String::new()];
if compared > 0 {
lines.push(format!(
"Timed as callers call it, crossing included. Overall {} (geometric mean); {} of {} {} at least 1.1x faster.",
harness::speed_phrase(v.speedup),
v.faster.len(),
compared,
if compared == 1 { "function" } else { "functions" }
));
}
if !v.left_out.is_empty() {
lines.push(format!(
"Left out of the overall: {} (their recorded cases do not all match, so their time is the cost of failing, not of the work; run `rust-anything diff {}`).",
v.left_out.join(", "),
rust_anything::app::cli_path(crate_dir)
));
}
lines.push(v.advice.clone());
lines
}
/// `n` and `word`, with an `s` unless `n` is one.
fn counted(n: usize, word: &str) -> String {
if n == 1 {
format!("1 {word}")
} else {
format!("{n} {word}s")
}
}
/// `fuzz`'s mismatch lines, ending with `- ... and N more` when it failed more cases than it kept,
/// as `app replay` does.
fn fuzz_mismatch_lines(f: &rust_anything::fuzz::FuzzOutcome) -> Vec<String> {
let mut lines: Vec<String> = f
.mismatches
.iter()
.map(|m| {
format!(
"- {}({}): expected {}, got {}",
m["fn"].as_str().unwrap_or_default(),
m["args"]
.as_array()
.map(|a| a
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "))
.unwrap_or_default(),
m["expected"],
m["actual"]
)
})
.collect();
if f.failed > f.mismatches.len() {
lines.push(format!("- ... and {} more", f.failed - f.mismatches.len()));
}
lines
}
/// What `app record` prints when it finishes: every count singular for one, so a one-trap
/// recording does not say "1 traps".
#[allow(clippy::too_many_arguments)]
fn recorded_summary(
cases: usize,
dir: &std::path::Path,
examples: usize,
inputs: usize,
duplicates: usize,
no_args: usize,
traps: usize,
dropped: Option<usize>,
) -> String {
let mut parts = format!("{examples} from examples, {inputs} from inputs");
if duplicates > 0 {
parts.push_str(&format!(
", {} skipped",
counted(duplicates, "duplicate input")
));
}
if no_args > 0 {
parts.push_str(&format!(", {} with no arguments", counted(no_args, "run")));
}
let head = format!(
"Recorded {} in {} ({parts}, {}",
counted(cases, "case"),
dir.display(),
counted(traps, "trap")
);
match dropped {
Some(n) => format!("{head}, {} dropped)", counted(n, "trap")),
None => format!("{head})"),
}
}
/// The stack `run` gets: Linux's main-thread default. Windows gives the main thread 1 MB, which
/// an unoptimized `run` overflows before it parses the arguments.
const STACK_SIZE: usize = 8 << 20;
/// Under `--json` a failure is JSON on stdout too, so a tool reading the output never has to
/// parse a sentence from stderr.
fn wants_json() -> bool {
std::env::args()
.skip(1)
.take_while(|a| a != "--")
.any(|a| a == "--json" || a == "--json-events")
}
fn error_code(e: &anyhow::Error) -> &'static str {
let text = format!("{e:#}");
if text.contains("recorded cases match; switch it on once they all do") {
"cases_mismatch"
} else if text.contains("run `rust-anything bridge` first") {
"not_bridged"
} else if text.contains("run `rust-anything record` first") {
"not_recorded"
} else if text.starts_with("no folder") || text.contains("No such file or directory") {
"not_found"
} else {
"failed"
}
}
fn version_json() -> String {
let schemas: serde_json::Map<String, serde_json::Value> = rust_anything::state::SCHEMAS
.iter()
.map(|c| ((*c).to_string(), rust_anything::state::schema(c).into()))
.collect();
serde_json::json!({
"name": "rust-anything",
"version": env!("CARGO_PKG_VERSION"),
"schemas": schemas,
})
.to_string()
}
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() == 2
&& args.contains(&"--version".to_string())
&& args.contains(&"--json".to_string())
{
println!("{}", version_json());
return ExitCode::SUCCESS;
}
let worker = std::thread::Builder::new()
.name("main".into())
.stack_size(STACK_SIZE)
.spawn(run)
.expect("starting the main thread");
match worker.join() {
Ok(Ok(code)) => code,
Ok(Err(e)) => {
if wants_json() {
println!(
"{}",
serde_json::json!({
"schema": rust_anything::state::schema("error"),
"error": { "code": error_code(&e), "message": format!("{e:#}") },
})
);
}
eprintln!("error: {e:#}");
ExitCode::from(2)
}
Err(panic) => std::panic::resume_unwind(panic),
}
}
fn run() -> Result<ExitCode> {
// Parse with `try_parse()` so a usage error under `--json` can be reported
// as error JSON on stdout, like every other failure (#1351). `Cli::parse()`
// exits the process before `main()` gets a chance to do that.
let command = match Cli::try_parse() {
Ok(cli) => cli.command,
Err(e) => {
use clap::error::ErrorKind::{DisplayHelp, DisplayVersion, MissingRequiredArgument};
match e.kind() {
// Not errors: print exactly what `Cli::parse()` prints today.
DisplayHelp | DisplayVersion => {
let _ = e.print();
return Ok(ExitCode::SUCCESS);
}
_ => {
if wants_json() {
let rendered = e.to_string();
let first_line = rendered.lines().next().unwrap_or_default();
let lead = first_line.strip_prefix("error: ").unwrap_or(first_line);
let message = if matches!(e.kind(), MissingRequiredArgument) {
let names: Vec<&str> = rendered
.lines()
.skip(1)
.map(str::trim)
.take_while(|line| !line.is_empty() && !line.starts_with("Usage:"))
.collect();
if names.is_empty() {
lead.to_string()
} else {
format!("{lead} {}", names.join(", "))
}
} else {
lead.to_string()
};
println!(
"{}",
serde_json::json!({
"schema": rust_anything::state::schema("error"),
"error": { "code": "usage", "message": message },
})
);
}
let _ = e.print();
return Ok(ExitCode::from(2));
}
}
}
};
match command {
Cmd::Analyze {
root,
json,
out,
lang,
whole_app,
} => {
// Said here, not under "analyzing X", so the path is named once (#267).
if !root
.try_exists()
.with_context(|| format!("reading {}", root.display()))?
{
anyhow::bail!("no folder {}", root.display());
}
let mut report = analyze::analyze_opts(&root, lang)
.with_context(|| format!("analyzing {}", root.display()))?;
if whole_app {
report.whole_app = Some(rust_anything::whole_app::whole_app(&root, &report));
}
let text = if json {
serde_json::to_string_pretty(&report)? + "\n"
} else {
let title = root
.canonical()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
.unwrap_or_else(|| root.display().to_string());
report::markdown(&report, &title)
};
match out {
Some(path) => std::fs::write(&path, text)
.with_context(|| format!("writing {}", path.display()))?,
None => say_raw!("{text}"),
}
}
Cmd::Bridge {
root,
unit,
kind,
out,
name,
force,
keep,
batch,
as_json,
allocator,
end_state,
} => {
let outcome = bridge::bridge(&bridge::Options {
root: &root,
unit: &unit,
kind: kind.map(|k| match k {
KindArg::Napi => bridge::Kind::Napi,
KindArg::Wasm => bridge::Kind::Wasm,
}),
out,
name,
force,
keep,
lang: None,
batch,
as_json,
allocator,
})?;
if let Some(end_state) = end_state {
bridge::set_end_state(&outcome.crate_dir, end_state)?;
}
say!(
"Created {} ({}) for {}",
outcome.crate_dir.display(),
outcome.kind.label(),
outcome.exports.join(", ")
);
for file in &outcome.files {
say!(" {file}");
}
for note in &outcome.notes {
say!("- {note}");
}
}
Cmd::Record {
crate_dir,
count,
inputs,
module,
resolve_from,
node_args,
float_tolerance,
allow_large_tolerance,
ignore_key_order,
no_ignore_key_order,
messages,
no_messages,
from_tests,
test_command,
profile,
device,
pin_clock,
no_pin_clock,
sandbox,
allow_dropped,
} => {
anyhow::ensure!(
profile != Profile::Host || device.is_none(),
"`--device` needs `--profile android`"
);
anyhow::ensure!(
!sandbox || !from_tests,
rust_anything::from_tests::NOT_SANDBOXED
);
anyhow::ensure!(
from_tests || test_command.is_empty(),
"a command after `--` is the test suite for `--from-tests`; add the flag"
);
anyhow::ensure!(
count > 0 || inputs.is_some() || from_tests,
"`--count 0` records nothing: pass --count 1 or more, or give cases with --inputs or \
--from-tests"
);
let float_tolerance = float_tolerance
.map(|t| rust_anything::tolerance::check_bounded(t, allow_large_tolerance))
.transpose()?;
let mut _run_inputs = rust_anything::from_tests::RunInputsGuard::new(&crate_dir);
let mut captured_inputs = None;
let inputs = if from_tests {
let c = rust_anything::from_tests::capture(&crate_dir, &test_command)?;
_run_inputs.track(&c.inputs);
let total_calls = c.per_function.values().sum::<usize>();
let call_noun = if total_calls == 1 { "call" } else { "calls" };
say!(
"Captured {} {call_noun} from the tests{}:",
total_calls,
if c.tests_passed {
""
} else {
" (the test command failed; calls made before that are kept)"
}
);
for (name, n) in &c.per_function {
say!(" {name}: {n}");
}
for s in &c.skipped {
say!(" not captured: {s}");
}
if let Some(notice) = c.capped_notice() {
say!(" {notice}");
}
let combined = rust_anything::from_tests::with_own_inputs(
&crate_dir,
inputs.as_deref(),
&c.inputs,
)?;
_run_inputs.track(&combined);
captured_inputs = Some(c.inputs);
Some(combined)
} else {
inputs
};
let _lock = rust_anything::fuzz::RecordingLock::take_recovered(&crate_dir)?;
if let Some(captured) = &captured_inputs {
rust_anything::from_tests::publish_test_inputs(&crate_dir, captured)?;
}
let settings = rust_anything::recording::Settings::save(&crate_dir)?;
let recorded = (|| {
if let Some(t) = float_tolerance {
let mut manifest = bridge::Manifest::load(&crate_dir)?;
manifest.float_tolerance = (t > 0.0).then_some(t);
manifest.save(&crate_dir)?;
}
if ignore_key_order || no_ignore_key_order {
let mut manifest = bridge::Manifest::load(&crate_dir)?;
manifest.ignore_key_order = ignore_key_order;
manifest.save(&crate_dir)?;
}
if messages || no_messages {
let mut manifest = bridge::Manifest::load(&crate_dir)?;
manifest.messages = messages;
manifest.save(&crate_dir)?;
}
if (pin_clock || no_pin_clock)
&& let Some(helper) = rust_anything::pin::set(&crate_dir, pin_clock)?
{
say!(
"Wrote {}: add `mod pinned;` to port.rs and call `pinned::now_ms()` and \
`pinned::random()` where the original reads the clock or draws a number",
helper.display()
);
}
let opts = harness::RecordOptions {
crate_dir: &crate_dir,
count,
inputs: inputs.as_deref(),
module: module.as_deref(),
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
sandbox,
};
match profile {
Profile::Host => {
harness::record_allowing_dropped(&opts, allow_dropped.unwrap_or(0))
}
Profile::Android => harness::record_android(&opts, device.as_deref()),
}
})();
let outcome = match recorded {
Ok(outcome) => outcome,
Err(error) => {
return Err(settings.put_back_after(error));
}
};
say!(
"Recorded {} ({} threw) in {}",
counted(outcome.cases, "case"),
outcome.errors,
outcome.path.display()
);
for (name, n) in &outcome.per_function {
say!(" {name}: {n}");
}
if let Some(warning) = outcome.mostly_threw() {
say!("Warning: {warning}.");
}
if let Some(pin) = &outcome.pinned {
say!(
"Clock pinned at {} ms (UTC), random numbers from seed {} ({})",
pin.now_ms,
pin.seed,
rust_anything::pin::FILE
);
}
if outcome.nested > 0 {
say!(
"{} change values inside string arguments that hold JSON or base64 JSON \
(dates in other shapes, numbers, strings)",
counted(outcome.nested, "case")
);
}
if !outcome.regex_functions.is_empty() {
say!(
"Regex traps (non-ASCII \\w, \\b and case folding) added for: {}",
outcome.regex_functions.join(", ")
);
}
if !outcome.timed_out.is_empty() {
let noun = if outcome.timed_out.len() == 1 {
"input"
} else {
"inputs"
};
say!(
"Left out {} {noun} the original ran too long on (over the per-case limit, \
RUST_ANYTHING_CASE_TIMEOUT seconds, 10 by default). The original does this \
itself, so the port need not match it there:",
outcome.timed_out.len()
);
for c in &outcome.timed_out {
say!(" {}({})", c["fn"].as_str().unwrap_or("?"), c["args"]);
}
}
if !outcome.dropped.is_empty() {
say!(
"Left out {} of {} generated inputs the original could not be recorded on \
(allowed with --allow-dropped; `gate` needs --accept-dropped {}):",
outcome.dropped.len(),
outcome.generated,
outcome.dropped.len()
);
for d in &outcome.dropped {
say!(" {}: {} (input {})", d.function, d.kind, d.input);
}
}
if outcome.inapplicable > 0 {
say!(
"{} generated input{} did not fit the original's parameter types and {} not recorded; the original cannot be called with {}.",
outcome.inapplicable,
if outcome.inapplicable == 1 { "" } else { "s" },
if outcome.inapplicable == 1 {
"was"
} else {
"were"
},
if outcome.inapplicable == 1 {
"it"
} else {
"them"
},
);
}
if let Some(line) = outcome
.coverage
.as_ref()
.and_then(rust_anything::recording::coverage_line)
{
say!("Coverage: {line}");
}
if !outcome.decoded.is_empty() {
say!(
"Decoded inside: {}: {}",
outcome.decoded.join(", "),
rust_anything::ts::scan::DECODED_INPUT_ADVICE
);
}
}
Cmd::Refresh { crate_dir, batch } => {
let r = if batch.is_empty() {
bridge::refresh(&crate_dir)?
} else {
bridge::add_batches(&crate_dir, &batch)?
};
say!(
"Regenerated {} for {}",
r.files.join(", "),
r.functions.join(", ")
);
if !r.not_exports.is_empty() {
let unit = bridge::Manifest::load(&crate_dir)?.unit;
for name in &r.not_exports {
say!(
"`{name}` is not an export of `{unit}` and is now part of the bridged API; \
make it private (`fn`) if it is a helper"
);
}
}
}
Cmd::Build {
crate_dir,
profile,
abi,
api,
ndk,
jni_libs,
} => match profile {
Profile::Host => {
if !abi.is_empty() || api.is_some() || jni_libs.is_some() || ndk.is_some() {
anyhow::bail!(
"`--abi`, `--api`, `--ndk` and `--jni-libs` need `--profile android`"
);
}
say!("Built {}", harness::build(&crate_dir)?.display());
}
Profile::Android => {
let report = harness::build_android(
&crate_dir,
&rust_anything::android::Options {
abis: abi,
api: api.unwrap_or(rust_anything::android::DEFAULT_API),
ndk,
out: jni_libs,
},
)?;
for library in &report.libraries {
say!(
"Built {} ({} JNI entry points checked, API {})",
library.path.display(),
library.entry_points,
report.api
);
}
}
},
Cmd::Diff {
crate_dir,
profile,
device,
jni_libs,
module,
ignore_key_order,
float_tolerance,
allow_large_tolerance,
redact,
json,
node_args,
} => {
// A bad tolerance is refused before anything is read or run, as
// `record` and `app record` do.
if let Some(t) = float_tolerance {
rust_anything::tolerance::check_bounded(t, allow_large_tolerance)?;
}
// Before the harness, which would otherwise say "run record first" for a crate that is not there.
rust_anything::bridge::Manifest::load(&crate_dir)?;
let opts = harness::DiffOptions {
crate_dir: &crate_dir,
module: module.as_deref(),
ignore_key_order,
node_args: &node_args,
float_tolerance,
};
let mut d = match profile {
Profile::Host => {
if device.is_some() || jni_libs.is_some() {
anyhow::bail!("`--device` and `--jni-libs` need `--profile android`");
}
harness::diff(&opts)?
}
Profile::Android => {
harness::diff_android(&opts, device.as_deref(), jni_libs.as_deref())?
}
};
if redact {
rust_anything::mismatch::redact_diff(&mut d);
}
// The same recording checks as `gate`: a recording whose fingerprint file is gone,
// whose original changed, or whose lines were edited says nothing about the port.
let verified = match rust_anything::bridge::Manifest::load(&crate_dir) {
Ok(m) => rust_anything::recording::verify(
&crate_dir,
&m,
rust_anything::recording::VerifyOptions::default(),
),
// A manifest that cannot be read leaves nothing to check the recording against:
// that is a failure, not a pass.
Err(e) => {
let mut v = rust_anything::recording::Verification::default();
v.problems.push(format!(
"{} could not be read, so the recording cannot be verified: {e:#}",
rust_anything::bridge::MANIFEST
));
v
}
};
let mut loosening = rust_anything::recording::Loosening::read(&crate_dir);
if let Some(t) = float_tolerance {
loosening.float_tolerance = (t > 0.0).then_some(t);
}
loosening.ignore_key_order |= ignore_key_order;
if json {
let mut report = serde_json::to_value(&d)?;
report["comparison"] = serde_json::to_value(&loosening)?;
report["recording"] = serde_json::to_value(&verified)?;
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say!("{}", loosening.line());
if let Some(line) = loosening.messages_line() {
say!("{line}");
}
for note in &d.notes {
say!("Note: {note}");
}
for why in &verified.problems {
say!("Recording problem: {why}");
}
for note in &verified.notes {
say!("Note: {note}");
}
if d.accepted > 0 {
say!(
"{}/{} cases match exactly, {} more accepted as known differences ({})",
d.passed - d.accepted.min(d.passed),
d.total,
d.accepted,
rust_anything::recording::KNOWN_DIFFS
);
} else {
say!("{}/{} cases match", d.passed, d.total);
}
for b in &d.batches {
say!("{}", rust_anything::batch_check::diff_line(b));
for m in &b.mismatches {
say!(" {}", rust_anything::batch_check::mismatch_line(m));
}
}
if let Some(t) = d.trend.as_ref().filter(|t| t.stalled) {
let shown: Vec<String> = t.passed.iter().map(ToString::to_string).collect();
say!(
"Stalled: the last {} changes to port.rs gained no matching case ({} of {}). \
Stop and look at the remaining mismatches with a person, or keep these \
functions in the original for now.",
rust_anything::recording::STALL_AFTER,
shown.join(", "),
t.total
);
}
for e in &d.stale_known {
say!(
"Known diff no longer happens, remove it from {}: {}",
rust_anything::recording::KNOWN_DIFFS,
rust_anything::recording::entry_label(e)
);
}
if !d.missing.is_empty() {
say!("Missing exports: {}", d.missing.join(", "));
}
for line in diff_group_lines(&d) {
say!("{line}");
}
for m in &d.mismatches {
if m.get("case").is_some() {
say!(
"- {} (case {})",
m["fn"].as_str().unwrap_or_default(),
m["case"].as_str().unwrap_or_default()
);
} else {
say!(
"- {}({}): expected {}, got {}",
m["fn"].as_str().unwrap_or_default(),
m["args"]
.as_array()
.map(|a| a
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "))
.unwrap_or_default(),
m["expected"],
m["actual"]
);
}
if let Ok(at) =
serde_json::from_value::<rust_anything::mismatch::At>(m["at"].clone())
{
say!(" {}", at.describe());
}
}
}
if d.failed > 0 || d.batches.iter().any(|b| !b.ok()) || !verified.ok() {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Fuzz {
crate_dir,
cases,
seed,
time,
keep,
resolve_from,
sandbox,
generator,
json,
node_args,
} => {
// `--time 0` means "one round", so zero is a valid value here: the helper rejects it,
// and a value `Duration` cannot hold is an error rather than a panic.
let time = time
.map(|t| {
anyhow::ensure!(
t.is_finite() && t >= 0.0,
"`--time` must be 0 or more seconds (0 runs one round), not {t}"
);
if t == 0.0 {
return Ok(std::time::Duration::ZERO);
}
rust_anything::process::seconds(t).context("`--time` is too large")
})
.transpose()?;
let f = rust_anything::fuzz::fuzz(&rust_anything::fuzz::FuzzOptions {
crate_dir: &crate_dir,
cases,
seed,
time,
keep,
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
sandbox,
generator: generator.as_deref(),
})?;
if json {
say!("{}", serde_json::to_string_pretty(&f)?);
} else {
say!("Seed {} (replay with --seed {})", f.seed, f.seed);
let rounds = format!("{} round{}", f.rounds, if f.rounds == 1 { "" } else { "s" });
if f.cases == 0 {
// "0/0 fresh cases match" reads as a pass, and nothing was tested.
say!(
"No fresh cases ({rounds}): every case it generated is already in the \
recording. Try a larger --cases or another --seed."
);
} else {
say!("{}/{} fresh cases match ({rounds})", f.passed, f.cases);
}
if !f.missing.is_empty() {
say!("Missing exports: {}", f.missing.join(", "));
}
for line in fuzz_mismatch_lines(&f) {
say!("{line}");
}
if f.kept > 0 {
let case_noun = if f.kept == 1 { "case" } else { "cases" };
say!(
"Kept {} {case_noun} in {}: the next diff and gate check them",
f.kept,
f.recording.display()
);
}
}
if f.failed > 0 {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Bench {
crate_dir,
min_ms,
resolve_from,
json,
node_args,
} => {
let rows = harness::bench(&harness::BenchOptions {
crate_dir: &crate_dir,
min_ms,
resolve_from: resolve_from.as_deref(),
node_args: &node_args,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&rows)?);
} else {
say!(
"{:<24} {:>6} {:>12} {:>12} {:>12}",
"function",
"cases",
"orig ns/call",
"Rust ns/call",
"speedup"
);
for r in &rows {
let mark = if r.failing {
" cases do not match"
} else {
""
};
say!(
"{:<24} {:>6} {:>12.0} {:>12.0} {:>12}{mark}",
r.name,
r.cases,
r.original_ns,
r.rust_ns,
harness::speed_phrase(r.speedup)
);
}
let lang = bridge::Manifest::load(&crate_dir)
.map(|m| m.language)
.unwrap_or_default();
let v = harness::verdict(&rows, lang, &crate_dir);
for line in bench_summary_lines(&rows, &v, &crate_dir) {
say!("{line}");
}
}
}
Cmd::Profile {
root,
json,
lang,
command,
} => {
let report = rust_anything::profile::profile(&root, &command, lang)?;
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say!("{}", rust_anything::profile::markdown(&report));
}
}
Cmd::Go {
path,
root,
agent,
function,
lang,
count,
rounds,
min_cases,
json,
command,
} => {
let root = path.or(root).unwrap_or_else(|| PathBuf::from("."));
let outcome = rust_anything::go::go(&rust_anything::go::Options {
root: &root,
command: &command,
lang,
agent: agent.as_deref().filter(|a| !a.trim().is_empty()),
function: function.as_deref(),
count,
rounds,
min_cases,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for problem in &outcome.failed_checks {
say!("{problem}\n");
}
say!("{}", outcome.next);
}
use rust_anything::go::Stage;
return Ok(match outcome.stage {
Stage::On | Stage::Passed | Stage::WaitingForPort => ExitCode::SUCCESS,
Stage::Mismatch | Stage::GateFailed | Stage::Slower | Stage::Thin => {
ExitCode::FAILURE
}
});
}
Cmd::Enable {
crate_dir,
only,
partial,
force,
json,
} => {
// An unsupported crate gets switching advice before any build or diff.
let manifest = bridge::Manifest::load(&crate_dir)?;
rust_anything::enable::supported_in(&crate_dir, &manifest)?;
let _lock = rust_anything::fuzz::RecordingLock::take_recovered(&crate_dir)?;
let manifest = bridge::Manifest::load(&crate_dir)?;
// The recording and the cheat guard first, as `gate` reads them: a switch-on must not
// be easier to get than a passing gate.
let mut notes = rust_anything::enable::guard(
&crate_dir,
&manifest,
force,
!partial && only.is_empty(),
)?;
let diff_opts = harness::DiffOptions {
crate_dir: &crate_dir,
module: None,
ignore_key_order: false,
node_args: &[],
float_tolerance: None,
};
let mut on = if partial || (!only.is_empty() && !force) {
harness::build(&crate_dir)?;
let (d, counts) = harness::diff_full_with_counts(&diff_opts)?;
rust_anything::enable::guard_cases(
&crate_dir, d.accepted, d.total, force, &mut notes,
)?;
let manifest = bridge::Manifest::load(&crate_dir)?;
let (selected, skipped) =
rust_anything::enable::select_matching(&manifest, &d, &counts, &only)?;
rust_anything::enable::enable_only(&crate_dir, Some(&selected), &skipped)?
} else if !only.is_empty() {
notes.push("forced: the recorded cases were not diffed first".into());
rust_anything::enable::enable_only(&crate_dir, Some(&only), &[])?
} else {
if force {
notes.push("forced: the recorded cases were not diffed first".into());
} else {
harness::build(&crate_dir)?;
let d = harness::diff(&diff_opts)?;
if d.failed > 0 || d.batches.iter().any(|b| !b.ok()) || !d.missing.is_empty() {
anyhow::bail!(
"{}/{} recorded cases match{}; switch it on once they all do (`rust-anything diff {}` shows them), or pass --partial / --only / --force",
d.passed,
d.total,
rust_anything::batch_check::failure_summary_suffix(&d.batches),
rust_anything::app::cli_path(&crate_dir)
);
}
rust_anything::enable::guard_cases(
&crate_dir, d.accepted, d.total, force, &mut notes,
)?;
}
rust_anything::enable::enable(&crate_dir)?
};
on.notes = notes;
let selection = if partial {
Some("partial")
} else if only.is_empty() {
None
} else {
Some("only")
};
rust_anything::audit::switched(&crate_dir, "enable", &on, selection, force, &on.notes);
if json {
say!("{}", serde_json::to_string_pretty(&on)?);
} else {
say!(
"{}",
rust_anything::recording::Loosening::read(&crate_dir).line()
);
for note in &on.notes {
say!("note: {note}");
}
if on.files.is_empty() {
// As `disable` says for a unit that was not on: nothing was written.
say!("{} was already on; nothing changed", on.crate_name);
} else {
say!(
"On: {} {} in Rust",
on.functions.join(", "),
if on.functions.len() == 1 {
"runs"
} else {
"run"
}
);
}
for f in &on.files {
say!(" {}", f.display());
}
for s in &on.skipped {
say!("- {s}");
}
say!(
"{}=original (or RUST_ANYTHING_MODE=old) runs the original for one run; `rust-anything disable {}` removes the block.",
on.switch,
rust_anything::app::cli_path(&crate_dir)
);
}
}
Cmd::Disable { crate_dir, json } => {
let off = rust_anything::enable::disable(&crate_dir)?;
rust_anything::audit::switched(&crate_dir, "disable", &off, None, false, &[]);
if json {
say!("{}", serde_json::to_string_pretty(&off)?);
} else if off.files.is_empty() {
say!("{} was not on; nothing changed", off.crate_name);
} else {
say!(
"Off: {} {} in the original again",
off.functions.join(", "),
if off.functions.len() == 1 {
"runs"
} else {
"run"
}
);
for f in &off.files {
say!(" {}", f.display());
}
}
}
Cmd::Report {
crate_dir,
out,
min_ms,
json,
node_args,
resolve_from,
} => {
let card = rust_anything::card::report(&rust_anything::card::Options {
crate_dir: &crate_dir,
out: out.as_deref(),
min_ms,
node_args: &node_args,
resolve_from: resolve_from.as_deref(),
})?;
if json {
say!("{}", serde_json::to_string_pretty(&card)?);
} else {
say_raw!("{}", rust_anything::card::markdown(&card));
say!(
"\nWrote {} and {}",
card.markdown.display(),
card.svg.display()
);
}
}
Cmd::Clean {
dry_run,
force,
json,
} => {
let c = rust_anything::cache::clean(dry_run, force)?;
if json {
say!("{}", serde_json::to_string_pretty(&c)?);
} else if !c.exists {
say!("nothing to remove: {} does not exist", c.dir.display());
} else if c.removed {
say!(
"Removed {} ({})",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
} else if c.from_env && !force {
say!(
"{} ({}) is CARGO_TARGET_DIR, which other cargo projects may share; pass --force to remove it",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
} else if dry_run {
say!(
"would remove {} ({})",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
} else {
say!(
"{} ({})",
c.dir.display(),
rust_anything::cache::human(c.bytes)
);
}
}
Cmd::Shadow { crate_dir, out } => {
let outcome = shadow::shadow(&crate_dir, out.as_deref())?;
say!(
"Wrote {} ({})",
outcome.path.display(),
outcome.exports.join(", ")
);
if outcome.path.extension().is_some_and(|e| e == "java") {
say!(
"Call the <Class>Shadow classes in place of the originals; compile them with the originals and java/rust-anything. -Drust-anything.mode=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "rb") {
say!(
"Require it after the original files. RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "go") {
say!(
"Import it in place of the original package (require and replace both modules in go.mod). RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
} else if outcome.path.extension().is_some_and(|e| e == "c") {
say!(
"Compile the original with the -D flags in shadow/flags.txt, build the crate with --features shadow, and link all three."
);
} else {
say!(
"Import it in place of the original. RUST_ANYTHING_MODE=old|shadow|new switches at runtime."
);
}
}
Cmd::Package {
crate_dir,
name,
version,
out,
fallback,
bin,
original,
dry_run,
json,
} => {
let outcome = rust_anything::package::package(&rust_anything::package::Options {
crate_dir: &crate_dir,
name,
version,
out,
dry_run,
fallback,
bin,
original,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"{} {} file{} for {}@{} in {}:",
if outcome.dry_run {
"Would write"
} else {
"Wrote"
},
outcome.files.len(),
if outcome.files.len() == 1 { "" } else { "s" },
outcome.name,
outcome.version,
outcome.out.display()
);
for file in &outcome.files {
say!(" {file}");
}
for note in &outcome.notes {
say!("{note}");
}
}
}
Cmd::Gate {
crate_dir,
json,
json_events,
held_out_cases,
held_out_seed,
node_args,
accept_known_diffs,
accept_smaller_recording,
accept_dropped,
} => {
gate::set_events(json_events);
let outcome = gate::gate_with(
&crate_dir,
&node_args,
&gate::GateOptions {
accept_known_diffs,
accept_smaller_recording,
accept_dropped,
held_out_cases,
held_out_seed,
},
)?;
if json_events {
let mut line = serde_json::to_value(&outcome)?;
line["event"] = "result".into();
say!("{line}");
} else if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say_raw!("{}", gate::text(&outcome));
}
if !outcome.passed {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Selftest {
lang,
keep,
strict,
only,
json,
} => {
let progress = |line: &str| eprintln!("selftest: {line}");
let report = rust_anything::selftest::selftest(&rust_anything::selftest::Options {
langs: &lang,
keep,
strict,
only: &only,
progress: Some(&progress),
})?;
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say_raw!("{}", rust_anything::selftest::text(&report));
}
if !report.passed {
return Ok(ExitCode::FAILURE);
}
}
Cmd::App { command } => return run_app(*command),
Cmd::Mcp => mcp::serve()?,
Cmd::Setup {
agents,
remove,
dry_run,
no_backup,
json,
} => {
let home = rust_anything::setup::home()?;
let command = std::env::current_exe()
.and_then(|p| p.canonical())
.context("finding the rust-anything executable")?;
let report = rust_anything::setup::setup(&rust_anything::setup::Options {
home: &home,
agents,
command,
remove,
dry_run,
backup: !no_backup,
})?;
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
} else {
print!("{}", rust_anything::setup::text(&report));
}
}
Cmd::Map {
repo,
crates,
write,
check,
json,
} => {
let map = rust_anything::port_map::map(&repo, &crates)?;
if json {
say!("{}", serde_json::to_string_pretty(&map)?);
} else if write {
let path = map.root.join(rust_anything::port_map::MAP_FILE);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(
&path,
rust_anything::port_map::markdown_with(&map, &repo, true),
)?;
say!("Wrote {}", path.display());
} else {
say_raw!(
"{}",
rust_anything::port_map::markdown_with(&map, &repo, false)
);
}
if check && (map.changed() > 0 || map.untrusted() > 0) {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Log { repo, json } => {
let log = rust_anything::audit::read(&repo)?;
if json {
say!("{}", serde_json::to_string_pretty(&log)?);
} else {
say_raw!("{}", rust_anything::audit::text(&log));
}
}
Cmd::Obligations {
action: Some(action),
..
} => match action {
ObligationsCmd::Waive {
items,
reason,
repo,
} => {
let done = rust_anything::obligations::standing::waive(&repo, &items, &reason)?;
say!(
"Waived {} under {}, written in {} and {}:",
done.items.len(),
done.adr,
rust_anything::obligations::standing::ADR_FILE,
rust_anything::obligations::standing::DECISIONS_FILE
);
for id in &done.items {
say!(" {id}");
}
}
ObligationsCmd::Attest {
families,
reason,
repo,
} => {
let done = rust_anything::obligations::standing::attest(&repo, &families, &reason)?;
let names: Vec<&str> = done.families.iter().map(|f| f.label()).collect();
say!(
"Attested {} under {}, written in {} and {}.",
names.join(", "),
done.adr,
rust_anything::obligations::standing::ADR_FILE,
rust_anything::obligations::standing::DECISIONS_FILE
);
}
ObligationsCmd::Fallbacks {
journals,
repo,
write,
inputs,
json,
} => {
let report = rust_anything::obligations::standing::run_fallbacks(
&rust_anything::obligations::standing::FallbacksOptions {
repo: &repo,
journals: &journals,
write,
inputs: inputs.as_deref(),
},
)?;
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say_raw!(
"{}",
rust_anything::obligations::standing::fallbacks_text(&report)
);
}
}
},
Cmd::Obligations {
action: None,
repo,
check: true,
json,
lang,
..
} => {
if let Some(lang) = lang {
let root = rust_anything::walk::resolve_root(&repo)?;
let declared = rust_anything::obligations::source::read(&root)?;
if declared.lang != Some(lang) {
anyhow::bail!(
"`--check` reads the language from {file}, as `app lift` does: write \
`lang = \"{name}\"` there (and `entry = [\"path/to/script\"]` for an \
executable that is ignored or has no extension), then run \
`rust-anything obligations --check` again",
file = rust_anything::obligations::source::SOURCE_FILE,
name = clap::ValueEnum::to_possible_value(&lang)
.map(|v| v.get_name().to_string())
.unwrap_or_default(),
);
}
}
let standing = rust_anything::obligations::standing::standing(&repo)?;
if json {
say!("{}", serde_json::to_string_pretty(&standing)?);
} else {
say_raw!(
"{}",
rust_anything::obligations::standing::standing_text(&standing)
);
}
if standing.blocks() {
return Ok(ExitCode::FAILURE);
}
}
Cmd::Obligations {
action: None,
repo,
lang,
write,
json,
evidence,
check: false,
} => {
let ledger = rust_anything::obligations::ledger(&repo, lang)?;
if evidence {
let found = rust_anything::obligations::evidence::evidence(&repo, &ledger)?;
if write {
let path = rust_anything::obligations::write(&repo, &ledger)?;
say!("Wrote {}", path.display());
let path = rust_anything::obligations::evidence::write_evidence(&repo, &found)?;
say!("Wrote {}", path.display());
} else if json {
say!("{}", serde_json::to_string_pretty(&found)?);
} else {
say_raw!(
"{}",
rust_anything::obligations::evidence::evidence_text(&found)
);
}
return Ok(ExitCode::SUCCESS);
}
if json {
say!("{}", serde_json::to_string_pretty(&ledger)?);
} else if write {
let path = rust_anything::obligations::write(&repo, &ledger)?;
say!("Wrote {}", path.display());
} else {
say_raw!("{}", rust_anything::obligations::text(&ledger));
}
}
Cmd::Doctor { json } => {
let report = rust_anything::doctor::run();
if json {
say!("{}", serde_json::to_string_pretty(&report)?);
} else {
say_raw!("{}", rust_anything::doctor::text(&report));
}
if !report.ok() {
return Ok(ExitCode::FAILURE);
}
}
Cmd::New { dir, name, json } => {
let outcome = rust_anything::spec::new_app(&dir, name.as_deref())?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!("Made {} in {}:", outcome.name, outcome.dir.display());
for file in &outcome.files {
say!(" {file}");
}
say!(
"Next: write what the app does in {} and its cases in {} (hello is an example to replace), then approve them with `rust-anything spec approve {}`.",
dir.join("spec").join("SPEC.md").display(),
dir.join("spec").join("cases").display(),
rust_anything::app::cli_path(&dir)
);
}
}
Cmd::Spec { command } => match command {
SpecCmd::Approve { dir, case, json } => {
let outcome = rust_anything::spec::approve(&dir, &case)?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say_raw!("{}", rust_anything::spec::approve_text(&outcome));
}
}
SpecCmd::Check { dir, case, json } => {
let outcome = rust_anything::spec::check(&dir, case.as_deref())?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say_raw!("{}", rust_anything::spec::text(&outcome));
}
if !outcome.done {
return Ok(ExitCode::FAILURE);
}
}
},
Cmd::Rules { root, add, json } => {
let outcome = rust_anything::rules::add(&root, &add)?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for rule in &outcome.added {
say!("Added: {rule}");
}
for rule in &outcome.skipped {
say!("Already a rule: {rule}");
}
if add.is_empty() {
if outcome.rules.is_empty() {
say!("{}", rules_empty_hint(&root, &outcome.file));
} else {
say!("{}:", outcome.file.display());
for rule in &outcome.rules {
say!("- {rule}");
}
}
} else {
say!(
"{} has {}.",
outcome.file.display(),
counted(outcome.rules.len(), "rule")
);
}
}
}
}
Ok(ExitCode::SUCCESS)
}
fn run_app(command: AppCmd) -> Result<ExitCode> {
match command {
AppCmd::Record {
repo,
inputs,
normalize,
name,
no_traps,
timeout,
http,
no_http,
port,
server_args,
no_args,
fresh,
no_fresh,
pace,
ready_timeout,
ready,
float_tolerance,
allow_large_tolerance,
float_files,
effects,
effect_env,
effect_response,
db_reset,
db_dump,
sandbox,
json,
run,
} => {
let float_tolerance = float_tolerance
.map(|t| rust_anything::tolerance::check_bounded(t, allow_large_tolerance))
.transpose()?;
let effects = rust_anything::effects::EffectsConfig::from_args_with_responses(
&effects,
&effect_env,
&effect_response,
&repo,
db_reset.as_deref(),
db_dump.as_deref(),
)?;
let outcome = app::record(&app::RecordOptions {
repo: &repo,
run: &run,
inputs: inputs.as_deref(),
normalize: &normalize,
name: name.as_deref(),
traps: !no_traps,
timeout_secs: timeout,
http: if http {
Some(true)
} else if no_http {
Some(false)
} else {
None
},
port,
server_args: if no_args {
Some(&[])
} else if server_args.is_empty() {
None
} else {
Some(&server_args)
},
fresh: if no_fresh {
Some(&[])
} else if fresh.is_empty() {
None
} else {
Some(&fresh)
},
pace_ms: pace,
float_tolerance,
float_files: &float_files,
effects,
ready_secs: ready_timeout,
ready_request: ready.as_deref(),
sandbox,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
return Ok(ExitCode::SUCCESS);
}
if let Some(note) = &outcome.trycmd_test {
say!("{note}");
}
say!(
"{}",
recorded_summary(
outcome.cases,
&outcome.dir,
outcome.examples,
outcome.inputs,
outcome.duplicate_inputs.len(),
outcome.no_args,
outcome.traps,
(outcome.traps_dropped > 0).then_some(outcome.traps_dropped)
)
);
if !outcome.duplicate_inputs.is_empty() {
say!(
"Duplicate inputs (the same arguments, stdin, environment and files as the case in parentheses; not recorded again): {}",
outcome.duplicate_inputs.join(", ")
);
}
if let Some(last) = &outcome.same_failure {
say!(
"Warning: every case failed with the same exit code and the same error, which ends `{last}`: the original may never have run. Check the command (a missing module, a wrong path) before porting against this recording."
);
}
for (kind, what) in [
(
app::NoiseKind::Lines,
"Lines (a different number of lines between two runs; now `...`, which matches anything: check these first)",
),
(
app::NoiseKind::Order,
"Order (the same lines in another order between two runs; replay compares them in any order)",
),
(
app::NoiseKind::Values,
"Values (parts of lines differed between two runs; now `[..]` wildcards)",
),
] {
let hits: Vec<String> = outcome
.noise
.iter()
.filter(|n| n.kind == kind)
.map(|n| format!("{} ({})", n.case, n.field))
.collect();
if !hits.is_empty() {
say!("Noise, {what}: {}", hits.join(", "));
}
}
if !outcome.unstable.is_empty() {
say!(
"Unstable (exit code or files differed between runs; check them): {}",
outcome.unstable.join(", ")
);
}
if !outcome.timed_out.is_empty() {
say!("Timed out, not recorded: {}", outcome.timed_out.join(", "));
}
if !outcome.stale.is_empty() {
say!(
"Removed, recorded before but not now: {}",
outcome.stale.join(", ")
);
}
if !outcome.kept.is_empty() {
say!(
"Kept, not from a recording (written by hand, or recorded before rust-anything listed its cases; delete them if they no longer apply): {}",
outcome.kept.join(", ")
);
}
say_raw!(
"{}",
rust_anything::obligations::evidence::after_record(&repo)
);
}
AppCmd::Replay {
repo,
build,
timeout,
port,
case,
redact,
json,
} => {
let opts = app::ReplayOptions {
repo: &repo,
build: build.as_deref(),
timeout_secs: timeout,
port,
case: case.as_deref(),
};
let outcome = if redact {
app::replay_redacted(&opts)?
} else {
app::replay(&opts)?
};
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say_replay(&outcome);
}
if !outcome.failures.is_empty() {
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Shadow {
repo,
build,
listen,
upstream,
requests,
timeout,
keep,
json,
} => {
let progress = |event: app_shadow::Event| match event {
app_shadow::Event::Listening(addr) if !json => {
say!(
"Shadowing on http://{addr}: answers come from the original, `{build}` is compared"
);
}
app_shadow::Event::Mismatch(f) if !json => {
let places: Vec<String> = f
.problems
.iter()
.map(|p| {
p.at.as_ref()
.map_or_else(|| p.field.clone(), |at| at.label())
})
.collect();
say!("- {}: {}", f.case, places.join(", "));
}
_ => {}
};
let outcome = app_shadow::shadow(&app_shadow::ShadowOptions {
repo: &repo,
build: &build,
listen,
upstream: upstream.as_deref(),
requests,
timeout_secs: timeout,
keep,
progress: Some(&progress),
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!("{}/{} requests matched", outcome.matched, outcome.requests);
say_groups(&outcome.groups, outcome.mismatches.len());
if !outcome.mismatches.is_empty() {
say!("Log: {}", outcome.log.display());
}
if let Some(inputs) = outcome
.inputs
.as_ref()
.filter(|_| !outcome.mismatches.is_empty())
{
say!(
"Kept: {} (`rust-anything app record --inputs {}` makes them cases)",
inputs.display(),
rust_anything::app::cli_path(inputs)
);
}
}
if !outcome.mismatches.is_empty() {
return Ok(ExitCode::FAILURE);
}
}
AppCmd::FrontDoor {
repo,
no_check,
library,
commands,
json,
} => {
let outcome = front_door::front_door(&front_door::FrontDoorOptions {
repo: &repo,
library,
check: !no_check,
commands: &commands,
})?;
// With no recorded command, `app wire` routes the root under the app's own name, the
// one the front door's state keeps (not always the binary's).
let root = (outcome.api.is_empty()
&& outcome.routes.is_empty()
&& outcome.commands.is_empty())
.then(|| {
front_door::State::load(&repo)
.map(|s| s.name)
.unwrap_or_else(|_| outcome.binary.clone())
});
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"Created {} ({} `{}`), {}",
outcome.dir.display(),
if outcome.api.is_empty() {
"binary"
} else {
"crate"
},
outcome.binary,
if !outcome.api.is_empty() {
format!(
"a library; public API: {}",
outcome
.api
.iter()
.map(|a| format!(
"{} ({})",
a.unit,
counted(a.exports.len(), "export")
))
.collect::<Vec<_>>()
.join(", ")
)
} else if !outcome.routes.is_empty() {
format!("requests recorded: {}", outcome.routes.join(", "))
} else if let Some(root) = &root {
format!("commands: none (the root command is `{root}`)")
} else {
format!("commands: {}", outcome.commands.join(", "))
}
);
for file in &outcome.files {
say!(" {file}");
}
for note in &outcome.notes {
say!("- {note}");
}
if let Some(replay) = &outcome.replay {
say_replay(replay);
}
if !outcome.api.is_empty() {
say!(
"Every export is still only in the original. After a unit's crate (from `bridge`) passes gate: rust-anything app wire {} <unit crate>",
rust_anything::app::cli_path(&repo)
);
} else if let Some(root) = &root {
say!(
"Every command runs the original. After a unit passes gate: rust-anything app wire {} <unit> --command {}",
rust_anything::app::cli_path(&repo),
rust_anything::app::cli_path(root)
);
} else if outcome.routes.is_empty() {
say!(
"Every command runs the original. After a unit passes gate: rust-anything app wire {} <unit> --command <name>",
rust_anything::app::cli_path(&repo)
);
} else {
say!(
"Every request goes to the original. After a unit passes gate: rust-anything app wire {} <unit> --route 'GET /path/{{param}}'",
rust_anything::app::cli_path(&repo)
);
}
}
if outcome
.replay
.as_ref()
.is_some_and(|r| !r.failures.is_empty())
{
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Wire {
repo,
unit,
commands,
routes,
skip_gate,
no_check,
json,
} => {
let outcome = front_door::wire(&front_door::WireOptions {
repo: &repo,
unit: &unit,
commands: &commands,
routes: &routes,
skip_gate,
check: !no_check,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"Wired {} ({}) to {}; {}=original sends it back to the original",
outcome.unit,
outcome.crate_dir.display(),
if outcome.shadow.is_some() {
"the public API".to_string()
} else if outcome.routes.is_empty() {
outcome.commands.join(", ")
} else {
outcome.routes.join(", ")
},
outcome.switch
);
if let Some(shadow) = &outcome.shadow {
say!(
"The original package imports {} in place of the unit until the lift.",
shadow.display()
);
if shadow.extension().is_some_and(|e| e == "c") {
say!(
"C switches at build time: compile without the -D flags in shadow/flags.txt to send it back."
);
}
}
if outcome.glue_pending {
say!(
"Write the glue in {}, then run this again.",
outcome.glue.display()
);
}
if let Some(replay) = &outcome.replay {
say_replay(replay);
}
}
if outcome
.replay
.as_ref()
.is_some_and(|r| !r.failures.is_empty())
{
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Lift { repo, json } => {
let outcome = lift::lift(&lift::LiftOptions { repo: &repo })?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
for item in &outcome.checklist {
let mark = match item.mark {
lift::Mark::Pass => "pass",
lift::Mark::Warn => "warn",
lift::Mark::Fail => "FAIL",
lift::Mark::Skip => "skip",
};
let mut lines = item.detail.lines();
say!(
"{mark} {:<24} {}",
item.name,
lines.next().unwrap_or_default()
);
if item.mark == lift::Mark::Fail {
for line in lines {
say!(" {line}");
}
}
}
if outcome.lifted {
say!(
"Lifted: {} is a pure Rust app ({}). Removed {} generated files; the original is untouched.",
repo.join(front_door::APP_DIR).display(),
outcome
.binary
.as_ref()
.map(|b| b.display().to_string())
.unwrap_or_default(),
outcome.removed.len()
);
} else {
say!("Not lifted:");
for b in &outcome.blockers {
say!("- {b}");
}
if let Some(stage) = &outcome.stage {
say!("The lifted copy is in {} for a look.", stage.display());
}
}
}
if !outcome.lifted {
return Ok(ExitCode::FAILURE);
}
}
AppCmd::Drift {
repo,
build,
timeout,
json,
} => {
let outcome = drift::drift(&drift::DriftOptions {
repo: &repo,
build: build.as_deref(),
timeout_secs: timeout,
})?;
if json {
say!("{}", serde_json::to_string_pretty(&outcome)?);
} else {
say!(
"{}; build: {}",
counted(outcome.cases, "case"),
outcome
.build
.as_ref()
.map(|b| b.join(" "))
.unwrap_or_else(|| "none".to_string())
);
for (title, list) in [
("Changed upstream", &outcome.changed),
("Recording changed", &outcome.recording),
("Port failures", &outcome.failing),
] {
if !list.is_empty() {
say!("{title}:");
for d in list {
say!("- {}: {} ({})", d.case, d.fields.join(", "), d.verdict);
}
}
}
if !outcome.new.is_empty() {
say!("New examples, not recorded:");
for n in &outcome.new {
say!("- {n}");
}
}
if !outcome.drifted {
say!("No drift.");
}
say!("Report: {}", outcome.report.display());
}
if outcome.drifted {
return Ok(ExitCode::FAILURE);
}
}
}
Ok(ExitCode::SUCCESS)
}
/// A path argument made absolute: the tools run compilers and cargo from scratch folders, where
/// a relative crate path points nowhere.
fn absolute(arg: &str) -> Result<PathBuf, String> {
std::path::absolute(arg).map_err(|e| e.to_string())
}
fn rules_empty_hint(root: &std::path::Path, file: &std::path::Path) -> String {
format!(
"No port rules yet in {}. Add one with `rust-anything rules{} --add \"...\"`.",
file.display(),
rust_anything::app::cli_root_arg(root)
)
}
#[cfg(test)]
mod tests {
use super::{
bench_summary_lines, diff_group_lines, fuzz_mismatch_lines, group_lines, recorded_summary,
rules_empty_hint,
};
use rust_anything::harness::{BenchRow, DiffOutcome, verdict};
use rust_anything::lang::Lang;
use rust_anything::mismatch::Group;
use serde_json::json;
use std::path::Path;
fn bench_row(name: &str, speedup: f64, failing: bool) -> BenchRow {
BenchRow {
name: name.into(),
cases: 10,
original_ns: speedup * 100.0,
rust_ns: 100.0,
speedup,
failing,
}
}
fn sample_group(id: &str, function: &str, cases: usize) -> Group {
Group {
id: id.into(),
function: Some(function.into()),
channel: "return vs throw".into(),
path: None,
kind: "type".into(),
cases,
example: json!({}),
}
}
#[test]
fn fuzz_says_how_many_mismatches_it_left_out() {
let outcome = |shown: usize, failed: usize| {
rust_anything::fuzz::FuzzOutcome {
seed: 7,
rounds: 1,
cases: 79,
passed: 79 - failed,
failed,
missing: Vec::new(),
mismatches: (0..shown)
.map(|i| json!({"fn": "add", "args": [i, 1], "expected": {"ok": i + 1}, "actual": {"ok": i + 2}}))
.collect(),
kept: 0,
recording: Path::new("cases.jsonl").to_path_buf(),
dropped: 0,
}
};
let lines = fuzz_mismatch_lines(&outcome(20, 49));
assert_eq!(lines.len(), 21);
assert_eq!(lines[0], r#"- add(0, 1): expected {"ok":1}, got {"ok":2}"#);
assert_eq!(lines.last().unwrap(), "- ... and 29 more");
let lines = fuzz_mismatch_lines(&outcome(3, 3));
assert_eq!(lines.len(), 3);
assert!(lines.iter().all(|l| !l.contains("more")), "{lines:?}");
}
#[test]
fn bench_summary_omits_overall_when_nothing_is_compared() {
let all_failing = vec![
bench_row("rangeOf", 0.01, true),
bench_row("words", 0.02, true),
bench_row("count", 0.03, true),
];
let cd = Path::new("rust/text-rs");
let v_all = verdict(&all_failing, Lang::Ts, cd);
let lines_all = bench_summary_lines(&all_failing, &v_all, cd);
let joined_all = lines_all.join("\n");
assert!(!joined_all.contains("Overall"), "{joined_all}");
assert!(!joined_all.contains("0 of 0"), "{joined_all}");
assert_eq!(
lines_all,
vec![
String::new(),
"Left out of the overall: rangeOf, words, count (their recorded cases do not all match, so their time is the cost of failing, not of the work; run `rust-anything diff rust/text-rs`).".to_string(),
"Nothing to compare: no function matches all its recorded cases yet. Run `rust-anything diff rust/text-rs`.".to_string(),
]
);
let empty: Vec<BenchRow> = Vec::new();
let v_empty = verdict(&empty, Lang::Ts, cd);
let lines_empty = bench_summary_lines(&empty, &v_empty, cd);
assert_eq!(
lines_empty,
vec![
String::new(),
"Nothing to compare: record cases that do not throw first.".to_string(),
]
);
let one = vec![bench_row("double", 2.0, false)];
let v_one = verdict(&one, Lang::Ts, cd);
assert_eq!(
bench_summary_lines(&one, &v_one, cd),
vec![
String::new(),
"Timed as callers call it, crossing included. Overall 2.0x faster (geometric mean); 1 of 1 function at least 1.1x faster.".to_string(),
"Ship it: every function is faster in Rust, call included.".to_string(),
]
);
let mixed = vec![
bench_row("double", 4.0, false),
bench_row("triple", 0.5, false),
bench_row("broken", 0.01, true),
];
let v_mixed = verdict(&mixed, Lang::Python, cd);
assert_eq!(
bench_summary_lines(&mixed, &v_mixed, cd),
vec![
String::new(),
"Timed as callers call it, crossing included. Overall 1.4x faster (geometric mean); 1 of 2 functions at least 1.1x faster.".to_string(),
"Left out of the overall: broken (their recorded cases do not all match, so their time is the cost of failing, not of the work; run `rust-anything diff rust/text-rs`).".to_string(),
"Ship the faster functions. Keep the slower one in the original (`rust-anything enable rust/text-rs --only double`) or move its callers to Rust too: triple.".to_string(),
]
);
let v_go = verdict(&mixed, Lang::Go, cd);
assert!(!v_go.advice.contains("bridge --keep"));
assert!(!v_go.advice.contains("enable"));
}
#[test]
fn diff_groups_count_total_failed_cases_not_truncated_mismatches() {
let truncated = DiffOutcome {
total: 131,
passed: 0,
failed: 131,
mismatches: vec![json!({}); 20],
groups: vec![
sample_group("72647cf4", "rangeOf", 63),
sample_group("2eaeba62", "words", 34),
sample_group("1f1ef7ce", "count", 34),
],
..Default::default()
};
let lines = diff_group_lines(&truncated);
assert_eq!(lines[0], "3 distinct differences in 131 cases:");
assert_eq!(lines.len(), 4);
let within_limit = DiffOutcome {
total: 5,
passed: 0,
failed: 5,
mismatches: vec![json!({}); 5],
groups: vec![
sample_group("72647cf4", "rangeOf", 3),
sample_group("2eaeba62", "words", 2),
],
..Default::default()
};
assert_eq!(
diff_group_lines(&within_limit)[0],
"2 distinct differences in 5 cases:"
);
let singular = DiffOutcome {
total: 1,
passed: 0,
failed: 1,
mismatches: vec![json!({})],
groups: vec![sample_group("1f1ef7ce", "count", 1)],
..Default::default()
};
assert_eq!(
diff_group_lines(&singular)[0],
"1 distinct difference in 1 case:"
);
assert!(group_lines(&[], 0).is_empty());
}
#[test]
fn the_record_summary_counts_traps_like_every_other_count() {
// Issue #854: a recording with one trap said "1 traps" while the case count next to it was
// already singular.
let dir = Path::new("/tmp/app-cases");
assert_eq!(
recorded_summary(1, dir, 0, 0, 0, 0, 1, None),
"Recorded 1 case in /tmp/app-cases (0 from examples, 0 from inputs, 1 trap)"
);
assert_eq!(
recorded_summary(2, dir, 1, 1, 0, 0, 61, None),
"Recorded 2 cases in /tmp/app-cases (1 from examples, 1 from inputs, 61 traps)"
);
assert_eq!(
recorded_summary(1, dir, 0, 0, 0, 0, 0, Some(1)),
"Recorded 1 case in /tmp/app-cases (0 from examples, 0 from inputs, 0 traps, 1 trap dropped)"
);
assert_eq!(
recorded_summary(1, dir, 0, 0, 0, 1, 0, None),
"Recorded 1 case in /tmp/app-cases (0 from examples, 0 from inputs, 1 run with no arguments, 0 traps)"
);
// Input lines that repeat an earlier case are counted, not dropped without a word.
assert_eq!(
recorded_summary(3, dir, 0, 3, 17, 0, 0, None),
"Recorded 3 cases in /tmp/app-cases (0 from examples, 3 from inputs, 17 duplicate inputs skipped, 0 traps)"
);
assert_eq!(
recorded_summary(1, dir, 0, 1, 1, 0, 0, None),
"Recorded 1 case in /tmp/app-cases (0 from examples, 1 from inputs, 1 duplicate input skipped, 0 traps)"
);
}
#[test]
fn rules_empty_hint_omits_dot_and_quotes_spaces() {
assert_eq!(
rules_empty_hint(Path::new("."), Path::new("./rust/RULES.md")),
"No port rules yet in ./rust/RULES.md. Add one with `rust-anything rules --add \"...\"`."
);
assert_eq!(
rules_empty_hint(
Path::new("tests/fixtures/mini"),
Path::new("tests/fixtures/mini/rust/RULES.md")
),
"No port rules yet in tests/fixtures/mini/rust/RULES.md. Add one with `rust-anything rules tests/fixtures/mini --add \"...\"`."
);
// Single quotes for POSIX shells, double quotes on Windows, where cmd takes no others.
let quoted = if cfg!(windows) && std::env::var_os("MSYSTEM").is_none() {
"\"my repo\""
} else {
"'my repo'"
};
assert_eq!(
rules_empty_hint(Path::new("my repo"), Path::new("my repo/rust/RULES.md")),
format!(
"No port rules yet in my repo/rust/RULES.md. Add one with `rust-anything rules {quoted} --add \"...\"`."
)
);
}
#[test]
fn front_door_accepts_repeated_and_comma_commands() {
use clap::Parser;
for argv in [
vec![
"rust-anything",
"app",
"front-door",
".",
"--command",
"check",
"--command",
"fmt",
],
vec![
"rust-anything",
"app",
"front-door",
".",
"--commands",
"check,fmt",
],
] {
let cli = super::Cli::try_parse_from(argv).unwrap();
let super::Cmd::App { command } = cli.command else {
panic!("expected app");
};
let super::AppCmd::FrontDoor { commands, .. } = *command else {
panic!("expected app front-door");
};
assert_eq!(commands, ["check", "fmt"]);
}
}
}