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