Skip to main content

capy_cli/
generate.rs

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/// Supported generators, each producing a registered, compilable Rust module.
13#[derive(Clone, Copy, Debug)]
14pub enum Generator {
15    /// A struct with an Axum-compatible handler.
16    Controller,
17    /// A native SeaORM entity with an integer primary key.
18    Model,
19    /// A Serde request with validator rules.
20    Request,
21    /// A native SeaORM migration with reversible up/down methods.
22    Migration,
23}
24
25/// Generate a file and update its explicit module registry without overwrites.
26/// Migration registry markers must remain present; other code is left intact.
27pub 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
33/// Exact route-builder declaration for a generated controller. Routing stays
34/// explicit because route modules may contain arbitrary application Rust. The
35/// suggested path is the snake-case name without `_controller`; customize it
36/// before adding this line to `routes/api.rs`'s `Routes` chain (mounted at `/api`).
37pub fn controller_route(name: &str) -> Result<String> {
38    let names = GeneratedNames::new(name)?;
39    let route = names
40        .module
41        .strip_suffix("_controller")
42        .unwrap_or(&names.module);
43    Ok(format!(
44        ".get(\"/{route}\", crate::app::controllers::{}::{}::index)",
45        names.module, names.ty
46    ))
47}
48
49fn generate_with(
50    root: &Path,
51    kind: Generator,
52    name: &str,
53    replace: impl FnOnce(tempfile::NamedTempFile, &Path) -> Result<()>,
54) -> Result<PathBuf> {
55    let names = GeneratedNames::new(name)?;
56    // A stable, separate inode: locking mod.rs would lose coordination on rename.
57    // Never unlink the lock, including on error (waiters may hold its inode).
58    let lock = OpenOptions::new()
59        .read(true)
60        .write(true)
61        .create(true)
62        .truncate(false)
63        .open(root.join(".capy-generator.lock"))?;
64    lock.lock_exclusive()
65        .context("Cannot lock the Capy generator registry")?;
66    let module = names.module.clone();
67    let ty = &names.ty;
68    let (directory, file_module, source, exports) = match kind {
69        Generator::Controller => (
70            "app/controllers",
71            module.clone(),
72            include_str!("../templates/controller.rs.txt").replace("{{type}}", ty),
73            String::new(),
74        ),
75        Generator::Request => (
76            "app/requests",
77            module.clone(),
78            include_str!("../templates/request.rs.txt").replace("{{type}}", ty),
79            String::new(),
80        ),
81        Generator::Model => {
82            let table = if module.ends_with('y') {
83                format!("{}ies", module.trim_end_matches('y'))
84            } else {
85                format!("{module}s")
86            };
87            (
88                "app/models",
89                module.clone(),
90                include_str!("../templates/model.rs.txt").replace("{{table}}", &table),
91                format!(
92                    "pub use self::{module}::Entity as {ty};\npub use self::{module}::Model as {ty}Model;\n"
93                ),
94            )
95        }
96        Generator::Migration => {
97            let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
98            let file_module = format!("m{timestamp}_{module}");
99            let source = if let Some(table) = module
100                .strip_prefix("create_")
101                .and_then(|s| s.strip_suffix("_table"))
102            {
103                validate_name(table, false)?;
104                include_str!("../templates/create_table.rs.txt").replace("{{table}}", table)
105            } else {
106                include_str!("../templates/migration.rs.txt").into()
107            };
108            ("database/migrations", file_module, source, String::new())
109        }
110    };
111    let directory = root.join(directory);
112    let path = directory.join(format!("{file_module}.rs"));
113    let registry_path = directory.join("mod.rs");
114    let registry = fs::read_to_string(&registry_path)
115        .context("Module registry is missing. Run the generator inside a Capy project.")?;
116    let metadata = fs::symlink_metadata(&registry_path)?;
117    if !metadata.file_type().is_file() {
118        bail!(
119            "Module registry must be a regular file, not a symlink: {}",
120            registry_path.display()
121        );
122    }
123    names.check_registry(&registry, &file_module, kind)?;
124    if path.exists()
125        || registry
126            .lines()
127            .any(|line| line.trim() == format!("pub mod {file_module};"))
128    {
129        bail!(
130            "{} already exists. Capy never overwrites generated code.",
131            path.display()
132        );
133    }
134    let registry = if matches!(kind, Generator::Migration) {
135        if registry.matches("// capy:modules").count() != 1
136            || registry.matches("// capy:migrations").count() != 1
137        {
138            bail!("Migration registry markers are missing. Restore `// capy:modules` and `// capy:migrations` in database/migrations/mod.rs.");
139        }
140        registry
141            .replace(
142                "// capy:modules",
143                &format!("mod {file_module};\n// capy:modules"),
144            )
145            .replace(
146                "// capy:migrations",
147                &format!("Box::new({file_module}::Migration),\n            // capy:migrations"),
148            )
149    } else {
150        format!("{registry}\npub mod {file_module};\n{exports}")
151    };
152    let source = format_rust(&source)?;
153    let registry = format_rust(&registry)?;
154    let mut replacement = tempfile::NamedTempFile::new_in(&directory)?;
155    replacement
156        .as_file()
157        .set_permissions(metadata.permissions())?;
158    replacement.write_all(registry.as_bytes())?;
159    replacement.as_file().sync_all()?;
160    let mut source_file = tempfile::NamedTempFile::new_in(&directory)?;
161    source_file.write_all(source.as_bytes())?;
162    source_file.as_file().sync_all()?;
163    source_file
164        .persist_noclobber(&path)
165        .with_context(|| format!("Cannot create {}", path.display()))?;
166    if let Err(error) = replace(replacement, &registry_path) {
167        fs::remove_file(&path).with_context(|| format!(
168            "Registration failed ({error:#}); could not remove unregistered source {}. Remove it before retrying.", path.display()
169        ))?;
170        return Err(error.context("Registration failed; generated source was rolled back"));
171    }
172    // Atomic rename commits the transaction; both files have been synced. Directory
173    // syncing is best effort because not every supported filesystem provides it.
174    #[cfg(unix)]
175    if let Ok(directory) = fs::File::open(&directory) {
176        let _ = directory.sync_all();
177    }
178    Ok(path)
179}
180
181pub(crate) fn format_rust(source: &str) -> Result<String> {
182    let mut child = Command::new("rustfmt")
183        .args([
184            "--edition",
185            "2021",
186            "--emit",
187            "stdout",
188            "--config",
189            "skip_children=true",
190        ])
191        .stdin(Stdio::piped())
192        .stdout(Stdio::piped())
193        .stderr(Stdio::piped())
194        .spawn()
195        .context("The generators need rustfmt. Install it with `rustup component add rustfmt`.")?;
196    child
197        .stdin
198        .take()
199        .expect("piped stdin")
200        .write_all(source.as_bytes())?;
201    let output = child.wait_with_output()?;
202    if !output.status.success() {
203        bail!(
204            "Could not format generated code: {}",
205            String::from_utf8_lossy(&output.stderr)
206        );
207    }
208    Ok(String::from_utf8(output.stdout)?)
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn failed_replacement_preserves_registry_and_rolls_back_source() {
217        let temp = tempfile::tempdir().unwrap();
218        let root = temp.path().join("blog");
219        crate::new_project(&root, "blog").unwrap();
220        let registry = root.join("app/models/mod.rs");
221        let before = fs::read(&registry).unwrap();
222        let error = generate_with(&root, Generator::Model, "Post", |_, _| {
223            Err(std::io::Error::new(
224                std::io::ErrorKind::PermissionDenied,
225                "simulated rename failure",
226            )
227            .into())
228        })
229        .unwrap_err();
230        assert!(format!("{error:#}").contains("rolled back"));
231        assert_eq!(fs::read(&registry).unwrap(), before);
232        assert_eq!(fs::read_dir(registry.parent().unwrap()).unwrap().count(), 1);
233    }
234}