pets_tools 0.2.0

MusKitty multi-repo source management CLI — one command to clone, build, test, push, and publish 9 independent crate repositories
//! `pets run <project> <script> [args...]` — run a user-defined script.
//!
//! Scripts come from `[project.commands]` (project root) or `[[repos]].commands`
//! (run with `--repo <name>`), npm `package.json` `scripts` style. The core
//! command set (clone/pull/build/...) stays fixed; these are supplementary.

use crate::config::Config;
use crate::ui;
use crate::RunArgs;
use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, ExitStatus};

pub fn run(config: Config, args: &RunArgs) {
    let (dir, script, env_repo) = match &args.repo {
        Some(name) => {
            let repo = config.repo_by_name(name).unwrap_or_else(|| {
                ui::error(&format!("unknown repo '{}'", name));
                std::process::exit(1);
            });
            let cmd = repo
                .commands
                .get(&args.script)
                .or_else(|| config.commands.get(&args.script))
                .unwrap_or_else(|| {
                    missing_script(&format!("repo '{}'", name), &args.script, &repo.commands)
                });
            (repo.abs_dir.clone(), cmd.clone(), name.clone())
        }
        None => {
            let cmd = config.commands.get(&args.script).unwrap_or_else(|| {
                missing_script(&config.project_name, &args.script, &config.commands)
            });
            (config.root.clone(), cmd.clone(), String::new())
        }
    };

    // npm-style trailing args are appended to the script string.
    let mut full = script;
    if !args.args.is_empty() {
        full.push(' ');
        full.push_str(&args.args.join(" "));
    }
    if args.verbose {
        ui::info(&format!("[{}] $ {}", dir.display(), full));
    }

    let extra = [
        ("PETS_PROJECT", config.project_name.as_str()),
        ("PETS_ROOT", config.root.to_str().unwrap_or("")),
        ("PETS_SCRIPT", args.script.as_str()),
        ("PETS_REPO", env_repo.as_str()),
    ];

    let status = run_shell(&dir, &full, &extra);
    if !status.success() {
        std::process::exit(status.code().unwrap_or(1));
    }
}

/// Print an error for a missing script and exit(1).
fn missing_script(scope: &str, script: &str, available: &BTreeMap<String, String>) -> ! {
    ui::error(&format!("no script '{}' for {}", script, scope));
    if available.is_empty() {
        ui::info("  (no scripts defined)");
    } else {
        ui::info(&format!(
            "available: {}",
            available.keys().cloned().collect::<Vec<_>>().join(", ")
        ));
    }
    std::process::exit(1);
}

/// Run a shell command in `dir`, inheriting stdio. Returns the exit status.
pub fn run_shell(dir: &Path, full: &str, extra_env: &[(&str, &str)]) -> ExitStatus {
    let mut cmd = shell_command(full);
    cmd.current_dir(dir);
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.status().unwrap_or_else(|e| {
        ui::error(&format!("failed to run shell command: {}", e));
        std::process::exit(1);
    })
}

/// Run a shell command in `dir`, capturing stdout/stderr.
pub fn run_shell_capture(
    dir: &Path,
    full: &str,
    extra_env: &[(&str, &str)],
) -> Result<(ExitStatus, String, String), String> {
    let mut cmd = shell_command(full);
    cmd.current_dir(dir);
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    let output = cmd
        .output()
        .map_err(|e| format!("failed to run shell command: {}", e))?;
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    Ok((output.status, stdout, stderr))
}

/// Build the platform shell command. The full command string is passed as a
/// single argument so quoting inside scripts is preserved.
#[cfg(windows)]
fn shell_command(full: &str) -> Command {
    let mut c = Command::new("cmd");
    c.arg("/C").arg(full);
    c
}

#[cfg(not(windows))]
fn shell_command(full: &str) -> Command {
    let mut c = Command::new("sh");
    c.arg("-c").arg(full);
    c
}

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

    #[test]
    fn run_shell_capture_captures_echo() {
        let dir = std::env::temp_dir();
        let (status, stdout, _stderr) = run_shell_capture(&dir, "echo pets-run-ok", &[]).unwrap();
        assert!(status.success());
        assert!(stdout.contains("pets-run-ok"));
    }

    #[test]
    fn run_shell_capture_propagates_env() {
        let dir = std::env::temp_dir();
        #[cfg(windows)]
        let cmd = "echo %PETS_SCRIPT%";
        #[cfg(not(windows))]
        let cmd = "echo $PETS_SCRIPT";
        let (status, stdout, _stderr) =
            run_shell_capture(&dir, cmd, &[("PETS_SCRIPT", "hello")]).unwrap();
        assert!(status.success());
        assert!(stdout.contains("hello"));
    }

    #[test]
    fn run_shell_capture_reports_exit_code() {
        let dir = std::env::temp_dir();
        let (status, _stdout, _stderr) = run_shell_capture(&dir, "exit 3", &[]).unwrap();
        assert_eq!(status.code(), Some(3));
    }

    #[test]
    fn run_shell_inherits_success() {
        let dir = std::env::temp_dir();
        assert!(run_shell(&dir, "exit 0", &[]).success());
    }
}