repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

xtask/src/main.rs

Raw
File outline
#![forbid(unsafe_code)]
#![warn(missing_docs)]

//! Cargo-only Smith project automation.
//!
//! Gate tools follow one rule: install immutable artifacts or pinned
//! versions with `--locked`, never live dependency resolution, so upstream
//! releases cannot break a gate without a change in this repository.

use std::{
    env,
    ffi::OsString,
    fs,
    io::{BufRead, Write},
    path::{Path, PathBuf},
    process::Command,
    process::ExitCode,
};

const HELP: &str = concat!(
    "usage: cargo x <check|lint|fmt|test|doc|arch|mutants [args...]|audit|ci|release|bootstrap>\n",
    "       cargo x dev [args...]   build and launch the dev smith binary\n",
);

/// Version of `cargo-nextest` used by the test gate.
const NEXTEST_VERSION: &str = "0.9.146";

/// Version of `cargo-binstall` used to install `cargo-nextest`.
const BINSTALL_VERSION: &str = "1.23.0";
const MACHETE_VERSION: &str = "0.9.2";
const DENY_VERSION: &str = "0.20.2";
const AUDIT_VERSION: &str = "0.22.2";
const MUTANTS_VERSION: &str = "27.1.0";
const CRATES: &[&str] = &[
    "smith",
    "smith-core",
    "smith-ai",
    "smith-ui",
    "smith-tui",
    "smith-rpc",
    "smith-harness",
    "smith-cli",
    "xtask",
];

fn main() -> ExitCode {
    let mut args = env::args_os();
    let _program = args.next();
    let Some(command) = args.next() else {
        return fail(HELP);
    };
    let rest: Vec<OsString> = args.collect();
    if command.to_str() == Some("dev") {
        return dev(&rest);
    }
    match command.to_str() {
        Some("check") => check(&rest),
        Some("lint") => lint(&rest),
        Some("fmt") => cargo_fmt_step(&rest),
        Some("test") => cargo_nextest(&rest),
        Some("doc") => cargo_doc(&rest),
        Some("arch") => arch(&rest),
        Some("mutants") => cargo_mutants(&rest),
        Some("audit") => audit(&rest),
        Some("ci") => ci(&rest),
        Some("release") => release(&rest),
        Some("bootstrap") => bootstrap(&rest),
        _ => fail(HELP),
    }
}

fn check(extra: &[OsString]) -> ExitCode {
    sequence(
        &[
            ensure_mold,
            cargo_fmt_step,
            cargo_clippy,
            arch,
            cargo_nextest,
            cargo_doc,
            cargo_machete,
        ],
        extra,
    )
}

type Step = fn(&[OsString]) -> ExitCode;

fn sequence(steps: &[Step], extra: &[OsString]) -> ExitCode {
    for step in steps {
        let code = step(extra);
        if code != ExitCode::SUCCESS {
            return code;
        }
    }
    ExitCode::SUCCESS
}

/// Append passthrough args; package scoping overrides workspace defaults,
/// so `-p crate` drops the `--workspace` flag rather than conflicting.
fn scoped(base: &[&str], extra: &[OsString]) -> Vec<OsString> {
    let mut args: Vec<OsString> = base.iter().map(OsString::from).collect();
    let narrows = extra.iter().any(|arg| {
        arg == "-p" || arg == "--package" || arg.to_string_lossy().starts_with("--package=")
    });
    if narrows {
        args.retain(|arg| arg != "--workspace");
    }
    args.extend_from_slice(extra);
    args
}

fn lint(extra: &[OsString]) -> ExitCode {
    sequence(&[cargo_fmt_step, cargo_clippy], extra)
}

/// Audit gates read the lockfile; scoping does not apply.
fn audit(extra: &[OsString]) -> ExitCode {
    if !extra.is_empty() {
        return fail("audit is lockfile-wide and admits no scoping\n");
    }
    sequence(
        &[install_deny, install_audit, cargo_deny, cargo_audit],
        extra,
    )
}

/// The merge-gate pipeline: every gate, machine context, fixed order.
/// Passthrough is rejected so workflows cannot drift from the definition.
fn ci(extra: &[OsString]) -> ExitCode {
    if !extra.is_empty() {
        return fail("ci is a fixed pipeline and admits no scoping\n");
    }
    sequence(&[bootstrap, check, audit], extra)
}

/// Release gates are defined by the release-readiness plan; the command
/// exists so workflows reference a stable name today.
fn release(extra: &[OsString]) -> ExitCode {
    let _ = extra;
    fail("release gates are not defined yet; see SMH-PLAN-RELS0001\n")
}

