Skip to content

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.

7.7 KB
Raw Blame
//! What tools read from `--json`: results carry the time and the port version where applicable,
//! `map` says which units are on, a failure under `--json` is JSON on stdout, and
//! `--version --json` lists the schemas. The gate's saved result, its events and
//! `report.json` need a recorded port; they are checked where one is built, in `tests/fuzz.rs`
//! and `tests/report.rs`.

mod common;

use std::path::{Path, PathBuf};
use std::process::Output;

use rust_anything::walk::Canonical;
use rust_anything::{bridge, state};
use serde_json::Value;

fn copy_tree(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap().flatten() {
        let path = entry.path();
        if path.is_dir() {
            copy_tree(&path, &to.join(entry.file_name()));
        } else {
            std::fs::copy(&path, to.join(entry.file_name())).unwrap();
        }
    }
}

fn bridged(name: &str) -> (PathBuf, PathBuf) {
    let repo =
        std::env::temp_dir().join(format!("rust-anything-json-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&repo);
    copy_tree(
        &Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini"),
        &repo,
    );
    let repo = repo.canonical().unwrap();
    let crate_dir = repo.join("rust/util-rs");
    bridge::bridge(&bridge::Options {
        root: &repo,
        unit: "packages/a/src/util.ts",
        kind: None,
        out: Some(crate_dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    // A stand-in for the built module: `enable` loads it before it edits a file.
    std::fs::write(
        crate_dir.join("index.cjs"),
        "exports.rangeOf = () => 0\nexports.words = () => 0\nexports.count = () => 0\n",
    )
    .unwrap();
    (repo, crate_dir)
}

fn run(args: &[&str], path: Option<&Path>) -> Output {
    let mut cmd = common::cli();
    cmd.args(args);
    if let Some(p) = path {
        cmd.arg(p);
    }
    cmd.output().unwrap()
}

fn json(out: &Output) -> Value {
    serde_json::from_slice(&out.stdout)
        .unwrap_or_else(|e| panic!("{e}: {}", String::from_utf8_lossy(&out.stdout)))
}

fn map(repo: &Path) -> Value {
    let out = run(&["map", "--json"], Some(repo));
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    json(&out)
}

fn is_time(v: &Value) -> bool {
    regex::Regex::new(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$")
        .unwrap()
        .is_match(v.as_str().unwrap_or_default())
}

#[test]
fn version_json_lists_the_schema_of_every_output() {
    let out = run(&["--version", "--json"], None);
    assert!(out.status.success());
    let v = json(&out);
    assert_eq!(v["name"], "rust-anything");
    assert_eq!(v["version"], env!("CARGO_PKG_VERSION"));
    let schemas = v["schemas"].as_object().expect("schema map");
    for command in state::SCHEMAS {
        assert_eq!(schemas[command], state::schema(command), "{command}");
    }

    let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mini");
    let analysis = run(&["analyze", "--json"], Some(&fixture));
    assert!(
        analysis.status.success(),
        "{}",
        String::from_utf8_lossy(&analysis.stderr)
    );
    let analysis = json(&analysis);
    let analysis_schema = analysis["schema"].as_str().expect("analyze schema");
    assert_eq!(schemas["analyze"], analysis_schema);
    assert_eq!(schemas.len(), state::SCHEMAS.len());

    let plain = run(&["--version"], None);
    assert_eq!(
        String::from_utf8_lossy(&plain.stdout).trim(),
        format!("rust-anything {}", env!("CARGO_PKG_VERSION"))
    );
}

#[test]
fn map_says_which_units_are_on_and_which_port_version_it_saw() {
    let (repo, crate_dir) = bridged("map");
    let before = map(&repo);
    assert_eq!(before["schema"], "rust-anything/map@1");
    let port = &before["ports"][0];
    assert_eq!(port["language"], "ts");
    assert_eq!(port["language_name"], "TypeScript/JavaScript");
    assert_eq!(port["enabled"], false);
    let version = port["port"].as_str().unwrap().to_string();
    assert_eq!(version.len(), 16);
    assert!(port.get("last_gate").is_none());

    // `enable` loads the module before it says On: a stand-in takes the place of the build.
    std::fs::write(
        crate_dir.join("index.cjs"),
        "exports.rangeOf = () => 0\nexports.words = () => 0\nexports.count = () => 0\n",
    )
    .unwrap();
    let on = run(&["enable", "--force", "--json"], Some(&crate_dir));
    assert!(
        on.status.success(),
        "{}",
        String::from_utf8_lossy(&on.stderr)
    );
    let on = json(&on);
    assert_eq!(on["schema"], "rust-anything/enable@1");
    assert!(is_time(&on["at"]), "{on}");
    assert_eq!(map(&repo)["ports"][0]["enabled"], true);

    let port_rs = crate_dir.join("src/port.rs");
    let text = std::fs::read_to_string(&port_rs).unwrap();
    std::fs::write(&port_rs, text + "\n// changed\n").unwrap();
    let after = map(&repo);
    assert_ne!(
        after["ports"][0]["port"], version,
        "editing port.rs is a new port version"
    );

    let off = json(&run(&["disable", "--json"], Some(&crate_dir)));
    assert_eq!(off["schema"], "rust-anything/disable@1");
    assert_eq!(map(&repo)["ports"][0]["enabled"], false);
    std::fs::remove_dir_all(&repo).unwrap();
}

#[test]
fn a_failure_under_json_from_usage_is_json_on_stdout() {
    for args in [
        vec!["gate", "--json", "--held-out-cases", "many"],
        vec!["analyze", ".", "--json", "--lang", "klingon"],
    ] {
        let out = run(&args, None);
        assert_eq!(out.status.code(), Some(2));
        let v = json(&out);
        assert_eq!(v["schema"], "rust-anything/error@1");
        assert_eq!(v["error"]["code"], "usage");
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert_eq!(
            v["error"]["message"],
            stderr
                .lines()
                .next()
                .unwrap()
                .strip_prefix("error: ")
                .unwrap()
        );
        let plain: Vec<_> = args.into_iter().filter(|arg| *arg != "--json").collect();
        let out = run(&plain, None);
        assert_eq!(out.status.code(), Some(2));
        assert!(out.stdout.is_empty(), "without --json stdout stays empty");
    }

    let out = run(&["app", "wire", "--json"], None);
    assert_eq!(out.status.code(), Some(2));
    let v = json(&out);
    assert_eq!(v["schema"], "rust-anything/error@1");
    assert_eq!(v["error"]["code"], "usage");
    let message = v["error"]["message"].as_str().unwrap();
    assert!(message.contains("<REPO>"), "{message}");
    assert!(message.contains("<UNIT>"), "{message}");
    let plain = run(&["app", "wire"], None);
    assert_eq!(plain.status.code(), Some(2));
    assert!(plain.stdout.is_empty(), "without --json stdout stays empty");
}

#[test]
fn a_failure_under_json_is_json_on_stdout() {
    for args in [["gate", "--json"], ["diff", "--json"]] {
        let out = run(&args, Some(Path::new("/no/such/rust-anything-crate")));
        assert_eq!(out.status.code(), Some(2));
        let v = json(&out);
        assert_eq!(v["schema"], "rust-anything/error@1");
        assert_eq!(v["error"]["code"], "not_bridged", "{args:?}: {v}");
        assert!(
            v["error"]["message"]
                .as_str()
                .unwrap()
                .contains("rust-anything bridge")
        );
        assert!(String::from_utf8_lossy(&out.stderr).starts_with("error: "));
    }
    let plain = run(&["gate"], Some(Path::new("/no/such/rust-anything-crate")));
    assert!(plain.stdout.is_empty(), "without --json stdout stays empty");
}