use anyhow::{bail, Context, Result};
use capy_cli::ProjectConfig;
use std::{
path::{Path, PathBuf},
process::{Command, ExitCode, ExitStatus, Stdio},
};
pub(crate) use supervisor::Owner;
pub(crate) fn serve(root: &Path) -> Result<ExitCode> {
application_command(root, &["serve".into()])
}
pub(crate) fn application_command(root: &Path, args: &[String]) -> Result<ExitCode> {
let mut owner = supervisor::Owner::new()?;
let executable = match compile_backend(root, &mut owner, false)? {
Ok(executable) => executable,
Err(status) => return Ok(exit_code(status)),
};
if args.first().is_some_and(|arg| arg == "queue:work") {
let config = capy_core::AppConfig::load_from(root)?;
owner.set_shutdown_timeout(std::time::Duration::from_secs(
config.jobs.shutdown_timeout_seconds + 2,
));
}
Ok(exit_code(owner.run(
Command::new(executable).args(args).current_dir(root),
)?))
}
fn compile_backend(
root: &Path,
owner: &mut supervisor::Owner,
release: bool,
) -> Result<std::result::Result<PathBuf, ExitStatus>> {
let metadata = tempfile::tempfile()?;
let status = owner.run(
Command::new("cargo")
.args(["metadata", "--no-deps", "--format-version=1"])
.current_dir(root)
.stdout(Stdio::from(metadata.try_clone()?)),
)?;
if !status.success() || owner.interrupted() {
return Ok(Err(status));
}
let data: serde_json::Value = read_json(metadata)?;
let manifest = root.join("Cargo.toml").canonicalize()?;
let package = data["packages"]
.as_array()
.context("Cargo metadata has no packages")?
.iter()
.find(|p| {
p["manifest_path"]
.as_str()
.is_some_and(|s| Path::new(s) == manifest)
})
.context("Cannot locate application package in Cargo metadata")?;
let bins: Vec<_> = package["targets"]
.as_array()
.context("Cargo metadata has no targets")?
.iter()
.filter(|t| {
t["kind"]
.as_array()
.is_some_and(|k| k.iter().any(|k| k == "bin"))
})
.filter_map(|t| t["name"].as_str())
.collect();
let bin = if let Some(default) = package["default_run"].as_str() {
default
} else if bins.len() == 1 {
bins[0]
} else {
bail!("Application has multiple binaries. Set `package.default-run` in Cargo.toml for `capy serve`.");
};
let artifacts = tempfile::tempfile()?;
let mut build = Command::new("cargo");
build
.args([
"build",
"--quiet",
"--bin",
bin,
"--message-format=json-render-diagnostics",
])
.current_dir(root)
.stdout(Stdio::from(artifacts.try_clone()?));
if release {
build.arg("--release");
}
let status = owner.run(&mut build)?;
if !status.success() || owner.interrupted() {
return Ok(Err(status));
}
use std::io::{BufRead, BufReader, Seek};
let mut artifacts = artifacts;
artifacts.rewind()?;
let mut executable = None;
for line in BufReader::new(artifacts).lines() {
let item: serde_json::Value = serde_json::from_str(&line?)?;
if item["reason"] == "compiler-artifact" && item["target"]["name"] == bin {
if let Some(path) = item["executable"].as_str() {
executable = Some(path.to_owned());
}
}
}
let executable = executable.context("Cargo did not produce an application binary")?;
Ok(Ok(PathBuf::from(executable)))
}
pub(crate) fn build(root: &Path) -> Result<ExitCode> {
let driver = ProjectConfig::load(root)?.frontend.driver;
driver.validate(root)?;
let mut owner = supervisor::Owner::new()?;
if let Some(mut command) = driver.install_command(root) {
println!("Installing frontend dependencies...");
let status = owner.run(&mut command).context("Could not install frontend dependencies. Install Node.js and pnpm, then run capy build again.")?;
if !status.success() || owner.interrupted() {
return Ok(exit_code(status));
}
}
println!("Building application...");
let executable = match compile_backend(root, &mut owner, true)? {
Ok(executable) => executable,
Err(status) => return Ok(exit_code(status)),
};
let generation =
crate::contracts::Generation::new(root, driver == capy_cli::FrontendDriver::React)?;
let mut export = Command::new(executable);
export.arg("__capy_contract").current_dir(root);
generation.capture(&mut export)?;
let status = owner.run(&mut export)?;
if !status.success() || owner.interrupted() {
return Ok(exit_code(status));
}
if let Some(mut command) = generation.types_command()? {
let status = owner.run(&mut command)?;
if !status.success() || owner.interrupted() {
return Ok(exit_code(status));
}
}
if generation.finish(false)? {
println!("API contracts regenerated.");
}
if let Some(mut command) = driver.build_command(root) {
println!("Building frontend...");
let status = owner
.run(&mut command)
.context("Could not build the frontend. Install Node.js and pnpm.")?;
if !status.success() || owner.interrupted() {
return Ok(exit_code(status));
}
if !root.join("frontend/dist/index.html").is_file() {
bail!("Frontend build did not produce frontend/dist/index.html. Check frontend/package.json and vite.config.ts.");
}
println!("✓ Frontend built\n");
}
println!("✓ Rust release build complete\n\nBuild complete.");
Ok(ExitCode::SUCCESS)
}
fn read_json(mut file: std::fs::File) -> Result<serde_json::Value> {
use std::io::Seek;
file.rewind()?;
Ok(serde_json::from_reader(file)?)
}
pub(crate) fn exit_code(status: ExitStatus) -> ExitCode {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
ExitCode::from(
status
.code()
.unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8,
)
}
#[cfg(not(unix))]
ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1))
}
#[path = "supervisor.rs"]
mod supervisor;