/// Mutation testing runs on demand, never in the blocking check chain.
///
/// Split of concerns, kept CI-sensible:
/// - `.cargo/mutants.toml` owns tree properties (scope, tool, profiles)
///   so bare `cargo mutants` behaves identically anywhere.
/// - this step owns run context: disk-backed scratch (system tmpfs is
///   16G RAM and tree copies crawl the machine), a modest default job
///   count overridable through `CARGO_MUTANTS_JOBS`, and a skipped
///   baseline because `cargo x check` owns test verification.
fn cargo_mutants(extra: &[OsString]) -> ExitCode {
    let installed = tool_present_bin("cargo-mutants", MUTANTS_VERSION, || {
        cargo(&[
            "binstall",
            "--no-confirm",
            &format!("cargo-mutants@{MUTANTS_VERSION}"),
        ])
    });
    if installed != ExitCode::SUCCESS {
        return installed;
    }
    let scratch = target_dir().join("mutants-tmp");
    if std::fs::create_dir_all(&scratch).is_err() {
        return fail("cannot create target/mutants-tmp\n");
    }
    let jobs = std::env::var("CARGO_MUTANTS_JOBS").unwrap_or_else(|_| "1".to_string());
    // `cargo x mutants -- -f x` and `cargo x mutants -f x` are equivalent:
    // a leading separator is stripped so cargo-run habits cannot turn
    // scope flags into stray nextest test filters.
    let extra: Vec<OsString> = if extra.first().is_some_and(|arg| arg == "--") {
        extra[1..].to_vec()
    } else {
        extra.to_vec()
    };
    let mut command = Command::new("cargo-mutants");
    command.env("TMPDIR", &scratch).args([
        "mutants",
        "--jobs",
        &jobs,
        "--baseline",
        "skip",
        "--no-shuffle",
    ]);
    // Passthrough args come last and override the defaults above.
    command.args(extra);
    match command.status() {
        Ok(status) if status.success() => ExitCode::SUCCESS,
        Ok(status) if status.code() == Some(2) => fail(
            "missed mutants: tests did not catch everything (see target/mutants.out/missed.txt)\n",
        ),
        Ok(status) => fail(&format!("cargo mutants exited with {status}\n")),
        Err(error) => fail(&format!("failed to run cargo mutants: {error}\n")),
    }
}

fn cargo_fmt_step(extra: &[OsString]) -> ExitCode {
    let args = scoped(&["fmt", "--check"], extra);
    run_os("cargo", &args)
}

fn cargo_clippy(extra: &[OsString]) -> ExitCode {
    sequence(&[clippy_prod, clippy_tests, clippy_guests], extra)
}

/// Production targets carry the full strict gate.
fn clippy_prod(extra: &[OsString]) -> ExitCode {
    clippy_phase(&["--lib", "--bins"], &[], extra)
}

/// Test targets may assert, panic, and print: outcomes are the point.
/// Pedantic relaxes too; correctness lints stay on so test quality is
/// still policed.
fn clippy_tests(extra: &[OsString]) -> ExitCode {
    clippy_phase(
        &["--tests"],
        &[
            "-A",
            "clippy::unwrap_used",
            "-A",
            "clippy::expect_used",
            "-A",
            "clippy::panic",
            "-A",
            "clippy::todo",
            "-A",
            "clippy::unimplemented",
            "-A",
            "clippy::print_stdout",
            "-A",
            "clippy::print_stderr",
            "-A",
            "clippy::dbg_macro",
            "-A",
            "clippy::pedantic",
        ],
        extra,
    )
}

/// Guest crates stay strict, cross-checked on their wasm target; the
/// crate-level expectations on generated surfaces carry the exceptions.
fn clippy_guests(extra: &[OsString]) -> ExitCode {
    if extra.iter().any(|arg| arg == "-p" || arg == "--package") {
        return ExitCode::SUCCESS;
    }
    clippy_phase(
        &[
            "-p",
            "smith-plugin-echo",
            "--target",
            "wasm32-wasip2",
            "--lib",
        ],
        &[],
        extra,
    )
}

