limonite-cli 0.1.4

Limonite's command: builds, runs and tests Rust crates compiled to JavaScript, with a prebuilt backend it downloads once
//! `limonite`: Limonite without building it. The first run installs what it needs, once:
//!
//! * the pinned nightly, through rustup (the backend is a plugin of that exact rustc). Projects keep their own
//!   toolchain: only Limonite's builds use the nightly, and they pick it themselves;
//! * the prebuilt backend and std for this machine (release/bundle.sh): downloaded from the release of this version,
//!   checked against the checksum built into this command (bundles.txt), and unpacked into the cache.
//!
//! Then every command is Limonite's own (bin/limonite.mjs, under Node):
//!
//! ```text
//! limonite build|run|size|test [cargo options] [-- args]
//! limonite install     only the installing
//! limonite home        where the installed Limonite is (for lazuli-cli: its LIMONITE is <home>/bin/limonite.mjs)
//! ```
//!
//! `LIMONITE_HOME`: use that unpacked bundle (or a checkout) instead of downloading one. `LIMONITE_CACHE`: where
//! bundles go (by default the platform's cache folder). `LIMONITE_DOWNLOAD`: where bundles are downloaded from (a
//! mirror; the checksums still apply).
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};

const VERSION: &str = env!("CARGO_PKG_VERSION");
/// the nightly the backend is built for (rust-toolchain.toml, bin/limonite.mjs)
const TOOLCHAIN: &str = "nightly-2026-11-24";
/// `<sha256>  limonite-<version>-<host>.tar.gz`, one line per platform with a prebuilt bundle (filled at release)
const BUNDLES: &str = include_str!("../bundles.txt");

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.first().map(String::as_str) {
        Some("--version" | "-V") => { println!("limonite {VERSION} (rustc {TOOLCHAIN})"); return ExitCode::SUCCESS }
        None | Some("--help" | "-h") => { eprintln!("usage: limonite build|run|size|test [cargo options] [-- args]\n       limonite install | home | --version"); return ExitCode::from(2) }
        _ => {}
    }
    let home = match install() { Ok(h) => h, Err(e) => { eprintln!("limonite: {e}"); return ExitCode::FAILURE } };
    match args[0].as_str() {
        "install" => { eprintln!("limonite: {VERSION} is installed in {}", home.display()); ExitCode::SUCCESS }
        "home" => { println!("{}", home.display()); ExitCode::SUCCESS }
        _ => {
            let script = home.join("bin/limonite.mjs");
            match Command::new("node").arg(&script).args(&args).status() {
                Ok(s) => ExitCode::from(s.code().map_or(1, |c| c.clamp(0, 255) as u8)),
                Err(e) => { eprintln!("limonite: cannot run node: {e} (Limonite runs under Node.js 22 or later: nodejs.org)"); ExitCode::FAILURE }
            }
        }
    }
}

/// The installed Limonite: the toolchain checked (installed if missing), the bundle unpacked (downloaded if missing)
fn install() -> Result<PathBuf, String> {
    node()?;
    toolchain()?;
    if let Some(h) = std::env::var_os("LIMONITE_HOME") {
        let h = PathBuf::from(h);
        if !h.join("bin/limonite.mjs").exists() { return Err(format!("LIMONITE_HOME is {}, which has no bin/limonite.mjs", h.display())) }
        return Ok(h);
    }
    let host = host()?;
    let name = format!("limonite-{VERSION}-{host}");
    let dir = cache()?.join(VERSION);
    let home = dir.join(&name);
    if home.join("bundle.json").exists() { return Ok(home) }
    let want = BUNDLES.lines().filter(|l| !l.starts_with('#')).find_map(|l| { let (sum, file) = l.split_once("  ")?; (file.trim() == format!("{name}.tar.gz")).then(|| sum.to_string()) })
        .ok_or(format!("there is no prebuilt Limonite {VERSION} for {host}. Build it from source instead: github.com/lazuli-rs/limonite (README.md)"))?;
    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    let base = std::env::var("LIMONITE_DOWNLOAD").unwrap_or(format!("https://github.com/lazuli-rs/limonite/releases/download/v{VERSION}"));
    let part = dir.join(format!("{name}.tar.gz.part"));
    eprintln!("limonite: downloading Limonite {VERSION} for {host} (once), into {}", dir.display());
    fetch(&format!("{}/{name}.tar.gz", base.trim_end_matches('/')), &part)?;
    let sum = sha256(&part)?;
    if sum != want {
        let _ = std::fs::remove_file(&part);
        return Err(format!("the downloaded {name}.tar.gz (sha256 {sum}) is not the one this limonite {VERSION} expects ({want}): not used"));
    }
    // unpacked beside, then moved into place: a run cut short leaves no half bundle
    let tmp = dir.join(format!("{name}.unpacking"));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
    run(Command::new("tar").arg("-xzf").arg(&part).arg("-C").arg(&tmp), "tar")?;
    let _ = std::fs::remove_dir_all(&home);
    std::fs::rename(tmp.join(&name), &home).map_err(|e| format!("cannot move the bundle into {}: {e}", home.display()))?;
    let _ = std::fs::remove_dir_all(&tmp);
    let _ = std::fs::remove_file(&part);
    Ok(home)
}

