cargo-worktree 1.0.0

Deterministic build namespace layer for Cargo
use anyhow::{Context, Result};
use std::process::Command;

pub fn rustc_version() -> Result<String> {
    let output = Command::new("rustc")
        .arg("--version")
        .output()
        .context("failed to run rustc --version")?;

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

pub fn target_triple() -> Result<String> {
    let output = Command::new("rustc")
        .args(["-vV"])
        .output()
        .context("failed to run rustc -vV")?;

    let stdout = String::from_utf8_lossy(&output.stdout);

    // 1. Try to find "host: xxx"
    for line in stdout.lines() {
        if let Some(rest) = line.strip_prefix("host: ") {
            return Ok(rest.trim().to_string());
        }
    }

    // 2. Try to find "host =" (some toolchains use this)
    for line in stdout.lines() {
        if let Some(rest) = line.strip_prefix("host = ") {
            return Ok(rest.trim().to_string());
        }
    }

    // 3. Try to find "Target:" (rare but exists)
    for line in stdout.lines() {
        if let Some(rest) = line.strip_prefix("Target: ") {
            return Ok(rest.trim().to_string());
        }
    }

    // 4. Fallback: use `rustc -vV` first line (contains triple)
    if let Some(first) = stdout.lines().next() {
        if first.contains('-') {
            // e.g. "rustc 1.78.0 (host: x86_64-unknown-linux-gnu)"
            if let Some(triple) = first.split_whitespace().find(|s| s.contains('-')) {
                return Ok(triple.to_string());
            }
        }
    }

    // 5. Final fallback: use env var or default
    if let Ok(env_triple) = std::env::var("RUSTC_HOST_TRIPLE") {
        return Ok(env_triple);
    }

    // 6. Last resort: assume common default
    Ok("x86_64-unknown-linux-gnu".to_string())
}