fn clippy_phase(targets: &[&str], lint_args: &[&str], extra: &[OsString]) -> ExitCode {
    let mut base = vec!["clippy", "--locked"];
    base.extend_from_slice(targets);
    base.push("--all-features");
    let args = scoped(&base, extra);
    let mut command = Command::new("cargo");
    command.env("CLIPPY_CONF_DIR", ".config").args(&args);
    if !lint_args.is_empty() {
        command.arg("--");
        command.args(lint_args);
    }
    match command.status() {
        Ok(status) if status.success() => ExitCode::SUCCESS,
        Ok(status) => fail(&format!("cargo clippy exited with {status}\n")),
        Err(error) => fail(&format!("failed to run cargo clippy: {error}\n")),
    }
}

fn cargo_nextest(extra: &[OsString]) -> ExitCode {
    let args = scoped(&["--locked", "--workspace", "--all-features"], extra);
    nextest_run_os(&args)
}

/// nextest has no warning-deny flag, so config-drift warnings are turned into
/// a gate failure by scanning its stderr.
fn nextest_run_os(args: &[OsString]) -> ExitCode {
    let mut child = match Command::new("cargo")
        .arg("nextest")
        .arg("run")
        .args(args)
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(error) => return fail(&format!("failed to run cargo nextest: {error}\n")),
    };
    let mut warned = false;
    if let Some(stderr) = child.stderr.take() {
        let reader = std::io::BufReader::new(stderr);
        for line in reader.lines() {
            let Ok(line) = line else {
                break;
            };
            if line.contains("warning: in config file") {
                warned = true;
            }
            let _ = std::io::stderr().write_all(format!("{line}\n").as_bytes());
        }
    }
    match child.wait() {
        Ok(status) if status.success() && !warned => ExitCode::SUCCESS,
        Ok(status) if status.success() => fail("nextest produced config file warnings\n"),
        Ok(status) => fail(&format!(
            "cargo exited with exit status: {}\n",
            status.code().unwrap_or_default()
        )),
        Err(error) => fail(&format!("failed to wait for cargo nextest: {error}\n")),
    }
}

fn cargo_machete(_extra: &[OsString]) -> ExitCode {
    let installed = tool_present_bin("cargo-machete", MACHETE_VERSION, || {
        cargo(&[
            "install",
            "--locked",
            "--version",
            MACHETE_VERSION,
            "cargo-machete",
        ])
    });
    if installed != ExitCode::SUCCESS {
        return installed;
    }
    run("cargo-machete", &[])
}

/// mold is a build prerequisite on linux-gnu `x86_64`; xtask verifies it, the
/// system package manager installs it.
fn ensure_mold(_extra: &[OsString]) -> ExitCode {
    if cfg!(all(
        target_arch = "x86_64",
        target_os = "linux",
        target_env = "gnu"
    )) {
        match Command::new("mold")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
        {
            Ok(status) if status.success() => ExitCode::SUCCESS,
            _ => fail(
                "mold linker missing: install it with the system package manager (e.g. pacman -S mold)\n",
            ),
        }
    } else {
        ExitCode::SUCCESS
    }
}

/// Install the external gate tools that Cargo cannot ship.
///
/// `cargo-nextest` arrives as a prebuilt binary through `cargo-binstall`.
/// The step is idempotent.
/// Installs tools; scoping does not apply.
fn bootstrap(extra: &[OsString]) -> ExitCode {
    if !extra.is_empty() {
        return fail("bootstrap installs tools and admits no scoping\n");
    }
    let steps: [Step; 6] = [
        install_binstall,
        install_nextest,
        install_machete,
        install_deny,
        install_audit,
        install_mutants,
    ];
    sequence(&steps, extra)
}

fn install_machete(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-machete", MACHETE_VERSION, || {
        cargo(&[
            "install",
            "--locked",
            "--version",
            MACHETE_VERSION,
            "cargo-machete",
        ])
    })
}

fn install_deny(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-deny", DENY_VERSION, || {
        cargo(&[
            "binstall",
            "--no-confirm",
            &format!("cargo-deny@{DENY_VERSION}"),
        ])
    })
}

fn install_audit(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-audit", AUDIT_VERSION, || {
        cargo(&[
            "binstall",
            "--no-confirm",
            &format!("cargo-audit@{AUDIT_VERSION}"),
        ])
    })
}

fn install_mutants(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-mutants", MUTANTS_VERSION, || {
        cargo(&[
            "binstall",
            "--no-confirm",
            &format!("cargo-mutants@{MUTANTS_VERSION}"),
        ])
    })
}

fn install_binstall(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-binstall", BINSTALL_VERSION, || {
        cargo(&[
            "install",
            "cargo-binstall",
            "--version",
            BINSTALL_VERSION,
            // Freeze binstall's own dependency graph for the same reason
            // crates.io drift cannot break the gate.
            "--locked",
        ])
    })
}

