cat-fetch 0.1.1

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 8 independent crate repositories
//! Cargo operations (check, build, test, publish).

use std::path::Path;
use std::process::Command;

/// Run `cargo check` in a directory.
pub fn check(dir: &Path) -> Result<BuildOutput, String> {
    cargo(dir, &["check"])
}

/// Run `cargo build --release` in a directory.
pub fn build_release(dir: &Path) -> Result<BuildOutput, String> {
    cargo(dir, &["build", "--release"])
}

/// Run `cargo test --lib` in a directory.
pub fn test_lib(dir: &Path) -> Result<TestOutput, String> {
    cargo_test(dir, &["test", "--lib"])
}

/// Run `cargo test --tests` (integration tests) in a directory.
pub fn test_integration(dir: &Path) -> Result<TestOutput, String> {
    cargo_test(dir, &["test", "--tests"])
}

/// Run `cargo publish` in a directory. If dry_run is true, adds --dry-run.
pub fn publish(dir: &Path, dry_run: bool) -> Result<String, String> {
    let mut args = vec!["publish"];
    if dry_run {
        args.push("--dry-run");
    }
    let output = Command::new("cargo")
        .args(&args)
        .current_dir(dir)
        .output()
        .map_err(|e| format!("cargo publish failed: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(stderr.trim().to_string());
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout.trim().to_string())
}

/// Check if a crate version already exists on crates.io.
/// Uses curl to avoid external HTTP dependencies.
pub fn version_exists_on_crates_io(name: &str, version: &str) -> Result<bool, String> {
    let url = format!("https://crates.io/api/v1/crates/{}/{}", name, version);
    let output = Command::new("curl")
        .args(["-s", "-o", "/dev/null", "-w", "%{http_code}", &url])
        .output()
        .map_err(|e| format!("curl failed: {}", e))?;

    let code = String::from_utf8_lossy(&output.stdout);
    Ok(code.trim() == "200")
}

/// Read the version from a crate's Cargo.toml.
pub fn read_version(dir: &Path) -> Result<String, String> {
    let cargo_toml = dir.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml)
        .map_err(|e| format!("cannot read {}: {}", cargo_toml.display(), e))?;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("version") {
            if let Some(pos) = trimmed.find('"') {
                let rest = &trimmed[pos + 1..];
                if let Some(end) = rest.find('"') {
                    return Ok(rest[..end].to_string());
                }
            }
        }
    }
    Err("version field not found in Cargo.toml".into())
}

// ── internal helpers ──

fn cargo(dir: &Path, args: &[&str]) -> Result<BuildOutput, String> {
    let output = Command::new("cargo")
        .args(args)
        .current_dir(dir)
        .output()
        .map_err(|e| format!("cargo failed: {}", e))?;

    let stderr = String::from_utf8_lossy(&output.stderr);
    let success = output.status.success();

    // Count warnings
    let warnings = stderr.lines().filter(|l| l.contains("warning:")).count() as u32;

    Ok(BuildOutput {
        success,
        warnings,
        stderr: stderr.to_string(),
    })
}

fn cargo_test(dir: &Path, args: &[&str]) -> Result<TestOutput, String> {
    let output = Command::new("cargo")
        .args(args)
        .current_dir(dir)
        .output()
        .map_err(|e| format!("cargo test failed: {}", e))?;

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

    // Parse test results: "test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out"
    let mut passed = 0u32;
    let mut failed = 0u32;

    for line in stdout.lines().chain(stderr.lines()) {
        if line.contains("test result:") {
            if let Some(p) = extract_count(line, "passed") {
                passed += p;
            }
            if let Some(f) = extract_count(line, "failed") {
                failed += f;
            }
        }
    }

    Ok(TestOutput {
        success: output.status.success(),
        passed,
        failed,
        stdout: stdout.to_string(),
        stderr: stderr.to_string(),
    })
}

fn extract_count(line: &str, key: &str) -> Option<u32> {
    let pattern = format!("{};", key);
    if let Some(idx) = line.find(&pattern) {
        // Scan backward from the pattern to find the number
        let before = &line[..idx].trim();
        if let Some(last_space) = before.rfind(' ') {
            before[last_space + 1..].parse().ok()
        } else {
            None
        }
    } else {
        None
    }
}

#[derive(Debug)]
pub struct BuildOutput {
    pub success: bool,
    pub warnings: u32,
    #[allow(dead_code)]
    pub stderr: String,
}

#[derive(Debug)]
pub struct TestOutput {
    pub success: bool,
    pub passed: u32,
    pub failed: u32,
    #[allow(dead_code)]
    pub stdout: String,
    #[allow(dead_code)]
    pub stderr: String,
}