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.9 KB
Raw Blame
//! Runtime checks shared by the integration tests.
//!
//! A test whose runtime is missing is skipped with a note, unless `RUST_ANYTHING_REQUIRE` names
//! that runtime (comma-separated: `node,python3,go,ruby,java`): then the test fails, so CI notices
//! when a language suite stops running. `java` covers `javac` too.

#![allow(dead_code)]

use std::process::Command;

fn required(runtime: &str) -> bool {
    let runtime = if runtime == "javac" { "java" } else { runtime };
    std::env::var("RUST_ANYTHING_REQUIRE").is_ok_and(|list| {
        list.split(',')
            .any(|r| r.trim().eq_ignore_ascii_case(runtime))
    })
}

fn runs(program: &str, args: &[&str]) -> bool {
    Command::new(program)
        .args(args)
        .output()
        .is_ok_and(|o| o.status.success())
}

fn version_args(program: &str) -> &'static [&'static str] {
    match program {
        "go" => &["version"],
        "java" | "javac" | "kotlinc" => &["-version"],
        _ => &["--version"],
    }
}

fn missing(runtime: &str, why: &str) -> bool {
    assert!(
        !required(runtime),
        "{runtime} is required (RUST_ANYTHING_REQUIRE) but {why}"
    );
    eprintln!("skipped: {runtime} {why}");
    false
}

/// Whether `program` runs; skips (or, when required, fails) the test when it does not.
pub fn have(program: &str) -> bool {
    runs(program, version_args(program)) || missing(program, "was not found")
}

/// Whether `program args` succeeds, for runtimes that need more than to exist (a minimum version).
pub fn have_with(program: &str, args: &[&str], need: &str) -> bool {
    runs(program, args) || missing(program, need)
}

/// Ruby 3 or newer, which a test that builds a magnus/rb-sys extension needs: macOS's system
/// Ruby is 2.6, and rb-sys does not build on it.
pub fn have_ruby_3() -> bool {
    have_with(
        "ruby",
        &["-e", "exit(RUBY_VERSION.to_i >= 3 ? 0 : 1)"],
        "3 or newer was not found",
    )
}

/// `python3`, else `python` (Windows installs only the latter); required as `python3` or `python`.
pub fn python() -> Option<&'static str> {
    if let Some(found) = ["python3", "python"]
        .into_iter()
        .find(|p| runs(p, &["--version"]))
    {
        return Some(found);
    }
    if required("python") {
        missing("python", "was not found");
    }
    missing("python3", "was not found");
    None
}

/// Marks a bridged crate as built for tests that swap the compiled module for a stand-in.
///
/// `diff`, `bench` and `fuzz` stop before starting node or python when the crate has no built
/// library; the stand-in replaces it, so an empty file sits where that check looks.
pub fn mark_built(crate_dir: &std::path::Path) {
    use rust_anything::bridge::{Kind, Manifest};
    let manifest = Manifest::load(crate_dir).unwrap();
    let lib = manifest.lib_name();
    match manifest.kind {
        Kind::Napi => std::fs::write(crate_dir.join(format!("{lib}.node")), "").unwrap(),
        Kind::Wasm => {
            std::fs::create_dir_all(crate_dir.join("pkg")).unwrap();
            std::fs::write(crate_dir.join("pkg").join(format!("{lib}.js")), "").unwrap();
        }
        Kind::Pyo3 => {
            let package = crate_dir.join("python").join(&lib);
            std::fs::create_dir_all(&package).unwrap();
            let native = if cfg!(windows) {
                "_native.pyd"
            } else {
                "_native.abi3.so"
            };
            std::fs::write(package.join(native), "").unwrap();
        }
        _ => {}
    }
}

pub struct Scratch(pub std::path::PathBuf);

impl Scratch {
    pub fn new(dir: std::path::PathBuf) -> Self {
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        Scratch(dir)
    }
}

impl std::ops::Deref for Scratch {
    type Target = std::path::Path;