/// The pinned nightly, with the wasm target (`#[wasm]` functions are built for real wasm)
fn toolchain() -> Result<(), String> {
    let list = Command::new("rustup").args(["toolchain", "list"]).output().map_err(|e| format!("cannot run rustup: {e} (Limonite installs its nightly through rustup: rustup.rs)"))?;
    let have = String::from_utf8_lossy(&list.stdout).lines().any(|l| l.starts_with(TOOLCHAIN));
    if !have {
        eprintln!("limonite: installing Rust {TOOLCHAIN} through rustup (once; only Limonite's builds use it)");
        run(Command::new("rustup").args(["toolchain", "install", TOOLCHAIN, "--profile", "minimal", "--target", "wasm32-unknown-unknown"]), "rustup")?;
        return Ok(());
    }
    let targets = Command::new("rustup").args(["target", "list", "--installed", "--toolchain", TOOLCHAIN]).output().map_err(|e| format!("cannot run rustup: {e}"))?;
    if !String::from_utf8_lossy(&targets.stdout).lines().any(|l| l.trim() == "wasm32-unknown-unknown") {
        eprintln!("limonite: adding wasm32-unknown-unknown to {TOOLCHAIN} (once)");
        run(Command::new("rustup").args(["target", "add", "wasm32-unknown-unknown", "--toolchain", TOOLCHAIN]), "rustup")?;
    }
    Ok(())
}

/// rustc's own host: the bundle's backend is loaded into it
fn host() -> Result<String, String> {
    let o = Command::new("rustc").arg(format!("+{TOOLCHAIN}")).arg("-vV").output().map_err(|e| format!("cannot run rustc: {e}"))?;
    String::from_utf8_lossy(&o.stdout).lines().find_map(|l| l.strip_prefix("host: ").map(str::to_string)).ok_or("rustc -vV names no host".to_string())
}

fn node() -> Result<(), String> {
    let o = Command::new("node").arg("--version").output().map_err(|_| "Limonite runs under Node.js 22 or later, and there is no node here: nodejs.org".to_string())?;
    let v = String::from_utf8_lossy(&o.stdout);
    let major: u32 = v.trim().trim_start_matches('v').split('.').next().and_then(|m| m.parse().ok()).unwrap_or(0);
    if major < 22 { return Err(format!("Limonite runs under Node.js 22 or later, and this node is {}", v.trim())) }
    Ok(())
}

fn cache() -> Result<PathBuf, String> {
    if let Some(d) = std::env::var_os("LIMONITE_CACHE") { return Ok(PathBuf::from(d)) }
    let home = || std::env::var_os("HOME").map(PathBuf::from).ok_or("no HOME: set LIMONITE_CACHE".to_string());
    Ok(if cfg!(target_os = "macos") { home()?.join("Library/Caches/limonite") }
       else if cfg!(windows) { PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or("no LOCALAPPDATA: set LIMONITE_CACHE")?).join("limonite") }
       else if let Some(x) = std::env::var_os("XDG_CACHE_HOME") { PathBuf::from(x).join("limonite") }
       else { home()?.join(".cache/limonite") })
}

fn run(c: &mut Command, what: &str) -> Result<(), String> {
    let s = c.status().map_err(|e| format!("cannot run {what}: {e}"))?;
    if s.success() { Ok(()) } else { Err(format!("{what} failed ({s})")) }
}

fn fetch(url: &str, to: &Path) -> Result<(), String> {
    let st = Command::new("curl").args(["-fL", "--retry", "2", "--progress-bar", "-o"]).arg(to).arg(url).status().map_err(|e| format!("cannot run curl: {e}"))?;
    if !st.success() { let _ = std::fs::remove_file(to); return Err(format!("could not download {url}")) }
    Ok(())
}

fn sha256(p: &Path) -> Result<String, String> {
    use sha2::{Digest, Sha256};
    let mut f = std::fs::File::open(p).map_err(|e| format!("cannot read {}: {e}", p.display()))?;
    let mut h = Sha256::new();
    std::io::copy(&mut f, &mut h).map_err(|e| format!("cannot read {}: {e}", p.display()))?;
    Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}