rsconstruct 0.9.178

Rust based fast build system
use crate::common::{make_executable, run_rsconstruct_with_env, setup_project_with_config};
use serde_json::Value;
use std::fs;

/// A `[dependencies] cargo` entry is a crate installed into the project's
/// tool directory, so that is where doctor looks: one there is ok, one
/// absent is reported missing, and the fix doctor names is `tool install
/// project`.
#[test]
fn doctor_checks_cargo_dependencies_in_the_project_tool_directory() {
    let temp_dir = setup_project_with_config(
        "[dependencies]\ncargo = [\"rsconstruct-fake-installed-crate\", \"rsconstruct-fake-missing-crate\"]\n\n[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n",
    );
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::create_dir_all(
        project_path.join(".rsconstruct/tools/pkgs/cargo/rsconstruct-fake-installed-crate@1.0.0"),
    )
    .unwrap();

    let output =
        run_rsconstruct_with_env(project_path, &["--json", "doctor"], &[("NO_COLOR", "1")]);
    let parsed: Value =
        serde_json::from_slice(&output.stdout).expect("doctor --json should emit valid JSON");
    let checks = parsed["checks"]
        .as_array()
        .expect("doctor --json should have a checks array");
    let find = |prefix: &str| {
        checks
            .iter()
            .find(|c| c["name"].as_str().is_some_and(|n| n.starts_with(prefix)))
            .unwrap_or_else(|| panic!("doctor should report {prefix}: {checks:?}"))
    };
    assert_eq!(find("rsconstruct-fake-installed-crate")["status"], "ok");
    let missing = find("rsconstruct-fake-missing-crate");
    assert_eq!(missing["status"], "fail");
    assert_eq!(missing["category"], "dependency");
    assert_eq!(missing["install_hint"], "rsconstruct tool install project");
}