    fn deref(&self) -> &std::path::Path {
        &self.0
    }
}

impl AsRef<std::path::Path> for Scratch {
    fn as_ref(&self) -> &std::path::Path {
        &self.0
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// A loopback port for a test that fixes the port itself, taken from 20000 to 29999. Every
/// common ephemeral range starts higher (Linux 32768, macOS and Windows 49152), so a listener
/// that binds port 0 elsewhere in the run is never handed one of these, which `free_port()`
/// cannot promise: its port is free again the moment it returns (#963). Each call gives a port
/// no earlier call in this process gave and no other test process holds (a lock file per port,
/// kept until the process ends), and checks it is free on both loopbacks: nothing answers there,
/// including a wildcard listener that macOS lets a loopback bind share.
#[allow(dead_code)]
pub fn fixed_port() -> u16 {
    use std::net::{Ipv6Addr, SocketAddr, TcpStream};
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU16, Ordering};
    use std::time::Duration;
    static NEXT: AtomicU16 = AtomicU16::new(0);
    static HELD: Mutex<Vec<std::fs::File>> = Mutex::new(Vec::new());
    let locks = std::env::temp_dir().join("rust-anything-test-ports");
    std::fs::create_dir_all(&locks).unwrap();
    let base = 20_000 + (std::process::id() % 100) as u16 * 100;
    for _ in 0..10_000 {
        let n = NEXT.fetch_add(1, Ordering::Relaxed);
        let port = 20_000 + (base - 20_000 + n) % 10_000;
        let v4 = SocketAddr::from(([127, 0, 0, 1], port));
        let v6 = SocketAddr::from((Ipv6Addr::LOCALHOST, port));
        let answers = |addr: &SocketAddr| {
            TcpStream::connect_timeout(addr, Duration::from_millis(200)).is_ok()
        };
        if answers(&v4) || answers(&v6) {
            continue;
        }
        use rust_anything::http::probe_bind;
        let free = probe_bind(v4).is_ok()
            && !matches!(probe_bind(v6), Err(e) if e.kind() == std::io::ErrorKind::AddrInUse);
        if !free {
            continue;
        }
        let Ok(lock) = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(locks.join(port.to_string()))
        else {
            continue;
        };
        if lock.try_lock().is_ok() {
            HELD.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(lock);
            return port;
        }
    }
    panic!("no free loopback port between 20000 and 29999");
}

pub fn cli() -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_rust-anything"));
    for (key, _) in std::env::vars_os() {
        if key
            .to_str()
            .is_some_and(|k| k.starts_with("RUST_ANYTHING_") && k != "RUST_ANYTHING_REQUIRE")
        {
            cmd.env_remove(key);
        }
    }
    cmd
}

/// What `app lift` asks of a person before it lifts: the obligations of the original that no
/// recorded case exercises are waived, and every family the ledger cannot prove complete is
/// attested, through the public API (each one writes its ADR). The reasons are the fixture's own.
/// Panics when something still blocks afterwards.
pub fn decide_obligations(repo: &std::path::Path) {
    use rust_anything::obligations::standing::{attest, standing, waive};
    let before = standing(repo).unwrap();
    let mut ids: Vec<String> = before
        .blocking
        .uncovered
        .iter()
        .map(|u| u.id.clone())
        .collect();
    ids.extend(before.blocking.wildcards.iter().map(|w| w.id.clone()));
    ids.extend(before.blocking.fallbacks.iter().map(|f| f.id.clone()));
    if !ids.is_empty() {
        waive(repo, &ids, "fixture: its cases are the recorded examples").unwrap();
    }
    let families: Vec<_> = before.blocking.families.iter().map(|f| f.family).collect();
    if !families.is_empty() {
        attest(
            repo,
            &families,
            "fixture: nobody reads more than its detectors list",
        )
        .unwrap();
    }
    let after = standing(repo).unwrap();
    assert!(!after.blocks(), "{after:#?}");
}