1use crate::FrontendDriver;
2use anyhow::{bail, Context, Result};
3use std::{
4 fs,
5 path::{Path, PathBuf},
6};
7
8const FILES: &[(&str, &str)] = &[
9 (".capy-generator.lock", ""),
10 (".gitattributes", "# Keep generated contracts byte-identical across Git checkouts.\n**/generated/** text eol=lf\n"),
11 ("Cargo.toml", include_str!("../templates/Cargo.toml.txt")),
12 ("src/main.rs", include_str!("../templates/main.rs.txt")),
13 ("src/lib.rs", include_str!("../templates/lib.rs.txt")),
14 ("src/bootstrap.rs", include_str!("../templates/bootstrap.rs.txt")),
15 ("app/mod.rs", "//! Application code.\npub mod controllers;\npub mod models;\npub mod requests;\n"),
16 ("app/controllers/mod.rs", "//! API controllers.\n"),
17 ("app/models/mod.rs", "//! SeaORM entities and convenient model aliases.\n"),
18 ("app/requests/mod.rs", "//! Validated JSON requests.\n"),
19 ("routes/mod.rs", "//! Application routes.\npub mod api;\n"),
20 ("routes/api.rs", include_str!("../templates/routes.rs.txt")),
21 ("database/mod.rs", "//! Database migrations and explicit development seeds.\npub mod migrations;\npub mod seeds;\n"),
22 ("database/seeds.rs", "//! Explicit, application-owned development data. Never runs while serving.\nuse capy::{SeedContext, SeedFuture};\n// capy:seed-modules\npub fn run(ctx: SeedContext<'_>) -> SeedFuture<'_> {\n Box::pin(async move {\n let _ = &ctx;\n // capy:seeds\n Ok(())\n })\n}\n"),
23 ("database/migrations/mod.rs", include_str!("../templates/migrator.rs.txt")),
24 ("config/app.toml", "name = \"{{name}}\"\nenvironment = \"development\"\nhost = \"127.0.0.1\"\nport = 8000\n"),
25 ("config/server.toml", "# Optional host/port override legacy APP_HOST/APP_PORT.\n# host = \"0.0.0.0\"\n# port = 8000\nshutdown_timeout_seconds = 10\n"),
26 ("config/api.toml", "# API contracts are opt-in on routes. Docs are development-only.\nopenapi = false\ndocs = false\n# title = \"My API\"\nversion = \"1.0.0\"\n"),
27 ("config/http.toml", "# Zero request timeout intentionally disables the response-header deadline.\nrequest_timeout_seconds = 30\nreadiness_timeout_seconds = 2\nmax_body_bytes = 2097152\ncompression = true\n"),
28 ("config/database.toml", "# SQLite makes the first run self-contained. Use DATABASE_URL for PostgreSQL.\nurl = \"sqlite://database/app.sqlite?mode=rwc\"\nmax_connections = 10\nmin_connections = 0\nconnect_timeout_seconds = 10\nacquire_timeout_seconds = 10\nidle_timeout_seconds = 600\n"),
29 (".env.example", include_str!("../templates/env.example.txt")),
30 (".gitignore", "/target\n.capy-generator.lock\n.env\n*.sqlite\n*.sqlite-shm\n*.sqlite-wal\n.capy/mail/\n"),
31 ("tests/health.rs", include_str!("../templates/health.rs.txt")),
32 ("README.md", include_str!("../templates/README.md.txt")),
33 ("capy.toml", "[frontend]\ndriver = \"{{frontend}}\"\n"),
34];
35
36pub fn new_project(path: &Path, name: &str) -> Result<()> {
38 new_project_with_frontend(path, name, FrontendDriver::React)
39}
40
41pub fn new_project_with_frontend(path: &Path, name: &str, frontend: FrontendDriver) -> Result<()> {
43 crate::names::project_name(name)?;
44 let files = FILES
45 .iter()
46 .chain(frontend.files())
47 .map(|(relative, contents)| {
48 let contents = if *relative == "routes/mod.rs" && frontend == FrontendDriver::React {
49 "//! Application routes.\npub mod api;\npub mod web;\n"
50 } else { contents };
51 let contents = contents
52 .replace("{{name}}", name)
53 .replace("{{frontend}}", frontend.as_str())
54 .replace("{{frontend-setup}}", if frontend == FrontendDriver::React {
55 ".routes(application::routes::web::routes())\n .frontend(\"frontend/dist\")"
56 } else { "" })
57 .replace("{{development}}", if frontend == FrontendDriver::React {
58 "Install Node.js 22.12+ (or 20.19+) and pnpm, then run `capy dev`.\nOpen http://127.0.0.1:5173. Capy installs missing dependencies and starts both servers.\nVite provides React HMR; Rust source changes automatically rebuild and restart the backend.\nCompilation errors retry after you save a fix. Press `1` then `r` for a manual restart.\nUse `CAPY_FRONTEND_PORT=5174 capy dev` if port 5173 is occupied.\nRequests to `/api/*` are proxied to the backend using the resolved app configuration."
59 } else {
60 "Run `capy dev` and visit http://127.0.0.1:8000/api/health.\nNo Node.js or pnpm is required. Rust source changes automatically rebuild and restart the backend.\nCompilation errors retry after you save a fix. Press `1` then `r` for a manual restart."
61 })
62 .replace("{{deployment}}", if frontend == FrontendDriver::React {
63 "Deploy the release binary together with `frontend/dist`, `config/`, and `database/`.\nRun from the application root. Capy serves the SPA and static assets; no Node server\nis needed. Missing API routes remain JSON 404s. Missing assets in production\nstop startup with a message to run `capy build`."
64 } else {
65 "Deploy the release binary together with `config/` and `database/`. Run from the application root."
66 })
67 .replace("{{framework-version}}", env!("CARGO_PKG_VERSION"))
68 .replace("{{rust-version}}", env!("CARGO_PKG_RUST_VERSION"))
69 .replace("{{crate}}", &name.replace('-', "_"));
70 let contents = if relative.ends_with(".rs") {
71 crate::generate::format_rust(&contents)?
72 } else {
73 contents
74 };
75 Ok((*relative, contents))
76 })
77 .collect::<Result<Vec<_>>>()?;
78 fs::create_dir(path).with_context(|| {
79 format!(
80 "Cannot create {}. Choose a new directory name.",
81 path.display()
82 )
83 })?;
84 let result = (|| {
85 for (relative, contents) in files {
86 let target = path.join(relative);
87 fs::create_dir_all(target.parent().expect("template has a parent"))?;
88 fs::write(target, contents)?;
89 }
90 Ok(())
91 })();
92 if result.is_err() {
93 let _ = fs::remove_dir_all(path);
95 }
96 result
97}
98
99pub fn find_project(start: impl AsRef<Path>) -> Result<PathBuf> {
101 for path in start.as_ref().ancestors() {
102 if path.join("Cargo.toml").is_file()
103 && path.join("routes/api.rs").is_file()
104 && path.join("app/mod.rs").is_file()
105 {
106 return Ok(path.to_owned());
107 }
108 }
109 bail!("No Capy application found. Run this command inside a project created by `capy new`.")
110}
111
112pub(crate) fn application_file(root: &Path) -> &'static str {
114 if root.join("src/bootstrap.rs").exists() {
115 "src/bootstrap.rs"
116 } else {
117 "src/main.rs"
118 }
119}
120
121pub(crate) fn wire_application(source: &str, call: &str) -> Result<String> {
123 if source.matches("// capy:app").count() == 1
124 && source.lines().any(|line| line.trim() == "// capy:app")
125 {
126 return Ok(source.replace("// capy:app", &format!("{call}\n // capy:app")));
127 }
128 bail!("Cannot safely wire the customized application factory. Add this exact builder call manually: {call}. Restore the // capy:app anchor before generating; no files changed.")
129}