Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

cli: add --json output flag for machine-readable command results

Brixton Pham269cee66bf6a
diff --git a/src/doctor.rs b/src/doctor.rs
index 2218239..065952e 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -2,6 +2,7 @@
use crate::ui::{self, bold, dim, green, red, yellow};
use anyhow::{Result, ensure};
+use serde::Serialize;
use std::process::Command;
fn version(program: &str, args: &[&str]) -> Option<String> {
@@ -53,6 +54,25 @@ fn problem(name: &str, found: &str) -> Option<String> {
None
}
+#[derive(Debug, Clone, Serialize)]
+pub struct Tool {
+ pub name: &'static str,
+ pub ok: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub version: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub problem: Option<String>,
+ pub need: &'static str,
+ pub hint: &'static str,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Report {
+ pub ready_to_scan: bool,
+ pub ready_to_port: bool,
+ pub tools: Vec<Tool>,
+}
+
struct Check {
name: &'static str,
found: Option<String>,
@@ -60,7 +80,15 @@ struct Check {
hint: &'static str,
}
-pub fn run() -> Result<()> {
+impl Check {
+ fn into_tool(self) -> Tool {
+ let problem = self.found.as_deref().and_then(|v| problem(self.name, v));
+ let ok = self.found.is_some() && problem.is_none();
+ Tool { name: self.name, ok, version: self.found, problem, need: self.need, hint: self.hint }
+ }
+}
+
+pub fn check() -> Report {
let python = version("python", &["--version"]).or_else(|| version("python3", &["--version"]));
let checks = [
Check {
@@ -145,31 +173,41 @@ pub fn run() -> Result<()> {
hint: "npm i -g @openai/codex",
},
];
- let usable = |c: &Check| c.found.as_deref().is_some_and(|v| problem(c.name, v).is_none());
- for c in &checks {
- match &c.found {
- Some(v) => match problem(c.name, v) {
- None => ui::line(format!(" {} {:<8} {}", green("✓"), bold(c.name), dim(v))),
- Some(why) => ui::line(format!(" {} {:<8} {} {}", red("✗"), bold(c.name), dim(v), why)),
- },
- None if c.name == "cargo" => {
- ui::line(format!(" {} {:<8} missing, {}: {}", red("✗"), bold(c.name), c.need, c.hint))
+ let tools: Vec<Tool> = checks.into_iter().map(Check::into_tool).collect();
+ let ready_to_scan = tools[1..12].iter().any(|t| t.ok);
+ let ready_to_port = tools[0].ok;
+ Report { ready_to_scan, ready_to_port, tools }
+}
+
+pub fn ensure_ready(report: &Report) -> Result<()> {
+ ensure!(
+ report.ready_to_scan,
+ "install Python, Node.js (or Bun, Deno), Ruby, Java, Go, PHP, .NET, R or a C compiler"
+ );
+ Ok(())
+}
+
+pub fn run() -> Result<()> {
+ let report = check();
+ for t in &report.tools {
+ match (&t.version, &t.problem) {
+ (Some(v), None) => ui::line(format!(" {} {:<8} {}", green("✓"), bold(t.name), dim(v))),
+ (Some(v), Some(why)) => ui::line(format!(" {} {:<8} {} {}", red("✗"), bold(t.name), dim(v), why)),
+ (None, _) if t.name == "cargo" => {
+ ui::line(format!(" {} {:<8} missing, {}: {}", red("✗"), bold(t.name), t.need, t.hint))
}
- None => ui::line(format!(
+ (None, _) => ui::line(format!(
" {} {:<8} {}",
yellow("·"),
- c.name,
- dim(format!("not found ({}): {}", c.need, c.hint))
+ t.name,
+ dim(format!("not found ({}): {}", t.need, t.hint))
)),
}
}
- ensure!(
- checks[1..12].iter().any(usable),
- "install Python, Node.js (or Bun, Deno), Ruby, Java, Go, PHP, .NET, R or a C compiler"
- );
+ ensure_ready(&report)?;
ui::ok("ready to scan");
// scanning works without Rust, so a missing toolchain only warns (#142)
- if usable(&checks[0]) {
+ if report.ready_to_port {
ui::ok("ready to port");
} else {
ui::warn("Rust 1.85 or newer is needed to port, verify and enable: https://rustup.rs");
@@ -194,4 +232,32 @@ mod tests {
assert!(problem("python", "Python 3.9.18").is_some());
assert_eq!(problem("clang", "Debian clang version 14.0.6"), None, "no minimum");
}
+
+ #[test]
+ fn report_serializes_clean_json() {
+ let mk = |name, found: Option<&str>, need, hint| {
+ Check { name, found: found.map(String::from), need, hint }.into_tool()
+ };
+ let report = Report {
+ ready_to_scan: true,
+ ready_to_port: false,
+ tools: vec![
+ mk("cargo", None, "to port (scan works without it)", "https://rustup.rs"),
+ mk("python", Some("Python 3.12.1"), "for Python apps (3.10+)", "https://python.org"),
+ mk("ruby", Some("ruby 3.1.7p261"), "for Ruby apps (3.3+)", "https://ruby-lang.org"),
+ ],
+ };
+ let raw = serde_json::to_string_pretty(&report).unwrap();
+ assert!(!raw.contains("\x1b["), "no ANSI codes in JSON: {raw}");
+ let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ assert_eq!((&v["ready_to_scan"], &v["ready_to_port"]), (&serde_json::json!(true), &serde_json::json!(false)));
+ let tools = v["tools"].as_array().unwrap();
+ assert_eq!(tools.len(), 3);
+ assert_eq!(tools[0]["ok"], false);
+ assert!(tools[0].get("version").is_none() && tools[0].get("problem").is_none());
+ assert_eq!(tools[1]["ok"], true);
+ assert!(tools[2]["problem"].as_str().unwrap().contains("3.3 or newer"));
+ assert!(ensure_ready(&report).is_ok());
+ assert!(ensure_ready(&Report { ready_to_scan: false, ..report }).is_err());
+ }
}
diff --git a/src/main.rs b/src/main.rs
index 448b80b..617a2e4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -24,8 +24,9 @@ mod state;
mod ui;
mod util;
-use anyhow::{Result, bail};
+use anyhow::{Result, bail, ensure};
use clap::{Parser, Subcommand};
+use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
@@ -38,6 +39,9 @@ struct Cli {
/// Project folder (default: the current folder)
#[arg(short = 'C', long = "dir", global = true, default_value = ".")]
dir: PathBuf,
+ /// Print machine-readable JSON on stdout
+ #[arg(long, global = true)]
+ json: bool,
#[command(subcommand)]
cmd: Cmd,
}
@@ -136,7 +140,7 @@ enum Cmd {
fn main() -> ExitCode {
let cli = Cli::parse();
let root = util::absolute(&cli.dir);
- match run(cli.cmd, &root) {
+ match run(cli.cmd, &root, cli.json) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
ui::error(format!("{e:#}"));
@@ -145,55 +149,108 @@ fn main() -> ExitCode {
}
}
-fn run(cmd: Cmd, root: &Path) -> Result<()> {
- match cmd {
- Cmd::Mcp => return mcp::serve(),
- Cmd::Replay { job } => return native::replay(&job),
- _ => {}
+fn run(cmd: Cmd, root: &Path, json: bool) -> Result<()> {
+ if let Cmd::Replay { job } = cmd {
+ return native::replay(&job);
+ }
+ if json {
+ match &cmd {
+ Cmd::Go { .. } | Cmd::Build | Cmd::Clean { .. } | Cmd::Mcp => {
+ bail!(
+ "--json isn't supported for this command (supported: scan, port, verify, enable, disable, bench, report, status, doctor)"
+ );
+ }
+ _ => ui::set_quiet(true),
+ }
+ }
+ if matches!(cmd, Cmd::Mcp) {
+ return mcp::serve();
+ }
+ if !json {
+ ui::banner();
}
- ui::banner();
match cmd {
Cmd::Go { agent, top, attempts, runs, samples, command } => {
pipeline::go(root, command, agent.as_deref(), top, attempts, runs, samples)
}
Cmd::Scan { command, duration } => {
- show::scan(&pipeline::scan(root, command, duration)?);
- Ok(())
+ let out = pipeline::scan(root, command, duration)?;
+ if json {
+ show::json(&show::scan_json(&out))
+ } else {
+ show::scan(&out);
+ Ok(())
+ }
}
Cmd::Port { id, agent, attempts, samples } => {
let out = pipeline::port(root, id.as_deref(), samples)?;
- show::port(&out, agent.is_none());
if let Some(agent) = agent {
+ if !json {
+ show::port(&out, false);
+ }
let v = pipeline::agent_port(root, &out.id, &agent, attempts)?;
+ if json {
+ show::json(&json!({ "port": out, "verify": show::verify_json(&out.id, &v) }))?;
+ }
if !v.ok() {
bail!("{agent} couldn't get {} right in {attempts} attempts", out.id);
}
- if !v.slower() {
+ if !json && !v.slower() {
show::next(&format!("fast-anything enable {}", out.id));
}
+ } else if json {
+ show::json(&out)?;
+ } else {
+ show::port(&out, true);
}
Ok(())
}
- Cmd::Verify { all: true, .. } => pipeline::verify_all(root),
+ Cmd::Verify { all: true, .. } => {
+ let results = pipeline::verify_all(root)?;
+ let failed: Vec<&str> = results.iter().filter(|(_, v)| !v.ok()).map(|(id, _)| id.as_str()).collect();
+ if json {
+ let ports: Vec<Value> = results.iter().map(|(id, v)| show::verify_json(id, v)).collect();
+ show::json(&json!({ "ok": failed.is_empty(), "ports": ports }))?;
+ }
+ ensure!(
+ failed.is_empty(),
+ "{} of {} ports don't match: {}",
+ failed.len(),
+ results.len(),
+ failed.join(", ")
+ );
+ ui::ok(format!("all {} ports match the original", results.len()));
+ Ok(())
+ }
Cmd::Verify { id, .. } => {
let (id, v) = pipeline::verify(root, id.as_deref())?;
- show::verify(&id, &v);
+ if json {
+ show::json(&show::verify_json(&id, &v))?;
+ } else {
+ show::verify(&id, &v);
+ }
if !v.ok() {
bail!("{id} doesn't match the original yet");
}
- if !v.slower() {
+ if !json && !v.slower() {
show::next(&format!("fast-anything enable {id}"));
}
Ok(())
}
Cmd::Enable { id, force } => {
let id = pipeline::enable(root, id.as_deref(), force)?;
+ if json {
+ return show::json(&json!({ "enabled": id }));
+ }
ui::ok(format!("{} now runs in Rust", ui::bold(&id)));
show::next("fast-anything bench");
Ok(())
}
Cmd::Disable { all: true, .. } => {
let ids = pipeline::disable_all(root)?;
+ if json {
+ return show::json(&json!({ "disabled": ids }));
+ }
if ids.is_empty() {
ui::ok("no port was switched on");
}
@@ -204,25 +261,51 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {
}
Cmd::Disable { id, .. } => {
let id = pipeline::disable(root, id.as_deref())?;
+ if json {
+ return show::json(&json!({ "disabled": id }));
+ }
ui::ok(format!("{} is back to the original code", ui::bold(&id)));
Ok(())
}
Cmd::Build => pipeline::build_all(root),
Cmd::Clean { all } => pipeline::clean(root, all),
Cmd::Bench { runs } => {
- show::bench(&pipeline::bench(root, runs)?);
- show::next("fast-anything report");
- Ok(())
+ let out = pipeline::bench(root, runs)?;
+ if json {
+ show::json(&out)
+ } else {
+ show::bench(&out);
+ show::next("fast-anything report");
+ Ok(())
+ }
}
Cmd::Report => {
- show::report(&pipeline::report(root)?);
- Ok(())
+ let out = pipeline::report(root)?;
+ if json {
+ show::json(&out)
+ } else {
+ show::report(&out);
+ Ok(())
+ }
}
Cmd::Status => {
- show::status(&state::Ctx::open(root)?);
- Ok(())
+ let ctx = state::Ctx::open(root)?;
+ if json {
+ show::json(&show::status_json(&ctx))
+ } else {
+ show::status(&ctx);
+ Ok(())
+ }
+ }
+ Cmd::Doctor => {
+ if json {
+ let report = doctor::check();
+ show::json(&report)?;
+ doctor::ensure_ready(&report)
+ } else {
+ doctor::run()
+ }
}
- Cmd::Doctor => doctor::run(),
Cmd::Mcp | Cmd::Replay { .. } => unreachable!(),
}
}
@@ -259,4 +342,46 @@ mod tests {
Cmd::Verify { all: false, .. }
));
}
+
+ #[test]
+ fn json_flag_parses_before_and_after_subcommand() {
+ for argv in [
+ vec!["fast-anything", "--json", "doctor"],
+ vec!["fast-anything", "doctor", "--json"],
+ vec!["fast-anything", "status", "--json"],
+ vec!["fast-anything", "bench", "--json", "--runs", "3"],
+ vec!["fast-anything", "verify", "--all", "--json"],
+ vec!["fast-anything", "report", "--json"],
+ vec!["fast-anything", "port", "--json", "fuzzy.lev"],
+ vec!["fast-anything", "enable", "--json", "fuzzy.lev"],
+ vec!["fast-anything", "disable", "--all", "--json"],
+ ] {
+ let cli = Cli::try_parse_from(argv).unwrap();
+ assert!(cli.json);
+ }
+
+ let scan_before = Cli::try_parse_from(["fast-anything", "--json", "scan", "--", "python", "app.py"]).unwrap();
+ assert!(scan_before.json);
+ let scan_after = Cli::try_parse_from(["fast-anything", "scan", "--json", "--", "python", "app.py"]).unwrap();
+ assert!(scan_after.json);
+
+ // --json after -- belongs to the user's app command, not fast-anything.
+ let app_flag = Cli::try_parse_from(["fast-anything", "scan", "--", "python", "app.py", "--json"]).unwrap();
+ assert!(!app_flag.json);
+ assert!(matches!(app_flag.cmd, Cmd::Scan { command, .. } if command == ["python", "app.py", "--json"]));
+ }
+
+ #[test]
+ fn json_rejects_unsupported_subcommands() {
+ let root = Path::new(".");
+ for cmd in [
+ Cmd::Build,
+ Cmd::Clean { all: false },
+ Cmd::Mcp,
+ Cmd::Go { agent: None, top: 1, attempts: 3, runs: 5, samples: 500, command: vec!["python".into()] },
+ ] {
+ let err = run(cmd, root, true).unwrap_err();
+ assert!(err.to_string().contains("--json isn't supported"), "{err}");
+ }
+ }
}
diff --git a/src/pipeline.rs b/src/pipeline.rs
index a6689cf..fc6945e 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -207,20 +207,18 @@ pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {
}
/// Verify every port; an enabled one that fails is switched back, as with a single verify.
-pub fn verify_all(root: &Path) -> Result<()> {
+pub fn verify_all(root: &Path) -> Result<Vec<(String, Verify)>> {
let ids: Vec<String> = Ctx::open(root)?.state.ports.keys().cloned().collect();
ensure!(!ids.is_empty(), "nothing ported yet: run fast-anything port");
- let mut failed = vec![];
+ let mut results = Vec::with_capacity(ids.len());
for id in &ids {
let (id, v) = verify(root, Some(id))?;
- show::verify(&id, &v);
- if !v.ok() {
- failed.push(id);
+ if !ui::quiet() {
+ show::verify(&id, &v);
}
+ results.push((id, v));
}
- ensure!(failed.is_empty(), "{} of {} ports don't match: {}", failed.len(), ids.len(), failed.join(", "));
- ui::ok(format!("all {} ports match the original", ids.len()));
- Ok(())
+ Ok(results)
}
/// What to do about a port whose original changed after it was recorded.
@@ -434,7 +432,9 @@ pub fn agent_port(root: &Path, id: &str, agent_spec: &str, attempts: usize) -> R
ui::step(format!("{} is writing the Rust port (attempt {attempt}/{attempts})", ui::bold(agent_spec)));
agent::run(agent_spec, &dir, &prompt, &dir.join("agent.log"))?;
let (_, v) = verify(root, Some(id))?;
- show::verify(id, &v);
+ if !ui::quiet() {
+ show::verify(id, &v);
+ }
if v.ok() && !v.slower() {
return Ok(v);
}
diff --git a/src/show.rs b/src/show.rs
index c1ef57d..80e48be 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -6,6 +6,9 @@ use crate::report::ReportOut;
use crate::state::{Ctx, Verify};
use crate::ui::{self, bold, dim, green, red, rust, yellow};
use crate::util::{nanos, secs, thousands, times};
+use anyhow::Result;
+use serde::Serialize;
+use serde_json::{Value, json};
fn bar(share: f64, width: usize) -> String {
const PARTS: [char; 8] = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
@@ -264,9 +267,84 @@ pub fn status(ctx: &Ctx) {
}
}
+pub fn json(value: &impl Serialize) -> Result<()> {
+ println!("{}", serde_json::to_string_pretty(value)?);
+ Ok(())
+}
+
+pub fn scan_json(s: &ScanOut) -> Value {
+ let hotspots: Vec<Value> = s
+ .hotspots
+ .iter()
+ .map(|h| {
+ json!({
+ "id": h.id,
+ "file": h.file,
+ "line": h.line,
+ "share": h.share,
+ "calls": h.ncalls,
+ "tottime": h.tottime,
+ "cumtime": h.cumtime,
+ "portable": h.portable(),
+ "worth_porting": h.worth_it(),
+ "why_not": h.why_not(),
+ "covered_by": h.covered_by,
+ "blockers": h.blockers,
+ "warnings": h.warnings,
+ })
+ })
+ .collect();
+ json!({
+ "command": s.command,
+ "wall_seconds": s.wall,
+ "hotspots": hotspots,
+ "notes": s.notes,
+ })
+}
+
+pub fn verify_json(id: &str, v: &Verify) -> Value {
+ let mut out = serde_json::to_value(v).unwrap_or(Value::Null);
+ if let Some(obj) = out.as_object_mut() {
+ obj.insert("id".into(), json!(id));
+ obj.insert("ok".into(), json!(v.ok()));
+ if !v.ok() {
+ obj.insert("fix".into(), json!(crate::pipeline::feedback(v)));
+ }
+ }
+ out
+}
+
+pub fn status_json(ctx: &Ctx) -> Value {
+ let s = &ctx.state;
+ let ports: serde_json::Map<String, Value> = s
+ .ports
+ .iter()
+ .map(|(id, p)| {
+ let mut v = serde_json::to_value(p).unwrap_or(Value::Null);
+ if let Some(obj) = v.as_object_mut() {
+ obj.insert("stale".into(), json!(ctx.stale(p)));
+ }
+ (id.clone(), v)
+ })
+ .collect();
+ let lang = (!s.command.is_empty()).then_some(s.lang);
+ json!({
+ "command": s.command,
+ "lang": lang,
+ "wall_seconds": s.wall,
+ "ports": ports,
+ "bench": s.bench,
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use crate::backend::Lang;
+ use crate::hotspot::Hotspot;
+ use crate::state::{Failure, Micro, Port, State};
+ use std::collections::BTreeMap;
+ use std::path::PathBuf;
#[test]
fn long_ids_keep_the_function_name() {
@@ -294,4 +372,111 @@ mod tests {
assert_eq!(status_a.chars().count(), 32);
assert!(status_a.ends_with("decodeArchive") && status_b.ends_with("checkHeader"));
}
+
+ #[test]
+ fn json_helpers_produce_valid_plain_json() {
+ let parse = |v: Value| -> Value {
+ let raw = serde_json::to_string_pretty(&v).unwrap();
+ assert!(!raw.contains("\x1b["), "no ANSI escapes: {raw}");
+ serde_json::from_str(&raw).unwrap()
+ };
+
+ let scan = ScanOut {
+ command: vec!["python".into(), "app.py".into()],
+ wall: 2.5,
+ hotspots: vec![
+ Hotspot {
+ id: "fuzzy.lev".into(),
+ file: "fuzzy.py".into(),
+ line: 10,
+ ncalls: 1000,
+ share: 0.8,
+ ..Hotspot::default()
+ },
+ Hotspot {
+ id: "fuzzy.io".into(),
+ file: "fuzzy.py".into(),
+ line: 30,
+ ncalls: 1,
+ share: 0.2,
+ blockers: vec!["does I/O".into()],
+ ..Hotspot::default()
+ },
+ ],
+ notes: vec!["note".into()],
+ };
+ let parsed = parse(scan_json(&scan));
+ assert_eq!(parsed["command"], json!(["python", "app.py"]));
+ assert_eq!(parsed["wall_seconds"], 2.5);
+ assert_eq!(
+ (&parsed["hotspots"][0]["worth_porting"], &parsed["hotspots"][1]["why_not"]),
+ (&json!(true), &json!("does I/O"))
+ );
+
+ let ok_v = Verify {
+ built: true,
+ total: 10,
+ passed: 10,
+ micro: Some(Micro { original_ns: 100.0, rust_ns: 10.0, speedup: 10.0 }),
+ lang: Lang::Python,
+ ..Verify::default()
+ };
+ let ok_parsed = parse(verify_json("fuzzy.lev", &ok_v));
+ assert_eq!((&ok_parsed["id"], &ok_parsed["ok"]), (&json!("fuzzy.lev"), &json!(true)));
+ assert!(ok_parsed.get("fix").is_none());
+
+ let bad_v = Verify {
+ built: true,
+ total: 10,
+ passed: 9,
+ failed: 1,
+ failures: vec![Failure { case: 1, call: "lev('a','b')".into(), expected: "1".into(), got: "2".into() }],
+ ..Verify::default()
+ };
+ let bad_parsed = parse(verify_json("fuzzy.lev", &bad_v));
+ assert_eq!(bad_parsed["ok"], false);
+ assert!(bad_parsed["fix"].as_str().unwrap().contains("1 of 10"));
+
+ let empty_ctx = Ctx { root: PathBuf::from("."), fast: PathBuf::from(".fast"), state: State::default() };
+ let empty_status = parse(status_json(&empty_ctx));
+ assert!(empty_status["lang"].is_null() && empty_status["ports"] == json!({}));
+
+ let mut ports = BTreeMap::new();
+ ports.insert(
+ "fuzzy.lev".into(),
+ Port {
+ id: "fuzzy.lev".into(),
+ file: "fuzzy.py".into(),
+ module: "fuzzy".into(),
+ func: "lev".into(),
+ ext: "fa_fuzzy_lev".into(),
+ crate_dir: ".fast/ports/fuzzy.lev".into(),
+ recorded: 10,
+ calls_seen: 10,
+ verify: Some(ok_v),
+ enabled: true,
+ lang: Lang::Python,
+ owner: None,
+ line: 10,
+ sources: vec![],
+ },
+ );
+ let ctx = Ctx {
+ root: PathBuf::from("."),
+ fast: PathBuf::from(".fast"),
+ state: State {
+ command: vec!["python".into(), "app.py".into()],
+ lang: Lang::Python,
+ wall: 1.25,
+ ports,
+ ..State::default()
+ },
+ };
+ let status_parsed = parse(status_json(&ctx));
+ assert_eq!((&status_parsed["lang"], &status_parsed["wall_seconds"]), (&json!("python"), &json!(1.25)));
+ assert_eq!(
+ (&status_parsed["ports"]["fuzzy.lev"]["enabled"], &status_parsed["ports"]["fuzzy.lev"]["stale"]),
+ (&json!(true), &json!(false))
+ );
+ }
}