1use crate::names::{validate_name, GeneratedNames};
2use anyhow::{bail, Context, Result};
3use fs2::FileExt;
4use std::{
5 fs::{self, OpenOptions},
6 io::Write,
7 path::{Path, PathBuf},
8 process::{Command, Stdio},
9 time::{SystemTime, UNIX_EPOCH},
10};
11
12#[derive(Clone, Copy, Debug)]
14pub enum Generator {
15 Controller,
17 Model,
19 Request,
21 Migration,
23}
24
25pub fn generate(root: &Path, kind: Generator, name: &str) -> Result<PathBuf> {
28 generate_with(root, kind, name, |temp, path| {
29 temp.persist(path).map(|_| ()).map_err(|e| e.error.into())
30 })
31}
32
33fn generate_with(
34 root: &Path,
35 kind: Generator,
36 name: &str,
37 replace: impl FnOnce(tempfile::NamedTempFile, &Path) -> Result<()>,
38) -> Result<PathBuf> {
39 let names = GeneratedNames::new(name)?;
40 let lock = OpenOptions::new()
43 .read(true)
44 .write(true)
45 .create(true)
46 .truncate(false)
47 .open(root.join(".capy-generator.lock"))?;
48 lock.lock_exclusive()
49 .context("Cannot lock the Capy generator registry")?;
50 let module = names.module.clone();
51 let ty = &names.ty;
52 let (directory, file_module, source, exports) = match kind {
53 Generator::Controller => (
54 "app/controllers",
55 module.clone(),
56 include_str!("../templates/controller.rs.txt").replace("{{type}}", ty),
57 String::new(),
58 ),
59 Generator::Request => (
60 "app/requests",
61 module.clone(),
62 include_str!("../templates/request.rs.txt").replace("{{type}}", ty),
63 String::new(),
64 ),
65 Generator::Model => {
66 let table = if module.ends_with('y') {
67 format!("{}ies", module.trim_end_matches('y'))
68 } else {
69 format!("{module}s")
70 };
71 (
72 "app/models",
73 module.clone(),
74 include_str!("../templates/model.rs.txt").replace("{{table}}", &table),
75 format!(
76 "pub use self::{module}::Entity as {ty};\npub use self::{module}::Model as {ty}Model;\n"
77 ),
78 )
79 }
80 Generator::Migration => {
81 let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
82 let file_module = format!("m{timestamp}_{module}");
83 let source = if let Some(table) = module
84 .strip_prefix("create_")
85 .and_then(|s| s.strip_suffix("_table"))
86 {
87 validate_name(table, false)?;
88 include_str!("../templates/create_table.rs.txt").replace("{{table}}", table)
89 } else {
90 include_str!("../templates/migration.rs.txt").into()
91 };
92 ("database/migrations", file_module, source, String::new())
93 }
94 };
95 let directory = root.join(directory);
96 let path = directory.join(format!("{file_module}.rs"));
97 let registry_path = directory.join("mod.rs");
98 let registry = fs::read_to_string(®istry_path)
99 .context("Module registry is missing. Run the generator inside a Capy project.")?;
100 let metadata = fs::symlink_metadata(®istry_path)?;
101 if !metadata.file_type().is_file() {
102 bail!(
103 "Module registry must be a regular file, not a symlink: {}",
104 registry_path.display()
105 );
106 }
107 names.check_registry(®istry, &file_module, kind)?;
108 if path.exists()
109 || registry
110 .lines()
111 .any(|line| line.trim() == format!("pub mod {file_module};"))
112 {
113 bail!(
114 "{} already exists. Capy never overwrites generated code.",
115 path.display()
116 );
117 }
118 let registry = if matches!(kind, Generator::Migration) {
119 if registry.matches("// capy:modules").count() != 1
120 || registry.matches("// capy:migrations").count() != 1
121 {
122 bail!("Migration registry markers are missing. Restore `// capy:modules` and `// capy:migrations` in database/migrations/mod.rs.");
123 }
124 registry
125 .replace(
126 "// capy:modules",
127 &format!("mod {file_module};\n// capy:modules"),
128 )
129 .replace(
130 "// capy:migrations",
131 &format!("Box::new({file_module}::Migration),\n // capy:migrations"),
132 )
133 } else {
134 format!("{registry}\npub mod {file_module};\n{exports}")
135 };
136 let source = format_rust(&source)?;
137 let registry = format_rust(®istry)?;
138 let mut replacement = tempfile::NamedTempFile::new_in(&directory)?;
139 replacement
140 .as_file()
141 .set_permissions(metadata.permissions())?;
142 replacement.write_all(registry.as_bytes())?;
143 replacement.as_file().sync_all()?;
144 let mut source_file = tempfile::NamedTempFile::new_in(&directory)?;
145 source_file.write_all(source.as_bytes())?;
146 source_file.as_file().sync_all()?;
147 source_file
148 .persist_noclobber(&path)
149 .with_context(|| format!("Cannot create {}", path.display()))?;
150 if let Err(error) = replace(replacement, ®istry_path) {
151 fs::remove_file(&path).with_context(|| format!(
152 "Registration failed ({error:#}); could not remove unregistered source {}. Remove it before retrying.", path.display()
153 ))?;
154 return Err(error.context("Registration failed; generated source was rolled back"));
155 }
156 #[cfg(unix)]
159 if let Ok(directory) = fs::File::open(&directory) {
160 let _ = directory.sync_all();
161 }
162 Ok(path)
163}
164
165pub(crate) fn format_rust(source: &str) -> Result<String> {
166 let mut child = Command::new("rustfmt")
167 .args([
168 "--edition",
169 "2021",
170 "--emit",
171 "stdout",
172 "--config",
173 "skip_children=true",
174 ])
175 .stdin(Stdio::piped())
176 .stdout(Stdio::piped())
177 .stderr(Stdio::piped())
178 .spawn()
179 .context("The generators need rustfmt. Install it with `rustup component add rustfmt`.")?;
180 child
181 .stdin
182 .take()
183 .expect("piped stdin")
184 .write_all(source.as_bytes())?;
185 let output = child.wait_with_output()?;
186 if !output.status.success() {
187 bail!(
188 "Could not format generated code: {}",
189 String::from_utf8_lossy(&output.stderr)
190 );
191 }
192 Ok(String::from_utf8(output.stdout)?)
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn failed_replacement_preserves_registry_and_rolls_back_source() {
201 let temp = tempfile::tempdir().unwrap();
202 let root = temp.path().join("blog");
203 crate::new_project(&root, "blog").unwrap();
204 let registry = root.join("app/models/mod.rs");
205 let before = fs::read(®istry).unwrap();
206 let error = generate_with(&root, Generator::Model, "Post", |_, _| {
207 Err(std::io::Error::new(
208 std::io::ErrorKind::PermissionDenied,
209 "simulated rename failure",
210 )
211 .into())
212 })
213 .unwrap_err();
214 assert!(format!("{error:#}").contains("rolled back"));
215 assert_eq!(fs::read(®istry).unwrap(), before);
216 assert_eq!(fs::read_dir(registry.parent().unwrap()).unwrap().count(), 1);
217 }
218}