#![forbid(unsafe_code)]
use std::error::Error;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use clap::{Parser, Subcommand, ValueEnum};
use coatcheck::config::{CONFIG_FILE, Config};
use coatcheck::runner::{fetch_manifest, finish_review, generate};
const PLAYWRIGHT_PACKAGE: &str = "@playwright/test@1.61.1";
const AXE_PACKAGE: &str = "@axe-core/playwright@4.12.1";
const CONFIG_TEMPLATE: &str = include_str!("../templates/Coatcheck.toml");
const PACKAGE_TEMPLATE: &str = include_str!("../templates/package.json");
const CUSTOM_SPEC_TEMPLATE: &str = include_str!("../templates/custom.spec.ts");
#[derive(Debug, Parser)]
#[command(
name = "coatcheck",
version,
about = "Semantic component checks for Topcoat workbenches"
)]
struct Cli {
#[arg(long, global = true, default_value = ".")]
project_root: PathBuf,
#[command(subcommand)]
command: Commands,
}
#[derive(Debug, Subcommand)]
enum Commands {
Init {
#[arg(long, value_enum, default_value_t = PackageManager::Bun)]
package_manager: PackageManager,
#[arg(long)]
force: bool,
#[arg(long)]
skip_install: bool,
},
Doctor {
#[arg(long)]
fix: bool,
},
Dev,
Test {
#[arg(long)]
no_host: bool,
#[arg(long)]
headed: bool,
#[arg(long)]
story: Option<String>,
#[arg(long)]
slow_mo: Option<u64>,
},
}
#[derive(Clone, Copy, Debug, ValueEnum)]
enum PackageManager {
Bun,
}
fn main() {
if let Err(error) = run() {
eprintln!("coatcheck: {error}");
std::process::exit(1);
}
}
fn run() -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
let project_root = absolute_project_root(&cli.project_root)?;
match cli.command {
Commands::Init {
package_manager,
force,
skip_install,
} => init(&project_root, package_manager, force, skip_install),
Commands::Doctor { fix } => doctor(&project_root, fix),
Commands::Dev => dev(&project_root),
Commands::Test {
no_host,
headed,
story,
slow_mo,
} => test(&project_root, no_host, headed, story.as_deref(), slow_mo),
}
}
fn init(
project_root: &Path,
package_manager: PackageManager,
force: bool,
skip_install: bool,
) -> Result<(), Box<dyn Error>> {
let config_path = project_root.join(CONFIG_FILE);
if config_path.exists() && !force {
return Err(message(format!(
"{} already exists; pass --force to replace it",
config_path.display()
)));
}
let project_name = project_root
.file_name()
.and_then(OsStr::to_str)
.unwrap_or("coatcheck-project");
let encoded_name = serde_json::to_string(project_name)?;
let rendered_config = CONFIG_TEMPLATE.replace("{{project_name}}", &encoded_name);
fs::write(&config_path, rendered_config)?;
write_if_missing(&project_root.join("package.json"), PACKAGE_TEMPLATE)?;
write_if_missing(
&project_root.join("coatcheck/example.spec.ts"),
CUSTOM_SPEC_TEMPLATE,
)?;
ensure_gitignore(project_root)?;
println!("created {}", config_path.display());
println!("created project-local Coatcheck spec scaffold");
if skip_install {
println!("skipped Bun and Chromium installation");
} else {
install_runner(project_root, package_manager)?;
}
Ok(())
}
fn doctor(project_root: &Path, fix: bool) -> Result<(), Box<dyn Error>> {
let config = load_config(project_root)?;
println!("ok {}", project_root.join(CONFIG_FILE).display());
if fix {
write_if_missing(&project_root.join("package.json"), PACKAGE_TEMPLATE)?;
install_runner(project_root, PackageManager::Bun)?;
}
check_command(project_root, "bun", &["--version"], "Bun")?;
check_command(
project_root,
"bun",
&[
"-e",
"await import('@playwright/test'); await import('@axe-core/playwright')",
],
"project-local Playwright and Axe",
)?;
let chromium_path = command_stdout(
project_root,
"bun",
&[
"-e",
"import { chromium } from '@playwright/test'; console.log(chromium.executablePath())",
],
)?;
let chromium_path = PathBuf::from(chromium_path.trim());
if !chromium_path.is_file() {
return Err(message(format!(
"Chromium is not installed at {}; run `coatcheck doctor --fix`",
chromium_path.display()
)));
}
println!("ok Chromium {}", chromium_path.display());
let health_url = config.endpoint(&config.host.health)?;
match ureq::get(health_url.as_str()).call() {
Ok(response) => println!("ok host health {} {}", response.status(), health_url),
Err(error) => {
println!("warn host is not reachable at {health_url}: {error} (run `coatcheck dev`)");
}
}
println!("doctor passed");
Ok(())
}
fn dev(project_root: &Path) -> Result<(), Box<dyn Error>> {
let config = load_config(project_root)?;
println!("running {}", display_command(&config.host.command));
let status = host_command(project_root, &config)?
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()?;
require_success(status, "host command")
}
fn test(
project_root: &Path,
no_host: bool,
headed: bool,
story: Option<&str>,
slow_mo: Option<u64>,
) -> Result<(), Box<dyn Error>> {
let config = load_config(project_root)?;
check_command(
project_root,
"bun",
&[
"-e",
"await import('@playwright/test'); await import('@axe-core/playwright')",
],
"project-local Playwright and Axe",
)?;
let health_url = config.endpoint(&config.host.health)?;
let host_is_ready = ureq::get(health_url.as_str()).call().is_ok();
let mut host = if no_host || host_is_ready {
if host_is_ready {
println!("reusing host at {health_url}");
}
None
} else {
println!("starting {}", display_command(&config.host.command));
Some(HostGuard::spawn(project_root, &config)?)
};
wait_for_health(&config)?;
let manifest_url = config.endpoint(&config.host.manifest)?;
let mut manifest = fetch_manifest(&manifest_url)?;
if let Some(story) = story {
manifest.stories.retain(|candidate| candidate.id == story);
if manifest.stories.is_empty() {
return Err(message(format!("story not found in manifest: {story}")));
}
}
let generated = generate(project_root, &config, &manifest)?;
println!(
"generated {} manifest cases in {}",
generated.case_count,
generated.directory.display()
);
let mut command = Command::new("bunx");
command
.current_dir(project_root)
.arg("playwright")
.arg("test")
.arg("--config")
.arg(&generated.config)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
if headed {
command.env("COATCHECK_HEADED", "1");
}
if let Some(slow_mo) = slow_mo {
command.env("COATCHECK_SLOW_MO", slow_mo.to_string());
}
let status = command.status()?;
let success = status.success();
finish_review(&generated, &manifest, success)?;
if let Some(host) = host.as_mut() {
host.stop();
}
if success {
println!("semantic gates passed");
println!("review artifacts: {}", generated.review.display());
Ok(())
} else {
Err(message(format!(
"semantic gates failed; review {}",
generated.review.display()
)))
}
}
fn load_config(project_root: &Path) -> Result<Config, Box<dyn Error>> {
Ok(Config::load(&project_root.join(CONFIG_FILE))?)
}
fn install_runner(
project_root: &Path,
package_manager: PackageManager,
) -> Result<(), Box<dyn Error>> {
match package_manager {
PackageManager::Bun => {
println!("installing {PLAYWRIGHT_PACKAGE} and {AXE_PACKAGE}");
let status = Command::new("bun")
.current_dir(project_root)
.args(["add", "--dev", "--exact", PLAYWRIGHT_PACKAGE, AXE_PACKAGE])
.status()?;
require_success(status, "Bun dependency installation")?;
println!("installing Playwright Chromium");
let status = Command::new("bunx")
.current_dir(project_root)
.args(["playwright", "install", "chromium"])
.status()?;
require_success(status, "Chromium installation")?;
}
}
Ok(())
}
fn wait_for_health(config: &Config) -> Result<(), Box<dyn Error>> {
let health_url = config.endpoint(&config.host.health)?;
let deadline = Instant::now() + Duration::from_secs(config.host.startup_timeout_seconds);
let mut last_error = String::new();
while Instant::now() < deadline {
match ureq::get(health_url.as_str()).call() {
Ok(_) => {
println!("host ready at {health_url}");
return Ok(());
}
Err(error) => last_error = error.to_string(),
}
thread::sleep(Duration::from_millis(200));
}
Err(message(format!(
"host did not become ready at {health_url}: {last_error}"
)))
}
fn host_command(project_root: &Path, config: &Config) -> Result<Command, Box<dyn Error>> {
let (program, args) = config
.host
.command
.split_first()
.ok_or_else(|| message("host.command is empty"))?;
let mut command = Command::new(program);
command.current_dir(project_root).args(args);
Ok(command)
}
fn check_command(
project_root: &Path,
program: &str,
args: &[&str],
label: &str,
) -> Result<(), Box<dyn Error>> {
let status = Command::new(program)
.current_dir(project_root)
.args(args)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map_err(|error| message(format!("{label} is unavailable: {error}")))?;
if !status.success() {
return Err(message(format!(
"{label} check failed; run `coatcheck doctor --fix`"
)));
}
println!("ok {label}");
Ok(())
}
fn command_stdout(
project_root: &Path,
program: &str,
args: &[&str],
) -> Result<String, Box<dyn Error>> {
let output = Command::new(program)
.current_dir(project_root)
.args(args)
.output()?;
if !output.status.success() {
return Err(message(format!(
"{program} command failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(String::from_utf8(output.stdout)?)
}
fn require_success(status: ExitStatus, label: &str) -> Result<(), Box<dyn Error>> {
if status.success() {
Ok(())
} else {
Err(message(format!("{label} exited with {status}")))
}
}
fn write_if_missing(path: &Path, contents: &str) -> Result<(), Box<dyn Error>> {
if path.exists() {
return Ok(());
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, contents)?;
println!("created {}", path.display());
Ok(())
}
fn ensure_gitignore(project_root: &Path) -> Result<(), Box<dyn Error>> {
let path = project_root.join(".gitignore");
let mut contents = fs::read_to_string(&path).unwrap_or_default();
if contents.lines().any(|line| line.trim() == ".coatcheck/") {
return Ok(());
}
if !contents.is_empty() && !contents.ends_with('\n') {
contents.push('\n');
}
contents.push_str(".coatcheck/\n");
fs::write(path, contents)?;
Ok(())
}
fn absolute_project_root(path: &Path) -> Result<PathBuf, Box<dyn Error>> {
let path = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()?.join(path)
};
if !path.is_dir() {
return Err(message(format!(
"project root does not exist: {}",
path.display()
)));
}
Ok(path.canonicalize()?)
}
fn display_command(command: &[String]) -> String {
command
.iter()
.map(|part| {
if part.contains(char::is_whitespace) {
format!("{part:?}")
} else {
part.clone()
}
})
.collect::<Vec<_>>()
.join(" ")
}
fn message(message: impl Into<String>) -> Box<dyn Error> {
Box::new(io::Error::other(message.into()))
}
struct HostGuard {
child: Child,
stopped: bool,
}
impl HostGuard {
fn spawn(project_root: &Path, config: &Config) -> Result<Self, Box<dyn Error>> {
let mut command = host_command(project_root, config)?;
command
.stdin(Stdio::null())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
Ok(Self {
child: command.spawn()?,
stopped: false,
})
}
fn stop(&mut self) -> Option<ExitStatus> {
if self.stopped {
return self.child.try_wait().ok().flatten();
}
self.stopped = true;
if let Ok(Some(status)) = self.child.try_wait() {
return Some(status);
}
#[cfg(unix)]
{
signal("-INT", &self.child.id().to_string());
}
#[cfg(not(unix))]
{
let _ = self.child.kill();
}
for _ in 0..100 {
if let Ok(Some(status)) = self.child.try_wait() {
return Some(status);
}
thread::sleep(Duration::from_millis(50));
}
#[cfg(unix)]
{
signal("-KILL", &format!("-{}", self.child.id()));
}
let _ = self.child.kill();
self.child.wait().ok()
}
}
impl Drop for HostGuard {
fn drop(&mut self) {
self.stop();
}
}
#[cfg(unix)]
fn signal(signal: &str, target: &str) {
let _ = Command::new("kill")
.args([signal, "--", target])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(all(test, unix))]
mod tests {
use std::os::unix::process::ExitStatusExt;
use super::{Config, HostGuard};
#[test]
fn host_stop_interrupts_the_child_without_terminating_its_parent() {
let project = tempfile::tempdir().unwrap();
let config: Config = toml::from_str(
r#"
version = 1
name = "Host cleanup"
[host]
command = ["sleep", "30"]
url = "http://127.0.0.1:3000"
"#,
)
.unwrap();
let mut host = HostGuard::spawn(project.path(), &config).unwrap();
let status = host.stop().expect("host should be reaped");
assert_eq!(status.signal(), Some(2));
}
}