instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! Run install.sh against a local fake release (a directory with a tgz and SHA256SUMS).
#![cfg(unix)]

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

const TAG: &str = "v9.9.9";

fn target() -> &'static str {
    match (std::env::consts::OS, std::env::consts::ARCH) {
        ("linux", "x86_64") => "x86_64-unknown-linux-gnu",
        ("linux", "aarch64") => "aarch64-unknown-linux-gnu",
        ("macos", "x86_64") => "x86_64-apple-darwin",
        ("macos", "aarch64") => "aarch64-apple-darwin",
        other => panic!("install.sh does not support {other:?}"),
    }
}

fn sh(args: &[&str], dir: &Path) {
    let status = Command::new(args[0])
        .args(&args[1..])
        .current_dir(dir)
        .status()
        .unwrap();
    assert!(status.success(), "{args:?} failed");
}

fn sha256(file: &Path) -> String {
    let out = if Command::new("sha256sum").arg("--version").output().is_ok() {
        Command::new("sha256sum").arg(file).output().unwrap()
    } else {
        Command::new("shasum").args(["-a", "256"]).arg(file).output().unwrap()
    };
    String::from_utf8(out.stdout).unwrap().split_whitespace().next().unwrap().to_owned()
}

/// A scratch directory under cargo's target dir, removed on drop.
struct Scratch(PathBuf);
impl Scratch {
    fn new(name: &str) -> Self {
        let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
            .join(format!("install-{name}-{}-{}", std::process::id(), uniq()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        Self(dir)
    }
}
impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

/// Build release/ with the real instinct binary for this target, a decoy for another target,
/// and a SHA256SUMS that lists both. Returns the release dir.
fn fake_release(root: &Path) -> PathBuf {
    let release = root.join("release");
    let stage = root.join("stage");
    fs::create_dir_all(&release).unwrap();
    fs::create_dir_all(&stage).unwrap();
    fs::copy(env!("CARGO_BIN_EXE_instinct"), stage.join("instinct")).unwrap();
    fs::set_permissions(stage.join("instinct"), fs::Permissions::from_mode(0o755)).unwrap();
    fs::write(stage.join("LICENSE"), "license\n").unwrap();
    fs::write(stage.join("NOTICE"), "notice\n").unwrap();

    let asset = format!("instinct-cli-{}-{TAG}.tgz", target());
    sh(
        &["tar", "-czf", release.join(&asset).to_str().unwrap(), "instinct", "LICENSE", "NOTICE"],
        &stage,
    );
    // A decoy for a target this machine is not: picking it would fail the checksum or the run.
    let decoy = if target().starts_with("x86_64") {
        format!("instinct-cli-aarch64-unknown-linux-gnu-{TAG}.tgz")
    } else {
        format!("instinct-cli-x86_64-unknown-linux-gnu-{TAG}.tgz")
    };
    fs::write(release.join(&decoy), "not an archive").unwrap();

    let sums = format!(
        "{}  {asset}\n{}  {decoy}\n",
        sha256(&release.join(&asset)),
        sha256(&release.join(&decoy))
    );
    fs::write(release.join("SHA256SUMS"), sums).unwrap();
    release
}

fn install(root: &Path, release: &Path, extra_path: Option<&Path>) -> (Output, PathBuf) {
    let dest = root.join("bin");
    let home = root.join("home");
    fs::create_dir_all(&home).unwrap();
    let mut path = std::env::var("PATH").unwrap();
    if let Some(extra) = extra_path {
        path = format!("{}:{path}", extra.display());
    }
    let out = Command::new("sh")
        .arg(concat!(env!("CARGO_MANIFEST_DIR"), "/install.sh"))
        .env("HOME", &home)
        .env("PATH", path)
        .env("TMPDIR", root)
        .env("INSTINCT_VERSION", TAG)
        .env("INSTINCT_INSTALL_DIR", &dest)
        .env("INSTINCT_RELEASE_BASE", format!("file://{}", release.display()))
        .output()
        .unwrap();
    (out, dest)
}

fn text(out: &Output) -> String {
    format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    )
}

#[test]
fn good_checksum_installs_the_matching_asset_and_it_runs() {
    let scratch = Scratch::new("good");
    let release = fake_release(&scratch.0);
    let (out, dest) = install(&scratch.0, &release, None);
    let said = text(&out);
    assert!(out.status.success(), "{said}");
    assert!(said.contains(target()), "{said}");
    assert!(said.contains("Checksum OK"), "{said}");
    assert!(said.contains(&format!("Installed {}/instinct", dest.display())), "{said}");
    assert!(said.contains("export PATH="), "dir is not on PATH, expected the export line: {said}");
    assert!(said.contains("instinct starter --apply"), "{said}");

    let version = Command::new(dest.join("instinct")).arg("--version").output().unwrap();
    assert!(version.status.success(), "{}", text(&version));
    assert!(text(&version).contains("instinct"), "{}", text(&version));

    // Nothing is left behind in the install dir or the temp dir.
    let names: Vec<_> = fs::read_dir(&dest).unwrap().map(|e| e.unwrap().file_name()).collect();
    assert_eq!(names, ["instinct"]);
    let leftovers = fs::read_dir(&scratch.0)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("instinct-install."))
        .count();
    assert_eq!(leftovers, 0, "temp dir was not cleaned up");
}

