1mod plan;
7mod templates;
8mod transaction;
9
10use std::{
11 env,
12 path::{Path, PathBuf},
13 process::Command,
14};
15
16use anyhow::{bail, Context, Result};
17use serde::Serialize;
18
19use crate::{
20 capabilities::{CapabilityOverrides, CapabilitySelection, SiteTemplate},
21 scaffold::DryRunFormat,
22};
23
24pub use plan::{PlannedFile, SitePlan};
25
26pub(crate) fn deployment_dockerfile(has_database: bool) -> String {
27 templates::current_deployment_dockerfile(has_database)
28}
29
30#[derive(Debug, Clone)]
31pub struct NewSiteOptions {
32 pub path: PathBuf,
33 pub destination: Option<PathBuf>,
34 pub title: Option<String>,
35 pub template: String,
36 pub overrides: CapabilityOverrides,
37 pub vscode: bool,
38 pub agents_md: bool,
39 pub no_git: bool,
40 pub verify: bool,
41 pub start: bool,
42 pub open: bool,
43 pub offline: bool,
44 pub dry_run: Option<DryRunFormat>,
45 pub json: bool,
46}
47
48#[derive(Debug, Serialize)]
49#[serde(rename_all = "camelCase")]
50struct OperationReport<'a> {
51 operation_id: &'static str,
52 command_version: u16,
53 project_root: &'a Path,
54 planned_filesystem_operations: Vec<FilesystemOperation<'a>>,
55 configuration_changes: CapabilitySelection,
56 warnings: Vec<&'static str>,
57 result: OperationResult<'a>,
58}
59
60#[derive(Debug, Serialize)]
61#[serde(rename_all = "camelCase")]
62struct FilesystemOperation<'a> {
63 operation: &'static str,
64 path: &'a Path,
65 bytes: usize,
66}
67
68#[derive(Debug, Serialize)]
69#[serde(rename_all = "camelCase")]
70struct OperationResult<'a> {
71 status: &'a str,
72 destination: &'a Path,
73 package: &'a str,
74 title: &'a str,
75 selection: CapabilitySelection,
76 files: usize,
77 next: String,
78}
79
80pub(crate) fn scaffold_version(package: &str) -> String {
81 let versions: std::collections::BTreeMap<String, String> = toml::from_str(include_str!(
82 concat!(env!("OUT_DIR"), "/scaffold-versions.toml")
83 ))
84 .expect("bundled scaffold versions are valid TOML");
85 versions
86 .get(package)
87 .expect("scaffold dependency is listed")
88 .clone()
89}
90
91pub fn new_site(options: NewSiteOptions) -> Result<()> {
92 let template = SiteTemplate::parse_compat(&options.template)?;
93 let selection = CapabilitySelection::resolve(template, options.overrides)?;
94 let root = resolve_destination(&options.path, options.destination.as_deref())?;
95 transaction::ensure_destination_available(&root)?;
96 let package = package_name(&root)?;
97 let title = options.title.unwrap_or_else(|| display_title(&package));
98 let capabilities = selection
99 .capabilities()
100 .into_iter()
101 .map(|capability| capability.id.to_string())
102 .collect();
103 let mut plan = SitePlan::new(root.clone(), capabilities);
104 templates::populate(
105 &mut plan,
106 &package,
107 &title,
108 selection,
109 options.vscode,
110 options.agents_md,
111 )?;
112 plan.validate()?;
113
114 if let Some(format) = options.dry_run {
115 print_plan(&plan, &package, &title, selection, format)?;
116 return Ok(());
117 }
118
119 transaction::commit(&plan)?;
120 if !options.no_git {
121 transaction::initialize_git(&root)?;
122 }
123 print_success(&plan, &package, &title, selection, options.json)?;
124
125 if options.verify {
126 run_child(
127 &root,
128 &["check", "--all", "--root", root.to_string_lossy().as_ref()],
129 )
130 .context(
131 "project was created, but verification failed; repair it and run `proa check --all`",
132 )?;
133 }
134 if options.start || options.open {
135 let root_arg = root.to_string_lossy().into_owned();
136 let mut args = vec!["run", "--root", root_arg.as_str(), "dev"];
137 if options.open {
138 args.push("--open");
139 }
140 if options.offline {
141 args.push("--offline");
142 }
143 run_child(&root, &args)?;
144 }
145 Ok(())
146}
147
148fn resolve_destination(path: &Path, parent: Option<&Path>) -> Result<PathBuf> {
149 if path.as_os_str().is_empty() {
150 bail!("site path cannot be empty");
151 }
152 if path.is_absolute() {
153 if parent.is_some() {
154 bail!("--destination cannot be combined with an absolute site path");
155 }
156 Ok(path.to_path_buf())
157 } else {
158 Ok(parent
159 .map(Path::to_path_buf)
160 .unwrap_or(env::current_dir()?)
161 .join(path))
162 }
163}
164
165fn package_name(root: &Path) -> Result<String> {
166 let raw = root
167 .file_name()
168 .and_then(|value| value.to_str())
169 .context("site path must end in a UTF-8 directory name")?;
170 let mut package = String::with_capacity(raw.len());
171 for character in raw.chars() {
172 if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
173 package.push(character.to_ascii_lowercase());
174 } else if character.is_whitespace() {
175 package.push('-');
176 } else {
177 package.push('_');
178 }
179 }
180 while package.starts_with(|character: char| !character.is_ascii_alphabetic()) {
181 package.remove(0);
182 }
183 if package.is_empty() {
184 bail!("site path does not contain a valid package name");
185 }
186 Ok(package)
187}
188
189fn display_title(package: &str) -> String {
190 package
191 .split(['-', '_'])
192 .filter(|part| !part.is_empty())
193 .map(|part| {
194 let mut characters = part.chars();
195 match characters.next() {
196 Some(first) => format!("{}{}", first.to_ascii_uppercase(), characters.as_str()),
197 None => String::new(),
198 }
199 })
200 .collect::<Vec<_>>()
201 .join(" ")
202}
203
204fn print_plan(
205 plan: &SitePlan,
206 package: &str,
207 title: &str,
208 selection: CapabilitySelection,
209 format: DryRunFormat,
210) -> Result<()> {
211 match format {
212 DryRunFormat::Json => println!(
213 "{}",
214 serde_json::to_string_pretty(&operation_report(
215 plan, package, title, selection, "planned"
216 ))?
217 ),
218 DryRunFormat::Text => {
219 println!("Plan {}", plan.destination.display());
220 for capability in &plan.capabilities {
221 println!(" capability {capability}");
222 }
223 for file in &plan.files {
224 println!(" create {} ({} B)", file.path.display(), file.bytes);
225 }
226 }
227 }
228 Ok(())
229}
230
231fn print_success(
232 plan: &SitePlan,
233 package: &str,
234 title: &str,
235 selection: CapabilitySelection,
236 json: bool,
237) -> Result<()> {
238 let root = &plan.destination;
239 if json {
240 println!(
241 "{}",
242 serde_json::to_string_pretty(&operation_report(
243 plan, package, title, selection, "created"
244 ))?
245 );
246 return Ok(());
247 }
248 println!("Created {package}\n");
249 println!(" App Proa + Axum");
250 println!(
251 " Database {}",
252 if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
253 "SQLite + SQLx"
254 } else {
255 "none"
256 }
257 );
258 if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
259 println!(" Data keyed loading through cx");
260 }
261 println!(
262 " UI {}",
263 match selection.ui {
264 crate::capabilities::UiChoice::Proa => "proa-ui · 3 components vendored",
265 crate::capabilities::UiChoice::ProaDocs => "proa-docs",
266 crate::capabilities::UiChoice::None => "none",
267 }
268 );
269 println!(
270 " Markdown {}",
271 if selection.markdown {
272 "/index.md · Accept: text/markdown"
273 } else {
274 "disabled"
275 }
276 );
277 println!(
278 " Client {}",
279 if selection.template == crate::capabilities::SiteTemplate::Origin {
280 "rsjs flood-the-table island on /"
281 } else {
282 "no client root on /"
283 }
284 );
285 println!(" Health /healthz · /readyz");
286 println!("\nNext:\n cd {} && proa run dev --open", root.display());
287 Ok(())
288}
289
290fn operation_report<'a>(
291 plan: &'a SitePlan,
292 package: &'a str,
293 title: &'a str,
294 selection: CapabilitySelection,
295 status: &'a str,
296) -> OperationReport<'a> {
297 OperationReport {
298 operation_id: "site.create",
299 command_version: 1,
300 project_root: &plan.destination,
301 planned_filesystem_operations: plan
302 .files
303 .iter()
304 .map(|file| FilesystemOperation {
305 operation: "create",
306 path: &file.path,
307 bytes: file.bytes,
308 })
309 .collect(),
310 configuration_changes: selection,
311 warnings: Vec::new(),
312 result: OperationResult {
313 status,
314 destination: &plan.destination,
315 package,
316 title,
317 selection,
318 files: plan.files.len(),
319 next: format!("cd {} && proa run dev --open", plan.destination.display()),
320 },
321 }
322}
323
324fn run_child(root: &Path, args: &[&str]) -> Result<()> {
325 let executable = crate::util::current_executable().context("locate the running Proa CLI")?;
326 let status = Command::new(executable)
327 .args(args)
328 .current_dir(root)
329 .status()
330 .context("start Proa child command")?;
331 if !status.success() {
332 bail!("Proa child command failed with {status}");
333 }
334 Ok(())
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 use crate::capabilities::{DatabaseChoice, StylingChoice, UiChoice};
341
342 fn options(path: PathBuf) -> NewSiteOptions {
343 NewSiteOptions {
344 path,
345 destination: None,
346 title: None,
347 template: "app".to_string(),
348 overrides: CapabilityOverrides::default(),
349 vscode: true,
350 agents_md: true,
351 no_git: true,
352 verify: false,
353 start: false,
354 open: false,
355 offline: true,
356 dry_run: None,
357 json: false,
358 }
359 }
360
361 #[test]
362 fn default_tree_has_application_first_contract() {
363 let temp = tempfile::tempdir().unwrap();
364 let root = temp.path().join("journal");
365 new_site(options(root.clone())).unwrap();
366 for path in [
367 "src/db.rs",
368 "src/loader.rs",
369 "src/components/database_badge.rs",
370 "src/components/database_card.rs",
371 "src/components/badge/md.rs",
372 "migrations/.gitkeep",
373 "data/.gitkeep",
374 "tests/dataloader.rs",
375 "tests/representations.rs",
376 ] {
377 assert!(root.join(path).exists(), "missing {path}");
378 }
379 let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
382 assert!(!config.contains("build: proa::config::BuildConfig"));
383 assert!(!config.contains("paths: proa::config::ProjectPaths"));
384 let config = crate::config::load_project_config(&root).unwrap();
385 assert_eq!(config.paths.public.as_deref(), Some(Path::new("public")));
386 let [asset] = config.build.assets() else {
387 panic!("expected one inferred Tailwind asset");
388 };
389 assert_eq!(asset.kind, "tailwind");
390 assert_eq!(asset.input, Path::new("styles/input.css"));
391 assert_eq!(asset.output, Path::new("public/styles.css"));
392 let input = std::fs::read_to_string(root.join("styles/input.css")).unwrap();
393 assert!(input.contains("@import \"./starter.css\" layer(components);"));
394 let starter = std::fs::read_to_string(root.join("styles/starter.css")).unwrap();
395 assert_eq!(
396 starter,
397 std::fs::read_to_string(root.join("public/styles.css")).unwrap()
398 );
399 assert!(!root.join("scripts").exists());
400 assert!(!root.join("src/islands").exists());
401 assert!(!root.join("rust-toolchain.toml").exists());
402 let cargo_toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
403 assert!(cargo_toml.contains("rust-version = \"1.98\""));
404 let home = std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap();
405 let parsed_home = syn::parse_file(&home).unwrap();
406 let mut saw_non_use_item = false;
407 for item in &parsed_home.items {
408 if matches!(item, syn::Item::Use(_)) {
409 assert!(
410 !saw_non_use_item,
411 "src/pages/home.rs should keep all `use` imports at the top of the file"
412 );
413 } else {
414 saw_non_use_item = true;
415 }
416 }
417 assert!(home.contains("DataResolver::request_scope"));
418 assert!(home.contains("MdRender<L> for HomePage"));
419 assert!(home.contains("# {HEADLINE}"));
420 assert!(!home.contains("Rust\\."));
421 assert!(!home.contains("multi\\-target"));
422 let routes = std::fs::read_to_string(root.join("src/routes.rs")).unwrap();
423 assert!(routes.contains("PublicAssets::configured()"));
424 }
425
426 #[test]
427 fn every_preset_has_canonical_macros_and_clean_component_hashes() {
428 let temp = tempfile::tempdir().unwrap();
429 for template in ["minimal", "app", "marketing", "docs", "origin"] {
430 let root = temp.path().join(template);
431 let mut value = options(root.clone());
432 value.template = template.to_string();
433 new_site(value).unwrap();
434 assert!(!root.join(".cargo/config.toml").exists(), "{template}");
435 assert!(!root.join("rust-toolchain.toml").exists(), "{template}");
436 let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
437 assert!(!config.contains("template:"), "{template}");
438 let formatting =
439 crate::fmt::format_paths_with_options(&[root.clone()], true, true).unwrap();
440 assert!(
441 formatting.changed.is_empty() && formatting.diagnostics.is_empty(),
442 "{template}: {:?}",
443 formatting.diagnostics
444 );
445 let diagnostics =
446 crate::lint::lint_paths(&[root.join("src")], crate::lint::LintOptions::default())
447 .unwrap();
448 assert!(
449 diagnostics
450 .iter()
451 .all(|diagnostic| diagnostic.severity.rank()
452 < crate::diagnostic::Severity::Warning.rank()),
453 "{template}: {diagnostics:?}"
454 );
455 let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
456 assert!(report.errors.is_empty(), "{template}: {:?}", report.errors);
457 let routes = crate::scaffold::site_routes(Some(root)).unwrap();
458 let markdown = routes.iter().find(|route| route.path == "/index.md");
459 match template {
460 "minimal" => assert!(markdown.is_none()),
461 "origin" => assert_eq!(markdown.unwrap().file, Path::new("src/lib.rs")),
462 _ => assert_eq!(markdown.unwrap().file, Path::new("src/pages/home.rs")),
463 }
464 }
465 }
466
467 #[test]
468 fn customized_pages_preserve_capability_checks() {
469 let temp = tempfile::tempdir().unwrap();
470 let root = temp.path().join("customized");
471 new_site(options(root.clone())).unwrap();
472 let home_path = root.join("src/pages/home.rs");
473 let source = std::fs::read_to_string(&home_path)
474 .unwrap()
475 .replace("HomePage", "IssuePage")
476 .replace("/index.md", "/issues.md");
477 let issue_path = root.join("src/pages/issues.rs");
478 std::fs::write(&issue_path, &source).unwrap();
479 std::fs::write(
480 &home_path,
481 "pub async fn handler() -> &'static str { \"Welcome\" }\n",
482 )
483 .unwrap();
484 let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
485 assert!(report.errors.is_empty(), "{:?}", report.errors);
486
487 std::fs::write(
489 &issue_path,
490 source
491 .replace("DataResolver::request_scope", "DataResolver::new")
492 .replace("explicit_markdown_async_with_loader(", "other_response("),
493 )
494 .unwrap();
495 let report = crate::scaffold::site_check(Some(root)).unwrap();
496 assert!(report
497 .errors
498 .iter()
499 .any(|e| e.contains("request-scoped DataResolver")));
500 assert!(report
501 .errors
502 .iter()
503 .any(|e| e.contains("explicit_markdown(")));
504 }
505
506 #[test]
507 fn capability_deltas_remove_owned_outputs() {
508 let temp = tempfile::tempdir().unwrap();
509 let root = temp.path().join("bare");
510 let mut value = options(root.clone());
511 value.overrides.database = Some(DatabaseChoice::None);
512 value.overrides.ui = Some(UiChoice::None);
513 value.overrides.styling = Some(StylingChoice::Css);
514 value.vscode = false;
515 new_site(value).unwrap();
516 let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
517 assert!(config.contains("assets: Some(vec![])"));
518 assert!(!root.join("src/db.rs").exists());
519 assert!(!root.join("src/components/badge").exists());
520 assert!(!root.join("styles").exists());
521 assert!(!root.join(".vscode").exists());
522 }
523
524 #[test]
525 fn dry_run_and_nonempty_refusal_do_not_write() {
526 let temp = tempfile::tempdir().unwrap();
527 let root = temp.path().join("dry");
528 let mut value = options(root.clone());
529 value.dry_run = Some(DryRunFormat::Json);
530 new_site(value).unwrap();
531 assert!(!root.exists());
532
533 std::fs::create_dir(&root).unwrap();
534 std::fs::write(root.join("keep"), "mine").unwrap();
535 let error = new_site(options(root.clone())).unwrap_err();
536 assert!(error.to_string().contains("not empty"));
537 assert_eq!(std::fs::read_to_string(root.join("keep")).unwrap(), "mine");
538 }
539}