use crate::names::{validate_name, GeneratedNames};
use anyhow::{bail, Context, Result};
use fs2::FileExt;
use std::{
fs::{self, OpenOptions},
io::Write,
path::{Path, PathBuf},
process::{Command, Stdio},
time::{SystemTime, UNIX_EPOCH},
};
#[derive(Clone, Copy, Debug)]
pub enum Generator {
Controller,
Model,
Request,
Migration,
}
pub fn generate(root: &Path, kind: Generator, name: &str) -> Result<PathBuf> {
generate_with(root, kind, name, |temp, path| {
temp.persist(path).map(|_| ()).map_err(|e| e.error.into())
})
}
fn generate_with(
root: &Path,
kind: Generator,
name: &str,
replace: impl FnOnce(tempfile::NamedTempFile, &Path) -> Result<()>,
) -> Result<PathBuf> {
let names = GeneratedNames::new(name)?;
let lock = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".capy-generator.lock"))?;
lock.lock_exclusive()
.context("Cannot lock the Capy generator registry")?;
let module = names.module.clone();
let ty = &names.ty;
let (directory, file_module, source, exports) = match kind {
Generator::Controller => (
"app/controllers",
module.clone(),
include_str!("../templates/controller.rs.txt").replace("{{type}}", ty),
String::new(),
),
Generator::Request => (
"app/requests",
module.clone(),
include_str!("../templates/request.rs.txt").replace("{{type}}", ty),
String::new(),
),
Generator::Model => {
let table = if module.ends_with('y') {
format!("{}ies", module.trim_end_matches('y'))
} else {
format!("{module}s")
};
(
"app/models",
module.clone(),
include_str!("../templates/model.rs.txt").replace("{{table}}", &table),
format!(
"pub use self::{module}::Entity as {ty};\npub use self::{module}::Model as {ty}Model;\n"
),
)
}
Generator::Migration => {
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
let file_module = format!("m{timestamp}_{module}");
let source = if let Some(table) = module
.strip_prefix("create_")
.and_then(|s| s.strip_suffix("_table"))
{
validate_name(table, false)?;
include_str!("../templates/create_table.rs.txt").replace("{{table}}", table)
} else {
include_str!("../templates/migration.rs.txt").into()
};
("database/migrations", file_module, source, String::new())
}
};
let directory = root.join(directory);
let path = directory.join(format!("{file_module}.rs"));
let registry_path = directory.join("mod.rs");
let registry = fs::read_to_string(®istry_path)
.context("Module registry is missing. Run the generator inside a Capy project.")?;
let metadata = fs::symlink_metadata(®istry_path)?;
if !metadata.file_type().is_file() {
bail!(
"Module registry must be a regular file, not a symlink: {}",
registry_path.display()
);
}
names.check_registry(®istry, &file_module, kind)?;
if path.exists()
|| registry
.lines()
.any(|line| line.trim() == format!("pub mod {file_module};"))
{
bail!(
"{} already exists. Capy never overwrites generated code.",
path.display()
);
}
let registry = if matches!(kind, Generator::Migration) {
if registry.matches("// capy:modules").count() != 1
|| registry.matches("// capy:migrations").count() != 1
{
bail!("Migration registry markers are missing. Restore `// capy:modules` and `// capy:migrations` in database/migrations/mod.rs.");
}
registry
.replace(
"// capy:modules",
&format!("mod {file_module};\n// capy:modules"),
)
.replace(
"// capy:migrations",
&format!("Box::new({file_module}::Migration),\n // capy:migrations"),
)
} else {
format!("{registry}\npub mod {file_module};\n{exports}")
};
let source = format_rust(&source)?;
let registry = format_rust(®istry)?;
let mut replacement = tempfile::NamedTempFile::new_in(&directory)?;
replacement
.as_file()
.set_permissions(metadata.permissions())?;
replacement.write_all(registry.as_bytes())?;
replacement.as_file().sync_all()?;
let mut source_file = tempfile::NamedTempFile::new_in(&directory)?;
source_file.write_all(source.as_bytes())?;
source_file.as_file().sync_all()?;
source_file
.persist_noclobber(&path)
.with_context(|| format!("Cannot create {}", path.display()))?;
if let Err(error) = replace(replacement, ®istry_path) {
fs::remove_file(&path).with_context(|| format!(
"Registration failed ({error:#}); could not remove unregistered source {}. Remove it before retrying.", path.display()
))?;
return Err(error.context("Registration failed; generated source was rolled back"));
}
#[cfg(unix)]
if let Ok(directory) = fs::File::open(&directory) {
let _ = directory.sync_all();
}
Ok(path)
}
pub(crate) fn format_rust(source: &str) -> Result<String> {
let mut child = Command::new("rustfmt")
.args([
"--edition",
"2021",
"--emit",
"stdout",
"--config",
"skip_children=true",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.context("The generators need rustfmt. Install it with `rustup component add rustfmt`.")?;
child
.stdin
.take()
.expect("piped stdin")
.write_all(source.as_bytes())?;
let output = child.wait_with_output()?;
if !output.status.success() {
bail!(
"Could not format generated code: {}",
String::from_utf8_lossy(&output.stderr)
);
}
Ok(String::from_utf8(output.stdout)?)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn failed_replacement_preserves_registry_and_rolls_back_source() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("blog");
crate::new_project(&root, "blog").unwrap();
let registry = root.join("app/models/mod.rs");
let before = fs::read(®istry).unwrap();
let error = generate_with(&root, Generator::Model, "Post", |_, _| {
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"simulated rename failure",
)
.into())
})
.unwrap_err();
assert!(format!("{error:#}").contains("rolled back"));
assert_eq!(fs::read(®istry).unwrap(), before);
assert_eq!(fs::read_dir(registry.parent().unwrap()).unwrap().count(), 1);
}
}