#[test]
fn install_dir_on_path_is_reported_without_an_export_line() {
    let scratch = Scratch::new("onpath");
    let release = fake_release(&scratch.0);
    let dest = scratch.0.join("bin");
    let (out, _) = install(&scratch.0, &release, Some(&dest));
    let said = text(&out);
    assert!(out.status.success(), "{said}");
    assert!(said.contains("is on your PATH"), "{said}");
    assert!(!said.contains("export PATH="), "{said}");
}

#[test]
fn bad_checksum_refuses_and_installs_nothing() {
    let scratch = Scratch::new("bad");
    let release = fake_release(&scratch.0);
    let asset = format!("instinct-cli-{}-{TAG}.tgz", target());
    let zeros = "0".repeat(64);
    fs::write(release.join("SHA256SUMS"), format!("{zeros}  {asset}\n")).unwrap();
    let (out, dest) = install(&scratch.0, &release, None);
    assert!(!out.status.success());
    assert!(text(&out).contains("checksum mismatch"), "{}", text(&out));
    assert!(!dest.join("instinct").exists());
}

#[test]
fn missing_checksum_line_refuses() {
    let scratch = Scratch::new("missing");
    let release = fake_release(&scratch.0);
    fs::write(release.join("SHA256SUMS"), "").unwrap();
    let (out, dest) = install(&scratch.0, &release, None);
    assert!(!out.status.success());
    assert!(text(&out).contains("no line for"), "{}", text(&out));
    assert!(!dest.join("instinct").exists());
}

#[test]
fn unknown_os_refuses_and_points_to_cargo() {
    let scratch = Scratch::new("os");
    let release = fake_release(&scratch.0);
    let shim = scratch.0.join("shim");
    fs::create_dir_all(&shim).unwrap();
    let uname = shim.join("uname");
    fs::write(&uname, "#!/bin/sh\ncase \"$1\" in -m) echo x86_64 ;; *) echo Plan9 ;; esac\n").unwrap();
    fs::set_permissions(&uname, fs::Permissions::from_mode(0o755)).unwrap();
    let (out, dest) = install(&scratch.0, &release, Some(&shim));
    assert!(!out.status.success());
    let said = text(&out);
    assert!(said.contains("unsupported operating system: Plan9"), "{said}");
    assert!(said.contains("cargo install --locked instinct-cli"), "{said}");
    assert!(!dest.exists());
}

#[test]
fn unknown_arch_refuses() {
    let scratch = Scratch::new("arch");
    let release = fake_release(&scratch.0);
    let shim = scratch.0.join("shim");
    fs::create_dir_all(&shim).unwrap();
    let uname = shim.join("uname");
    fs::write(&uname, "#!/bin/sh\ncase \"$1\" in -m) echo riscv64 ;; *) echo Linux ;; esac\n").unwrap();
    fs::set_permissions(&uname, fs::Permissions::from_mode(0o755)).unwrap();
    let (out, _) = install(&scratch.0, &release, Some(&shim));
    assert!(!out.status.success());
    assert!(text(&out).contains("unsupported CPU architecture: riscv64"), "{}", text(&out));
}

/// A number no other call in this test process has seen, so parallel tests never share a folder.
fn uniq() -> usize {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}