fn install_nextest(_extra: &[OsString]) -> ExitCode {
    tool_present_bin("cargo-nextest", NEXTEST_VERSION, || {
        cargo(&[
            "binstall",
            &format!("cargo-nextest@{NEXTEST_VERSION}"),
            "--no-confirm",
        ])
    })
}

/// Run `probe` with cargo; when it fails, run `install` and return its code.
/// The probe pins the tool so a stale unpinned binary is replaced.
/// Probes an external binary directly and enforces the pinned version;
/// mismatch or absence runs the installer, so drift self-heals to the pin.
fn tool_present_bin(program: &str, version: &str, install: impl FnOnce() -> ExitCode) -> ExitCode {
    let probe = Command::new(program)
        .arg("--version")
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output();
    let pinned = probe.is_ok_and(|output| {
        output.status.success() && String::from_utf8_lossy(&output.stdout).contains(version)
    });
    if pinned { ExitCode::SUCCESS } else { install() }
}

fn cargo_doc(extra: &[OsString]) -> ExitCode {
    let args = scoped(&["doc", "--locked", "--workspace", "--no-deps"], extra);
    run_os("cargo", &args)
}

fn cargo_deny(_extra: &[OsString]) -> ExitCode {
    cargo(&["deny", "--config", ".config/deny.toml", "check"])
}

fn cargo_audit(_extra: &[OsString]) -> ExitCode {
    cargo(&["audit", "--deny", "warnings"])
}

fn cargo(args: &[&str]) -> ExitCode {
    run("cargo", args)
}

/// Builds the CLI, then launches it against an isolated dev home.
fn dev(args: &[OsString]) -> ExitCode {
    let code = cargo(&["build", "--locked", "-p", "smith-cli", "--bin", "smith"]);
    if code != ExitCode::SUCCESS {
        return code;
    }
    let target = target_dir();
    let binary = target.join("debug").join(binary_name());
    if !binary.is_file() {
        return fail(&format!("missing dev binary: {}\n", binary.display()));
    }
    let home = target.join("dev-home");
    let mut command = Command::new(&binary);
    for (key, dir) in dev_home_dirs() {
        let path = home.join(dir);
        if let Err(error) = fs::create_dir_all(&path) {
            return fail(&format!("failed to create {}: {error}\n", path.display()));
        }
        command.env(key, &path);
    }
    command.args(args);
    note(&format!(
        "running {} (home {})\n",
        binary.display(),
        home.display()
    ));
    match command.status() {
        Ok(status) => match status.code() {
            Some(0) => ExitCode::SUCCESS,
            Some(value) => ExitCode::from(u8::try_from(value).unwrap_or(1)),
            None => fail("smith terminated by signal\n"),
        },
        Err(error) => fail(&format!("failed to run {}: {error}\n", binary.display())),
    }
}

/// Environment overrides that keep dev runs out of the real user profile.
const fn dev_home_dirs() -> &'static [(&'static str, &'static str)] {
    &[
        ("XDG_CONFIG_HOME", "config"),
        ("XDG_DATA_HOME", "data"),
        ("XDG_STATE_HOME", "state"),
        ("XDG_CACHE_HOME", "cache"),
    ]
}

fn target_dir() -> PathBuf {
    env::var_os("CARGO_TARGET_DIR").map_or_else(|| PathBuf::from("target"), PathBuf::from)
}

const fn binary_name() -> &'static str {
    if cfg!(windows) { "smith.exe" } else { "smith" }
}

fn note(message: &str) {
    let _ignored = std::io::stderr().write_all(message.as_bytes());
}

fn run_os(program: &str, args: &[OsString]) -> ExitCode {
    match Command::new(program).args(args).status() {
        Ok(status) if status.success() => ExitCode::SUCCESS,
        Ok(status) => fail(&format!("{program} exited with {status}\n")),
        Err(error) => fail(&format!("failed to run {program}: {error}\n")),
    }
}

fn run(program: &str, args: &[&str]) -> ExitCode {
    match Command::new(program).args(args).status() {
        Ok(status) if status.success() => ExitCode::SUCCESS,
        Ok(status) => fail(&format!("{program} exited with {status}\n")),
        Err(error) => fail(&format!("failed to run {program}: {error}\n")),
    }
}

