use anyhow::{bail, Context, Result};
use capy_cli::{FrontendDriver, ProjectConfig};
use std::{
cell::Cell,
fs,
io::Write,
path::{Path, PathBuf},
process::{Command, ExitCode, Stdio},
};
pub(crate) const OPENAPI: &str = "generated/openapi.json";
pub(crate) const TYPES: &str = "frontend/src/generated/api-types.ts";
pub(crate) struct Generation {
temp: tempfile::TempDir,
root: PathBuf,
types: bool,
skip_types: Cell<bool>,
empty: Cell<bool>,
}
impl Generation {
pub fn new(root: &Path, types: bool) -> Result<Self> {
if types && ProjectConfig::load(root)?.frontend.driver != FrontendDriver::React {
bail!("capy types requires a React/TypeScript frontend in frontend/. Use capy openapi for other clients.");
}
let temp = tempfile::tempdir()?;
fs::write(
temp.path().join("contracts.mjs"),
include_str!("../templates/contracts.mjs"),
)?;
Ok(Self {
temp,
root: root.to_path_buf(),
types,
skip_types: Cell::new(false),
empty: Cell::new(false),
})
}
pub fn capture(&self, command: &mut Command) -> Result<()> {
command.stdout(Stdio::from(fs::File::create(
self.temp.path().join("openapi.json"),
)?));
Ok(())
}
pub fn types_command(&self) -> Result<Option<Command>> {
let bytes = fs::read(self.temp.path().join("openapi.json"))?;
let document: serde_json::Value = serde_json::from_slice(&bytes)
.context("The application did not export an OpenAPI document. Update Capy and forward application commands through App::run(). Do not log to stdout before contract export.")?;
if document["openapi"] != "3.1.0" || !document["paths"].is_object() {
bail!("The application returned an unsupported API document; expected OpenAPI 3.1.0.");
}
self.empty.set(
document["paths"]
.as_object()
.is_some_and(|paths| paths.is_empty()),
);
self.skip_types
.set(self.empty.get() && !self.root.join(TYPES).exists());
if !self.types || self.skip_types.get() {
return Ok(None);
}
let mut command = Command::new("node");
command
.arg(self.temp.path().join("contracts.mjs"))
.arg(self.root.join("frontend"))
.arg(self.temp.path().join("openapi.json"))
.arg(self.temp.path().join("api-types.ts"))
.current_dir(&self.root);
Ok(Some(command))
}
pub fn finish(&self, check: bool) -> Result<bool> {
if check
&& self.empty.get()
&& !self.root.join(OPENAPI).exists()
&& !self.root.join(TYPES).exists()
{
return Ok(false);
}
let mut files = vec![(
self.root.join(OPENAPI),
fs::read(self.temp.path().join("openapi.json"))?,
)];
if self.types && !self.skip_types.get() {
files.push((
self.root.join(TYPES),
fs::read(self.temp.path().join("api-types.ts"))?,
));
}
let mut changed = Vec::new();
for (path, bytes) in files {
match fs::read(&path) {
Ok(existing) if existing == bytes => {}
Ok(_) => changed.push((path, bytes)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
changed.push((path, bytes))
}
Err(error) => return Err(error).context("Could not read generated API contract"),
}
}
if check && !changed.is_empty() {
bail!("API contracts are out of date.\n\nRun:\n\n capy {}\n\nNo generated files were changed.", if self.types {"types"} else {"openapi"});
}
for (path, bytes) in &changed {
let parent = path.parent().context("Invalid generated path")?;
fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
file.write_all(bytes)?;
file.persist(path)
.with_context(|| format!("Could not atomically update {}", path.display()))?;
}
Ok(!changed.is_empty())
}
}
pub(crate) fn run(root: &Path, types: bool, check: bool, offline: bool) -> Result<ExitCode> {
run_with_strict(root, types, check, offline, false)
}
pub(crate) fn run_with_strict(
root: &Path,
types: bool,
check: bool,
offline: bool,
strict: bool,
) -> Result<ExitCode> {
let generation = Generation::new(root, types)?;
let mut owner = crate::process::Owner::new()?;
let mut command = Command::new("cargo");
command.args(["run", "--quiet"]);
if offline {
command.arg("--offline");
}
command
.args([
"--",
if strict {
"__capy_contract_strict"
} else {
"__capy_contract"
},
])
.current_dir(root);
generation.capture(&mut command)?;
let status = owner.run(&mut command)?;
if !status.success() || owner.interrupted() {
eprintln!("Capy could not export the API contract. Resolve the compiler/schema diagnostic above; add ApiSchema to public DTOs or use #[schemars(with = \"WireType\")] for custom serialization.");
return Ok(crate::process::exit_code(status));
}
if let Some(mut command) = generation.types_command()? {
let status = owner.run(&mut command).context("TypeScript generation requires Node.js and frontend dependencies. Run pnpm install in frontend/.")?;
if !status.success() || owner.interrupted() {
return Ok(crate::process::exit_code(status));
}
}
let changed = generation.finish(check)?;
println!(
"{}",
if check {
"API contracts are up to date."
} else if changed {
"API contracts regenerated."
} else {
"API contracts unchanged."
}
);
Ok(ExitCode::SUCCESS)
}
#[cfg(test)]
mod tests {
use super::*;
fn prepared(root: &Path, document: &str) -> Generation {
let generation = Generation::new(root, false).unwrap();
fs::write(generation.temp.path().join("openapi.json"), document).unwrap();
assert!(generation.types_command().unwrap().is_none());
generation
}
#[test]
fn drift_check_does_not_create_or_replace_files_and_unchanged_generation_keeps_mtime() {
let temp = tempfile::tempdir().unwrap();
let document = r#"{"openapi":"3.1.0","paths":{"/posts":{}}}"#;
let generation = prepared(temp.path(), document);
let error = generation.finish(true).unwrap_err().to_string();
assert!(error.contains("API contracts are out of date") && error.contains("capy openapi"));
assert!(!temp.path().join("generated").exists());
assert!(generation.finish(false).unwrap());
let path = temp.path().join(OPENAPI);
let time = fs::metadata(&path).unwrap().modified().unwrap();
assert!(!generation.finish(true).unwrap());
assert!(!prepared(temp.path(), document).finish(false).unwrap());
assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), time);
fs::write(&path, "previous good contract").unwrap();
assert!(generation.finish(true).is_err());
assert_eq!(fs::read_to_string(path).unwrap(), "previous good contract");
}
#[test]
fn types_failure_keeps_both_published_files_and_removing_routes_clears_stale_types() {
let temp = tempfile::tempdir().unwrap();
capy_cli::new_project(temp.path().join("app").as_path(), "app").unwrap();
let root = temp.path().join("app");
fs::create_dir_all(root.join("generated")).unwrap();
fs::create_dir_all(root.join("frontend/src/generated")).unwrap();
fs::write(root.join(OPENAPI), "good schema").unwrap();
fs::write(root.join(TYPES), "good types").unwrap();
let generation = Generation::new(&root, true).unwrap();
fs::write(
generation.temp.path().join("openapi.json"),
r#"{"openapi":"3.1.0","paths":{}}"#,
)
.unwrap();
assert!(generation.types_command().unwrap().is_some());
assert!(generation.finish(false).is_err());
assert_eq!(
fs::read_to_string(root.join(OPENAPI)).unwrap(),
"good schema"
);
assert_eq!(fs::read_to_string(root.join(TYPES)).unwrap(), "good types");
fs::write(generation.temp.path().join("api-types.ts"), "empty types").unwrap();
assert!(generation.finish(true).is_err());
assert!(generation.finish(false).unwrap());
assert_eq!(fs::read_to_string(root.join(TYPES)).unwrap(), "empty types");
}
#[test]
fn unannotated_starter_requires_no_node_and_has_no_contract_drift() {
let temp = tempfile::tempdir().unwrap();
let generation = prepared(temp.path(), r#"{"openapi":"3.1.0","paths":{}}"#);
assert!(!generation.finish(true).unwrap());
assert!(!temp.path().join(OPENAPI).exists());
let invalid = Generation::new(temp.path(), false).unwrap();
fs::write(invalid.temp.path().join("openapi.json"), "not JSON").unwrap();
assert!(invalid
.types_command()
.unwrap_err()
.to_string()
.contains("did not export an OpenAPI"));
}
}