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 assert!(!root.join("scripts").exists());
365 assert!(!root.join("src/islands").exists());
366 let home = std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap();
367 syn::parse_file(&home).unwrap();
368 assert!(home.contains("DataResolver::request_scope"));
369 assert!(home.contains("MdRender<L> for HomePage"));
370 }
371
372 #[test]
373 fn every_preset_has_canonical_macros_and_clean_component_hashes() {
374 let temp = tempfile::tempdir().unwrap();
375 for template in ["minimal", "app", "marketing", "docs", "origin"] {
376 let root = temp.path().join(template);
377 let mut value = options(root.clone());
378 value.template = template.to_string();
379 new_site(value).unwrap();
380 for path in crate::source::find_rust_files(&[root.join("src")]).unwrap() {
381 let source = std::fs::read_to_string(&path).unwrap();
382 assert!(
383 !source.contains("content_part!"),
384 "{template}: {}",
385 path.display()
386 );
387 }
388 let formatting =
389 crate::fmt::format_paths_with_options(&[root.clone()], true, true).unwrap();
390 assert!(
391 formatting.changed.is_empty() && formatting.diagnostics.is_empty(),
392 "{template}: {:?}",
393 formatting.diagnostics
394 );
395 let diagnostics =
396 crate::lint::lint_paths(&[root.join("src")], crate::lint::LintOptions::default())
397 .unwrap();
398 assert!(
399 diagnostics
400 .iter()
401 .all(|diagnostic| diagnostic.severity.rank()
402 < crate::diagnostic::Severity::Warning.rank()),
403 "{template}: {diagnostics:?}"
404 );
405 let report = crate::scaffold::site_check(Some(root)).unwrap();
406 assert!(report.errors.is_empty(), "{template}: {:?}", report.errors);
407 }
408 }
409
410 #[test]
411 fn customized_pages_preserve_capability_checks() {
412 let temp = tempfile::tempdir().unwrap();
413 let root = temp.path().join("customized");
414 new_site(options(root.clone())).unwrap();
415 let home_path = root.join("src/pages/home.rs");
416 let source = std::fs::read_to_string(&home_path)
417 .unwrap()
418 .replace("HomePage", "IssuePage")
419 .replace("/index.md", "/issues.md");
420 let issue_path = root.join("src/pages/issues.rs");
421 std::fs::write(&issue_path, &source).unwrap();
422 std::fs::write(
423 &home_path,
424 "pub async fn handler() -> &'static str { \"Welcome\" }\n",
425 )
426 .unwrap();
427 let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
428 assert!(report.errors.is_empty(), "{:?}", report.errors);
429
430 std::fs::write(
432 &issue_path,
433 source
434 .replace("DataResolver::request_scope", "DataResolver::new")
435 .replace("explicit_markdown_async_with_loader(", "other_response("),
436 )
437 .unwrap();
438 let report = crate::scaffold::site_check(Some(root)).unwrap();
439 assert!(report
440 .errors
441 .iter()
442 .any(|e| e.contains("request-scoped DataResolver")));
443 assert!(report
444 .errors
445 .iter()
446 .any(|e| e.contains("explicit_markdown(")));
447 }
448
449 #[test]
450 fn capability_deltas_remove_owned_outputs() {
451 let temp = tempfile::tempdir().unwrap();
452 let root = temp.path().join("bare");
453 let mut value = options(root.clone());
454 value.overrides.database = Some(DatabaseChoice::None);
455 value.overrides.ui = Some(UiChoice::None);
456 value.overrides.styling = Some(StylingChoice::Css);
457 value.vscode = false;
458 new_site(value).unwrap();
459 assert!(!root.join("src/db.rs").exists());
460 assert!(!root.join("src/components/badge").exists());
461 assert!(!root.join("styles").exists());
462 assert!(!root.join(".vscode").exists());
463 }
464
465 #[test]
466 fn dry_run_and_nonempty_refusal_do_not_write() {
467 let temp = tempfile::tempdir().unwrap();
468 let root = temp.path().join("dry");
469 let mut value = options(root.clone());
470 value.dry_run = Some(DryRunFormat::Json);
471 new_site(value).unwrap();
472 assert!(!root.exists());
473
474 std::fs::create_dir(&root).unwrap();
475 std::fs::write(root.join("keep"), "mine").unwrap();
476 let error = new_site(options(root.clone())).unwrap_err();
477 assert!(error.to_string().contains("not empty"));
478 assert_eq!(std::fs::read_to_string(root.join("keep")).unwrap(), "mine");
479 }
480}