fn arch(extra: &[OsString]) -> ExitCode {
    let wanted: Vec<String> = extra
        .iter()
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect();
    for crate_name in CRATES {
        if !Path::new(crate_name).join("Cargo.toml").is_file() {
            return fail(&format!("missing crate manifest: {crate_name}\n"));
        }
    }
    for rule in dependency_rules() {
        if !wanted.is_empty() && !wanted.iter().any(|name| name == rule.crate_name) {
            continue;
        }
        let manifest = match fs::read_to_string(Path::new(rule.crate_name).join("Cargo.toml")) {
            Ok(value) => value,
            Err(error) => {
                return fail(&format!(
                    "failed to read {} Cargo.toml: {error}\n",
                    rule.crate_name
                ));
            }
        };
        for denied in rule.denied {
            if has_dependency(&manifest, denied) {
                return fail(&format!(
                    "{} must not depend on {denied}\n",
                    rule.crate_name
                ));
            }
        }
    }
    ExitCode::SUCCESS
}

struct DependencyRule {
    crate_name: &'static str,
    denied: &'static [&'static str],
}

const fn dependency_rules() -> &'static [DependencyRule] {
    &[
        DependencyRule {
            crate_name: "smith",
            denied: &[
                "smith-core",
                "smith-ai",
                "smith-ui",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
        DependencyRule {
            crate_name: "smith-core",
            denied: &[
                "smith-ai",
                "smith-ui",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
        DependencyRule {
            crate_name: "smith-ai",
            denied: &[
                "smith-core",
                "smith-ui",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
        DependencyRule {
            crate_name: "smith-ui",
            denied: &[
                "smith-core",
                "smith-ai",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
        DependencyRule {
            crate_name: "smith-tui",
            denied: &["smith-core", "smith-ai", "smith-harness", "smith-cli"],
        },
        DependencyRule {
            crate_name: "smith-rpc",
            denied: &[
                "smith-ai",
                "smith-ui",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
        DependencyRule {
            crate_name: "smith-cli",
            denied: &["smith-core", "smith-ai", "smith-ui", "smith-tui"],
        },
        DependencyRule {
            crate_name: "xtask",
            denied: &[
                "smith",
                "smith-core",
                "smith-ai",
                "smith-ui",
                "smith-tui",
                "smith-harness",
                "smith-cli",
            ],
        },
    ]
}

fn has_dependency(manifest: &str, crate_name: &str) -> bool {
    // Library edges only: the manifest up to the dev-dependency table.
    let library = manifest
        .split("[dev-dependencies]")
        .next()
        .unwrap_or(manifest);
    let table = format!("[dependencies.{crate_name}]");
    let assignment = format!("{crate_name} =");
    library.lines().any(|line| {
        let trimmed = line.trim_start();
        trimmed.starts_with(&table) || trimmed.starts_with(&assignment)
    })
}

fn fail(message: &str) -> ExitCode {
    let _ignored = std::io::stderr().write_all(message.as_bytes());
    ExitCode::FAILURE
}

#[cfg(test)]
mod tests {
    use super::{binary_name, dev_home_dirs, has_dependency, target_dir};
    use std::path::PathBuf;

    #[test]
    fn dev_home_covers_all_xdg_roots() {
        let keys: Vec<&str> = dev_home_dirs().iter().map(|(key, _)| *key).collect();
        assert_eq!(
            keys,
            vec![
                "XDG_CONFIG_HOME",
                "XDG_DATA_HOME",
                "XDG_STATE_HOME",
                "XDG_CACHE_HOME"
            ]
        );
    }

    #[test]
    fn dev_binary_path_is_platform_correct() {
        let path = target_dir().join("debug").join(binary_name());
        assert!(path.ends_with(if cfg!(windows) { "smith.exe" } else { "smith" }));
        assert!(path.starts_with(env_target()));
    }

    fn env_target() -> PathBuf {
        std::env::var_os("CARGO_TARGET_DIR").map_or_else(|| PathBuf::from("target"), PathBuf::from)
    }

    #[test]
    fn detects_inline_and_table_dependencies() {
        assert!(has_dependency(
            "smith-core = { path = \"../smith-core\" }",
            "smith-core"
        ));
        assert!(has_dependency(
            "[dependencies.smith-ai]\npath = \"../smith-ai\"",
            "smith-ai"
        ));
    }

    #[test]
    fn ignores_non_dependency_mentions() {
        assert!(!has_dependency("# smith-core = forbidden", "smith-core"));
        assert!(!has_dependency("smith_core = \"0.1\"", "smith-core"));
    }
}