pets_tools 0.2.0

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 9 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);

    let (passed, failed) = parse_test_counts(&stdout, &stderr);

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

/// Parse `test result: ok. N passed; M failed; ...` lines from test output
/// into `(passed, failed)`. Sums across all result lines found.
pub fn parse_test_counts(stdout: &str, stderr: &str) -> (u32, u32) {
    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;
            }
        }
    }

    (passed, failed)
}

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,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn temp_dir(tag: &str) -> PathBuf {
        let mut dir = std::env::temp_dir();
        dir.push(format!("pets-cargo-test-{}-{}", tag, std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn parse_counts_basic() {
        let stdout = "running 3 tests\ntest a ... ok\ntest result: ok. 12 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out\n";
        assert_eq!(parse_test_counts(stdout, ""), (12, 2));
    }

    #[test]
    fn parse_counts_sums_multiple_sections() {
        let stdout = "test result: ok. 5 passed; 0 failed; 0 ignored;\ntest result: ok. 3 passed; 1 failed; 0 ignored;\n";
        assert_eq!(parse_test_counts(stdout, ""), (8, 1));
    }

    #[test]
    fn parse_counts_empty() {
        assert_eq!(parse_test_counts("", ""), (0, 0));
    }

    #[test]
    fn extract_count_parses_known_keys() {
        let line = "test result: ok. 12 passed; 0 failed;";
        assert_eq!(extract_count(line, "passed"), Some(12));
        assert_eq!(extract_count(line, "failed"), Some(0));
        assert_eq!(extract_count(line, "ignored"), None);
    }

    #[test]
    fn read_version_finds_field() {
        let dir = temp_dir("version");
        std::fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"x\"\nversion = \"1.2.3\"\n",
        )
        .unwrap();
        assert_eq!(read_version(&dir).unwrap(), "1.2.3");
        let _ = std::fs::remove_dir_all(&dir);
    }
}