#![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::Write, path::{Path, PathBuf}, process::Command, process::ExitCode, }; const HELP: &str = concat!( "usage: cargo x \n", " cargo x dev [args...] build and launch the dev smith binary\n", ); /// Nightly toolchain pinned for the cargo-pup architecture gate. const PINNED_NIGHTLY: &str = "+nightly-2026-01-22"; /// Version of `cargo_pup` used by the architecture gate. const PUP_VERSION: &str = "0.1.8"; /// Version of `cargo-nextest` used by the test gate. const NEXTEST_VERSION: &str = "0.9.144"; /// Version of `cargo-binstall` used to install `cargo-nextest`. const BINSTALL_VERSION: &str = "1.23.0"; const DENY_VERSION: &str = "0.20.2"; const AUDIT_VERSION: &str = "0.22.2"; const CRATES: &[&str] = &[ "smith", "smith-core", "smith-ai", "smith-tui", "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 = args.collect(); if command.to_str() == Some("dev") { return dev(&rest); } if !rest.is_empty() { return fail("xtask accepts exactly one command\n"); } match command.to_str() { Some("check") => check(), Some("lint") => lint(), Some("fmt") => cargo(&["fmt"]), Some("test") => cargo_nextest(), Some("doc") => cargo(&["doc", "--workspace", "--no-deps"]), Some("arch") => arch(), Some("pup") => cargo_pup(), Some("audit") => audit(), Some("bootstrap") => bootstrap(), _ => fail(HELP), } } fn check() -> ExitCode { sequence(&[ cargo_fmt, cargo_clippy, arch, cargo_pup, cargo_nextest, cargo_doc, cargo_machete, ]) } type Step = fn() -> ExitCode; fn sequence(steps: &[Step]) -> ExitCode { for step in steps { let code = step(); if code != ExitCode::SUCCESS { return code; } } ExitCode::SUCCESS } fn lint() -> ExitCode { sequence(&[cargo_fmt, cargo_clippy]) } fn audit() -> ExitCode { sequence(&[install_deny, install_audit, cargo_deny, cargo_audit]) } fn cargo_fmt() -> ExitCode { cargo(&["fmt", "--check"]) } fn cargo_clippy() -> ExitCode { cargo(&["clippy", "--workspace", "--all-targets", "--all-features"]) } fn cargo_nextest() -> ExitCode { cargo(&["nextest", "run", "--workspace", "--all-features"]) } fn cargo_pup() -> ExitCode { cargo(&[PINNED_NIGHTLY, "pup"]) } fn cargo_machete() -> ExitCode { let installed = tool_present_bin("cargo-machete", "--version", || { cargo(&["install", "--locked", "cargo-machete"]) }); if installed != ExitCode::SUCCESS { return installed; } run("cargo-machete", &[]) } /// Install the external gate tools that Cargo cannot ship. /// /// `cargo-nextest` arrives as a prebuilt binary through `cargo-binstall`; /// `cargo_pup` has no published binaries, so it is built from source on the /// pinned nightly with its rustc-dev dependency, which `rustup component /// add` provides. Both steps are idempotent. fn bootstrap() -> ExitCode { let steps: [Step; 6] = [ install_binstall, install_nextest, install_pup, install_machete, install_deny, install_audit, ]; sequence(&steps) } fn install_machete() -> ExitCode { tool_present_bin("cargo-machete", "--version", || { cargo(&["install", "--locked", "cargo-machete"]) }) } fn install_deny() -> ExitCode { tool_present_bin("cargo-deny", "--version", || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-deny@{DENY_VERSION}"), ]) }) } fn install_audit() -> ExitCode { tool_present_bin("cargo-audit", "--version", || { cargo(&[ "binstall", "--no-confirm", &format!("cargo-audit@{AUDIT_VERSION}"), ]) }) } fn install_binstall() -> ExitCode { tool_present(&["binstall", "--help"], || { cargo(&[ "install", "cargo-binstall", "--version", BINSTALL_VERSION, // Freeze binstall's own dependency graph for the same reason // as cargo_pup: crates.io drift cannot break the gate. "--locked", ]) }) } fn install_nextest() -> ExitCode { tool_present(&["nextest", "--version"], || { cargo(&[ "binstall", &format!("cargo-nextest@{NEXTEST_VERSION}"), "--no-confirm", ]) }) } fn add_pup_components() -> ExitCode { run( "rustup", &[ "component", "add", "--toolchain", PINNED_NIGHTLY.trim_start_matches('+'), "rust-src", "rustc-dev", "llvm-tools", ], ) } fn install_pup() -> ExitCode { let components = sequence(&[add_pup_components]); if components != ExitCode::SUCCESS { return components; } tool_present(&[PINNED_NIGHTLY, "pup", "--help"], || { cargo(&[ PINNED_NIGHTLY, "install", "cargo_pup", "--version", PUP_VERSION, // Freeze pup's dependency graph: a semver-compatible but // broken dep release on crates.io cannot break the gate. "--locked", ]) }) } /// 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. fn tool_present(probe: &[&str], install: impl FnOnce() -> ExitCode) -> ExitCode { let mut arguments = vec!["cargo"]; arguments.extend_from_slice(probe); match Command::new(arguments[0]) .args(&arguments[1..]) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() { Ok(status) if status.success() => ExitCode::SUCCESS, _ => install(), } } /// Probes an external binary directly; cargo subcommand dispatch can mangle /// arguments, so build tools are probed and run as plain binaries. fn tool_present_bin(program: &str, flag: &str, install: impl FnOnce() -> ExitCode) -> ExitCode { match Command::new(program) .arg(flag) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .status() { Ok(status) if status.success() => ExitCode::SUCCESS, _ => install(), } } fn cargo_doc() -> ExitCode { cargo(&["doc", "--workspace", "--no-deps"]) } fn cargo_deny() -> ExitCode { cargo(&["deny", "check"]) } fn cargo_audit() -> 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", "-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(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() -> ExitCode { 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() { 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-tui", "smith-harness", "smith-cli", ], }, DependencyRule { crate_name: "smith-core", denied: &["smith-ai", "smith-tui", "smith-harness", "smith-cli"], }, DependencyRule { crate_name: "smith-ai", denied: &["smith-core", "smith-tui", "smith-harness", "smith-cli"], }, DependencyRule { crate_name: "smith-tui", denied: &["smith-core", "smith-ai", "smith-harness", "smith-cli"], }, DependencyRule { crate_name: "smith-cli", denied: &["smith-core", "smith-ai", "smith-tui"], }, DependencyRule { crate_name: "xtask", denied: &[ "smith", "smith-core", "smith-ai", "smith-tui", "smith-harness", "smith-cli", ], }, ] } fn has_dependency(manifest: &str, crate_name: &str) -> bool { let table = format!("[dependencies.{crate_name}]"); let assignment = format!("{crate_name} ="); manifest.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")); } }