/// A package.json dependency is a project-local install: doctor judges it
/// by the project's own node_modules, not by a global copy or a binary on
/// PATH, and the fix it names is `tool install project` (which runs `npm
/// ci`).
#[test]
fn doctor_checks_package_json_dependencies_in_node_modules() {
    let temp_dir =
        setup_project_with_config("[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n");
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(
        project_path.join("package.json"),
        r#"{"devDependencies": {"rsconstruct-fake-installed": "1.0.0", "rsconstruct-fake-missing": "1.0.0"}}"#,
    )
    .unwrap();
    fs::write(
        project_path.join("package-lock.json"),
        r#"{"lockfileVersion": 3, "packages": {"node_modules/rsconstruct-fake-installed": {"version": "1.0.0"}, "node_modules/rsconstruct-fake-missing": {"version": "1.0.0"}}}"#,
    )
    .unwrap();
    let installed = project_path.join("node_modules/rsconstruct-fake-installed");
    fs::create_dir_all(&installed).unwrap();
    fs::write(installed.join("package.json"), r#"{"version": "1.0.0"}"#).unwrap();

    let output =
        run_rsconstruct_with_env(project_path, &["--json", "doctor"], &[("NO_COLOR", "1")]);
    let parsed: Value =
        serde_json::from_slice(&output.stdout).expect("doctor --json should emit valid JSON");
    let checks = parsed["checks"]
        .as_array()
        .expect("doctor --json should have a checks array");
    let find = |prefix: &str| {
        checks
            .iter()
            .find(|c| c["name"].as_str().is_some_and(|n| n.starts_with(prefix)))
            .unwrap_or_else(|| panic!("doctor should report {prefix}"))
    };
    assert_eq!(find("rsconstruct-fake-installed")["status"], "ok");
    let missing = find("rsconstruct-fake-missing");
    assert_eq!(missing["status"], "fail");
    assert_eq!(missing["install_hint"], "rsconstruct tool install project");
}

/// The lock is what makes the install reproducible, so a manifest that
/// declares packages without one is an error, not a floating install.
#[test]
fn doctor_rejects_package_json_without_lock() {
    let temp_dir =
        setup_project_with_config("[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n");
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(
        project_path.join("package.json"),
        r#"{"devDependencies": {"stylelint": "latest"}}"#,
    )
    .unwrap();

    let output = run_rsconstruct_with_env(project_path, &["doctor"], &[("NO_COLOR", "1")]);
    assert!(
        !output.status.success(),
        "doctor should fail without a lock"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("package-lock.json"),
        "error should name the missing lock: {stderr}"
    );
}

/// The regression this guards: `doctor` used to probe `[dependencies] system`
/// entries with `which()`, treating packages as if they were tools. That
/// misreports in both directions — a binary-less package like aspell-en (a
/// dictionary) showed as missing even when installed, and any binary that
/// happens to share a package's name showed as installed without the package
/// being on. The probe must go through the package manager, the same one
/// `tool install machine` uses.
///
/// The test plants a fake binary on PATH whose name is not a real package.
/// The old which()-based doctor reported it ok; the package-manager probe
/// must report it missing. This assumes a supported package manager exists
/// (dpkg/rpm/pacman/brew) — on a machine without one, `tool install
/// machine` bails
/// anyway, so that environment is already unsupported.
#[test]
fn doctor_system_dependency_is_probed_as_package_not_tool() {
    let temp_dir = setup_project_with_config(
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n\n[dependencies]\nsystem = [\"rsconstruct-fake-system-package\"]\n",
    );
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();

    // A binary with the package's exact name, on PATH.
    let bin_dir = project_path.join("fakebin");
    fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("rsconstruct-fake-system-package");
    fs::write(&fake, "#!/bin/sh\nexit 0\n").unwrap();
    make_executable(&fake);
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").expect("PATH must be set")
    );

    let output = run_rsconstruct_with_env(
        project_path,
        &["--json", "doctor"],
        &[("NO_COLOR", "1"), ("PATH", &path)],
    );
    assert!(
        output.status.success(),
        "doctor failed to run: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let parsed: Value =
        serde_json::from_slice(&output.stdout).expect("doctor --json should emit valid JSON");
    let checks = parsed["checks"]
        .as_array()
        .expect("doctor --json should have a checks array");
    let check = checks
        .iter()
        .find(|c| {
            c["name"]
                .as_str()
                .is_some_and(|n| n.starts_with("rsconstruct-fake-system-package"))
        })
        .expect("doctor should report on the declared system dependency");

    assert_eq!(
        check["status"], "fail",
        "a fake binary on PATH is not an installed system package; doctor must ask \
         the package manager, not which(). Check was: {check}",
    );
    assert_eq!(check["category"], "dependency");
    assert_eq!(
        check["install_hint"], "rsconstruct tool install machine",
        "the fix for a missing system dependency is a machine install",
    );
}

/// `doctor` checks the tools of the enabled processors. A stanza with
/// `enabled = false` is kept precisely so its tool need not be installed, so
/// its absence is not a finding; the same stanza enabled is.
#[test]
fn doctor_skips_tools_of_disabled_processors() {
    let config = |enabled: &str| {
        format!(
            "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n\n[processor.checker.script]\ncommand = \"definitely-not-a-real-tool-xyz\"\nsrc_dirs = [\"src\"]\nenabled = {enabled}\n"
        )
    };
    let temp_dir = setup_project_with_config(&config("false"));
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();

    let tool_checks = |output: std::process::Output| -> Vec<Value> {
        let parsed: Value =
            serde_json::from_slice(&output.stdout).expect("doctor --json should emit valid JSON");
        parsed["checks"]
            .as_array()
            .expect("doctor --json should have a checks array")
            .iter()
            .filter(|c| {
                c["name"]
                    .as_str()
                    .is_some_and(|n| n.starts_with("definitely-not-a-real-tool-xyz"))
            })
            .cloned()
            .collect()
    };

    let output =
        run_rsconstruct_with_env(project_path, &["--json", "doctor"], &[("NO_COLOR", "1")]);
    let checks = tool_checks(output);
    assert!(
        checks.is_empty(),
        "doctor probed a disabled processor's tool: {checks:?}"
    );

    // Control: enabled, the missing tool is a failed check.
    fs::write(project_path.join("rsconstruct.toml"), config("true")).unwrap();
    let output =
        run_rsconstruct_with_env(project_path, &["--json", "doctor"], &[("NO_COLOR", "1")]);
    let checks = tool_checks(output);
    assert_eq!(checks.len(), 1, "{checks:?}");
    assert_eq!(checks[0]["status"], "fail");
    assert_eq!(checks[0]["category"], "tool");
}

/// Python and npm dependencies are judged the way `tool check` judges them,
/// not by the exit status of a package manager:
///
/// - a Python package (here pinned by uv.lock) is asked of the interpreter
///   (`importlib.metadata`), since a uv-managed venv has no pip at all.
///   The fake `pip` here claims every package is installed; the
///   interpreter knows the pinned name is not;
/// - an `[dependencies].npm` entry is installed into the project's tool
///   directory, so it is looked for there. The fake `npm` lists one package
///   globally and claims success for any other query; a global copy does
///   not count, only the one in the project does.
#[test]
fn doctor_probes_pip_through_python_and_npm_in_the_project() {
    let temp_dir = setup_project_with_config(
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n\n[dependencies]\nnpm = [\"rsconstruct-fake-global-pkg\", \"rsconstruct-fake-project-pkg\"]\n",
    );
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(
        project_path.join("uv.lock"),
        "version = 1\n\n[[package]]\nname = \"rsconstruct-fake-missing-dist\"\nversion = \"1.0.0\"\nsource = { registry = \"https://pypi.org/simple\" }\n",
    )
    .unwrap();
    fs::create_dir_all(
        project_path.join(".rsconstruct/tools/pkgs/npm/rsconstruct-fake-project-pkg@1.0.0"),
    )
    .unwrap();

    let bin_dir = project_path.join("fakebin");
    fs::create_dir_all(&bin_dir).unwrap();
    let pip = bin_dir.join("pip");
    fs::write(&pip, "#!/bin/sh\nexit 0\n").unwrap();
    make_executable(&pip);
    let npm = bin_dir.join("npm");
    fs::write(
        &npm,
        "#!/bin/sh\ncase \" $* \" in\n  *\" -g \"*) printf '%s' '{\"dependencies\":{\"rsconstruct-fake-global-pkg\":{\"version\":\"1.0.0\"}}}' ;;\nesac\nexit 0\n",
    )
    .unwrap();
    make_executable(&npm);
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").expect("PATH must be set")
    );

    let output = run_rsconstruct_with_env(
        project_path,
        &["--json", "doctor"],
        &[("NO_COLOR", "1"), ("PATH", &path)],
    );
    assert!(
        output.status.success(),
        "doctor failed to run: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let parsed: Value =
        serde_json::from_slice(&output.stdout).expect("doctor --json should emit valid JSON");
    let checks = parsed["checks"]
        .as_array()
        .expect("doctor --json should have a checks array");
    let find = |prefix: &str| {
        checks
            .iter()
            .find(|c| c["name"].as_str().is_some_and(|n| n.starts_with(prefix)))
            .unwrap_or_else(|| panic!("doctor should report {prefix}: {checks:?}"))
    };

    let pip_check = find("rsconstruct-fake-missing-dist");
    assert_eq!(
        pip_check["status"], "fail",
        "a package the interpreter cannot import is not installed, whatever `pip` says: {pip_check}"
    );
    assert_eq!(pip_check["detail"], "pip");

    assert_eq!(find("rsconstruct-fake-project-pkg")["status"], "ok");
    let global = find("rsconstruct-fake-global-pkg");
    assert_eq!(
        global["status"], "fail",
        "a package only in the global tree is not installed for the project: {global}"
    );
    assert_eq!(global["install_hint"], "rsconstruct tool install project");
}