1use base16ct::HexDisplay;
5use std::{
6 env, fs,
7 path::{Path, PathBuf},
8};
9
10use anyhow::{bail, Context, Result};
11use clap::ValueEnum;
12use serde::Serialize;
13use sha2::{Digest, Sha256};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ValueEnum)]
16pub enum DryRunFormat {
17 Text,
18 Json,
19}
20
21pub struct GenerateComponentOptions {
22 pub name: String,
23 pub root: Option<PathBuf>,
24 pub folder: bool,
25 pub recipe: bool,
26 pub children: bool,
27 pub asynchronous: bool,
28 pub markdown: bool,
29 pub dry_run: Option<DryRunFormat>,
30 pub force: bool,
31}
32
33pub struct GenerateLayoutOptions {
34 pub name: String,
35 pub root: Option<PathBuf>,
36 pub document: bool,
37 pub section: bool,
38 pub replace_root: bool,
39 pub dry_run: Option<DryRunFormat>,
40 pub force: bool,
41}
42
43pub struct GenerateDataOptions {
44 pub name: String,
45 pub root: Option<PathBuf>,
46 pub dry_run: Option<DryRunFormat>,
47 pub force: bool,
48}
49
50#[derive(Debug, Default, Serialize)]
51pub struct ScaffoldPlan {
52 pub root: PathBuf,
53 pub operations: Vec<PlanOperation>,
54 pub warnings: Vec<String>,
55 pub follow_up: Vec<String>,
56}
57
58#[derive(Debug, Clone, Serialize)]
59#[serde(tag = "action", rename_all = "snake_case")]
60pub enum PlanOperation {
61 WriteFile {
62 path: PathBuf,
63 description: String,
64 bytes: usize,
65 #[serde(skip)]
66 content: String,
67 },
68 AppendLine {
69 path: PathBuf,
70 description: String,
71 line: String,
72 },
73}
74
75#[derive(Debug, Serialize)]
76pub struct SiteCheckReport {
77 pub root: PathBuf,
78 pub errors: Vec<String>,
79 pub warnings: Vec<String>,
80}
81
82#[derive(Debug, Serialize)]
83pub struct RouteInfo {
84 pub method: &'static str,
85 pub path: String,
86 pub kind: &'static str,
87 pub representations: String,
88 pub file: PathBuf,
89}
90
91pub fn generate_component(options: GenerateComponentOptions) -> Result<()> {
92 let root = resolve_root(options.root)?;
93 let target = ModuleTarget::new(&root, "components", &options.name)?;
94 let struct_name = pascal_case(&target.leaf);
95 let data_attr = format!("data-{}", kebab_case(&target.leaf));
96 let mut plan = ScaffoldPlan::new(root.clone());
97
98 target.plan_mod_updates(&mut plan);
99
100 if options.folder || options.recipe {
101 let dir = target.file_path.with_extension("");
102 plan.write_file(
103 dir.join("mod.rs"),
104 if options.recipe {
105 format!(
106 "mod {};\nmod recipe;\n\npub use {}::{};\npub use recipe::{}Recipe;\n",
107 target.leaf, target.leaf, struct_name, struct_name
108 )
109 } else {
110 format!(
111 "mod {};\n\npub use {}::{};\n",
112 target.leaf, target.leaf, struct_name
113 )
114 },
115 );
116 plan.write_template(
117 dir.join(format!("{}.rs", target.leaf)),
118 component_source(
119 &struct_name,
120 &data_attr,
121 options.children,
122 options.asynchronous,
123 options.markdown,
124 options.recipe,
125 ),
126 )?;
127 if options.recipe {
128 plan.write_file(dir.join("recipe.rs"), component_recipe_source(&struct_name));
129 }
130 } else {
131 plan.write_template(
132 target.file_path,
133 component_source(
134 &struct_name,
135 &data_attr,
136 options.children,
137 options.asynchronous,
138 options.markdown,
139 false,
140 ),
141 )?;
142 }
143
144 finish_plan(plan, options.dry_run, options.force)
145}
146
147pub fn generate_layout(options: GenerateLayoutOptions) -> Result<()> {
148 if options.document && options.section {
149 bail!("--document and --section cannot be combined");
150 }
151
152 let root = resolve_root(options.root)?;
153 let target = ModuleTarget::new(&root, "layouts", &options.name)?;
154 let struct_name = format!("{}Layout", pascal_case(&target.leaf));
155 let mut plan = ScaffoldPlan::new(root.clone());
156
157 if options.document {
158 let mut current_roots = Vec::new();
159 let layouts = root.join("src/layouts");
160 if layouts.is_dir() {
161 for path in rust_files(&layouts)? {
162 if path != target.file_path
163 && fs::read_to_string(&path)
164 .unwrap_or_default()
165 .contains("// proa:document-root")
166 {
167 current_roots.push(path);
168 }
169 }
170 }
171 if !current_roots.is_empty() && !options.replace_root {
172 bail!(
173 "a document root is already marked at {}; rerun with --replace-root",
174 display_rel(&root, ¤t_roots[0])
175 );
176 }
177 for path in current_roots {
178 let source = fs::read_to_string(&path)?
179 .replace("// proa:document-root", "// proa:document-layout");
180 plan.write_file(path, source);
181 }
182 }
183
184 target.plan_mod_updates(&mut plan);
185 let source = if options.document {
186 document_layout_source(&struct_name)
187 } else {
188 section_layout_source(&struct_name)
189 };
190 plan.write_template(target.file_path, source)?;
191
192 finish_plan(plan, options.dry_run, options.force || options.replace_root)
193}
194
195pub fn generate_data(options: GenerateDataOptions) -> Result<()> {
196 let root = resolve_root(options.root)?;
197 let target = ModuleTarget::new(&root, "static_data", &options.name)?;
198 let mut plan = ScaffoldPlan::new(root);
199
200 target.plan_mod_updates(&mut plan);
201 plan.write_file(target.file_path, data_source(&target.leaf));
202
203 finish_plan(plan, options.dry_run, options.force)
204}
205
206pub fn site_check(root: Option<PathBuf>) -> Result<SiteCheckReport> {
207 let root = resolve_root(root)?;
208 let config = crate::config::load_project_config(&root)?;
209 site_check_with_config(root, &config)
210}
211
212fn site_routes_in_library(root: &Path) -> bool {
213 !root.join("src/routes.rs").is_file()
214 && fs::read_to_string(root.join("src/lib.rs"))
215 .is_ok_and(|source| source.contains("router_from_spec("))
216}
217
218pub(crate) fn site_check_with_config(
219 root: PathBuf,
220 config: &crate::config::ProjectConfig,
221) -> Result<SiteCheckReport> {
222 let mut report = SiteCheckReport {
223 root: root.clone(),
224 errors: Vec::new(),
225 warnings: Vec::new(),
226 };
227
228 let application_first = config.application.is_some();
229 let required: &[&str] = if site_routes_in_library(&root) {
230 &[
231 "src/lib.rs",
232 "src/main.rs",
233 "src/components/mod.rs",
234 "src/layouts/mod.rs",
235 "public/styles.css",
236 ]
237 } else if application_first {
238 &[
239 "src/pages/mod.rs",
240 "src/components/mod.rs",
241 "src/layouts/mod.rs",
242 "src/endpoints/mod.rs",
243 "src/routes.rs",
244 "src/app.rs",
245 "src/config.rs",
246 "src/error.rs",
247 "src/static_assets.rs",
248 ]
249 } else {
250 &[
251 "src/pages/mod.rs",
252 "src/components/mod.rs",
253 "src/layouts/mod.rs",
254 "src/data/mod.rs",
255 ]
256 };
257 for rel in required {
258 if !root.join(rel).exists() {
259 report.errors.push(format!("missing {rel}"));
260 }
261 }
262
263 if root.join("src/islands").exists() {
264 report
265 .errors
266 .push("src/islands should not be generated for this site convention".to_string());
267 }
268
269 if application_first {
270 let sources = rust_files(&root.join("src"))?
272 .into_iter()
273 .map(fs::read_to_string)
274 .collect::<std::io::Result<Vec<_>>>()?;
275 let has_source = |needle: &str| sources.iter().any(|source| source.contains(needle));
276 if domain_root_is_empty(&root.join("src/models"))
277 || domain_root_is_empty(&root.join("src/services"))
278 {
279 report.errors.push(
280 "empty domain roots must not be generated; create models/services on demand"
281 .to_string(),
282 );
283 }
284 let database = config.database.as_ref().map(|value| value.driver);
285 if database == Some(crate::config::DatabaseDriver::Sqlite) {
286 let manual = config
287 .database
288 .as_ref()
289 .map(|value| value.integration.as_str())
290 .filter(|value| !value.is_empty())
291 == Some("manual");
292 let required_database_files: &[&str] = if manual {
293 &["src/db.rs", "data/.gitkeep", "migrations/.gitkeep"]
294 } else {
295 &[
296 "src/db.rs",
297 "src/loader.rs",
298 "data/.gitkeep",
299 "migrations/.gitkeep",
300 ]
301 };
302 for rel in required_database_files {
303 if !root.join(rel).exists() {
304 report
305 .errors
306 .push(format!("SQLite capability is missing {rel}"));
307 }
308 }
309 if manual {
310 report.warnings.push(
311 "SQLite is installed with manual integration pending; add `mod db;`, connect the pool, and place it in application state"
312 .to_string(),
313 );
314 } else {
315 if !has_source("DataResolver::request_scope") {
316 report.errors.push(
317 "SQLite application does not create a request-scoped DataResolver"
318 .to_string(),
319 );
320 }
321 }
322 }
323 let lock = crate::config::load_component_lock(&root)?;
324 let markdown = lock.scaffold_markdown() == Some(true)
325 && lock.scaffold_capabilities().any(|id| id == "base:site");
326 if markdown {
327 for (sync, asynchronous) in [
328 ("MdRenderSync", "MdRender<"),
329 ("explicit_markdown(", "explicit_markdown_async_with_loader("),
330 ] {
331 if !has_source(sync) && !has_source(asynchronous) {
332 report.errors.push(format!(
333 "Markdown representation contract is missing `{sync}`"
334 ));
335 }
336 }
337 let layout = fs::read_to_string(root.join("src/layouts/root.rs")).unwrap_or_default();
338 if layout.contains("MdRender") {
339 report
340 .errors
341 .push("RootDocument must remain HTML-only".to_string());
342 }
343 }
344 let validation = crate::config::validate_build_config(&root, config);
345 report.errors.extend(validation.errors);
346 report.warnings.extend(validation.warnings);
347 for rel in [
348 ".vscode/extensions.json",
349 ".vscode/settings.json",
350 ".vscode/tasks.json",
351 ] {
352 let path = root.join(rel);
353 if path.exists()
354 && fs::read_to_string(&path)
355 .ok()
356 .and_then(|source| serde_json::from_str::<serde_json::Value>(&source).ok())
357 .is_none()
358 {
359 report.errors.push(format!("{rel} is not valid JSON"));
360 }
361 }
362 validate_component_hashes(&root, &mut report)?;
363 validate_migration_pairs(&root, &mut report)?;
364 }
365
366 let pages_dir = root.join("src/pages");
367 if pages_dir.exists() {
368 for file in rust_files(&pages_dir)? {
369 if file.file_name().and_then(|name| name.to_str()) == Some("mod.rs") {
370 continue;
371 }
372 let source =
373 fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
374 if !source.contains("fn handler") && !source.contains("fn render") {
375 report.errors.push(format!(
377 "{} does not expose a handler or render function",
378 display_rel(&root, &file)
379 ));
380 }
381 }
382 }
383
384 Ok(report)
385}
386
387fn domain_root_is_empty(path: &Path) -> bool {
388 if !path.is_dir() {
389 return false;
390 }
391 fs::read_dir(path)
392 .ok()
393 .into_iter()
394 .flatten()
395 .filter_map(Result::ok)
396 .all(|entry| entry.file_name() == "mod.rs")
397}
398
399fn validate_component_hashes(root: &Path, report: &mut SiteCheckReport) -> Result<()> {
400 let lock_path = root.join(crate::config::LOCK_FILE);
401 if !lock_path.is_file() {
402 return Ok(());
403 }
404 let lock: serde_json::Value = serde_json::from_str(&fs::read_to_string(&lock_path)?)?;
405 let Some(components) = lock
406 .get("components")
407 .and_then(serde_json::Value::as_object)
408 else {
409 return Ok(());
410 };
411 for (component, value) in components {
412 let Some(files) = value.get("files").and_then(serde_json::Value::as_object) else {
413 continue;
414 };
415 for (relative, expected) in files {
416 let path = root.join(relative);
417 let actual = fs::read(&path)
418 .ok()
419 .map(|bytes| format!("sha256:{:x}", HexDisplay(&Sha256::digest(bytes))));
420 if actual.as_deref() != expected.as_str() {
421 report.errors.push(format!(
422 "component {component} has local drift in {relative}"
423 ));
424 }
425 }
426 }
427 Ok(())
428}
429
430fn validate_migration_pairs(root: &Path, report: &mut SiteCheckReport) -> Result<()> {
431 let directory = root.join("migrations");
432 if !directory.is_dir() {
433 return Ok(());
434 }
435 let mut up = std::collections::BTreeSet::new();
436 let mut down = std::collections::BTreeSet::new();
437 for entry in fs::read_dir(directory)? {
438 let name = entry?.file_name().to_string_lossy().into_owned();
439 if let Some(base) = name.strip_suffix(".up.sql") {
440 up.insert(base.to_string());
441 } else if let Some(base) = name.strip_suffix(".down.sql") {
442 down.insert(base.to_string());
443 }
444 }
445 for missing in up.difference(&down) {
446 report
447 .errors
448 .push(format!("migration {missing} is missing its .down.sql pair"));
449 }
450 for missing in down.difference(&up) {
451 report
452 .errors
453 .push(format!("migration {missing} is missing its .up.sql pair"));
454 }
455 Ok(())
456}
457
458pub fn print_site_check(report: &SiteCheckReport, json: bool) -> Result<()> {
459 if json {
460 println!("{}", serde_json::to_string_pretty(report)?);
461 return Ok(());
462 }
463
464 if report.errors.is_empty() {
465 println!("Proa site check passed for {}", report.root.display());
466 } else {
467 for error in &report.errors {
468 eprintln!("error: {error}");
469 }
470 }
471 for warning in &report.warnings {
472 eprintln!("warning: {warning}");
473 }
474 Ok(())
475}
476
477pub fn site_routes(root: Option<PathBuf>) -> Result<Vec<RouteInfo>> {
478 let root = resolve_root(root)?;
479 let config = crate::config::load_project_config(&root)?;
480 if config.application.is_some() {
481 let (router_file, home_file, health_file) = if site_routes_in_library(&root) {
482 ("src/lib.rs", "src/lib.rs", "src/lib.rs")
483 } else {
484 (
485 "src/routes.rs",
486 "src/pages/home.rs",
487 "src/endpoints/health.rs",
488 )
489 };
490 let generated_routes = fs::read_to_string(root.join(router_file)).unwrap_or_default();
491 let markdown = generated_routes.contains(".route(\"/index.md\"");
492 let mut routes = vec![RouteInfo {
493 method: "GET",
494 path: "/".to_string(),
495 kind: "page",
496 representations: if markdown {
497 "html · md:/index.md".to_string()
498 } else {
499 "html".to_string()
500 },
501 file: PathBuf::from(home_file),
502 }];
503 if markdown {
504 routes.push(RouteInfo {
505 method: "GET",
506 path: "/index.md".to_string(),
507 kind: "representation",
508 representations: "markdown".to_string(),
509 file: PathBuf::from(home_file),
510 });
511 }
512 for path in ["/healthz", "/readyz"] {
513 routes.push(RouteInfo {
514 method: "GET",
515 path: path.to_string(),
516 kind: "endpoint",
517 representations: "json".to_string(),
518 file: PathBuf::from(health_file),
519 });
520 }
521 for line in generated_routes.lines() {
522 let trimmed = line.trim();
523 if !trimmed.starts_with("Route::endpoint(\"") {
524 continue;
525 }
526 let Some(route_path) = trimmed
527 .strip_prefix("Route::endpoint(\"")
528 .and_then(|rest| rest.split('\"').next())
529 else {
530 continue;
531 };
532 if route_path == "/" || routes.iter().any(|route| route.path == route_path) {
533 continue;
534 }
535 let (kind, module, method) = if let Some(rest) = trimmed.split("pages::").nth(1) {
536 ("page", rest.split("::").next().unwrap_or("unknown"), "GET")
537 } else if let Some(rest) = trimmed.split("endpoints::").nth(1) {
538 let method = ["get", "post", "put", "patch", "delete"]
539 .into_iter()
540 .find(|method| trimmed.contains(&format!("routing::{method}(")))
541 .unwrap_or("get");
542 (
543 "endpoint",
544 rest.split("::").next().unwrap_or("unknown"),
545 match method {
546 "post" => "POST",
547 "put" => "PUT",
548 "patch" => "PATCH",
549 "delete" => "DELETE",
550 _ => "GET",
551 },
552 )
553 } else {
554 continue;
555 };
556 let markdown_alias = format!("{route_path}.md");
557 let has_markdown = kind == "page"
558 && (trimmed.contains("::handler_with_markdown_alias)")
559 || generated_routes.contains(&format!(".route(\"{markdown_alias}\"")));
560 routes.push(RouteInfo {
561 method,
562 path: route_path.to_string(),
563 kind,
564 representations: if has_markdown {
565 format!("html · md:{markdown_alias}")
566 } else if kind == "page" {
567 "html".to_string()
568 } else {
569 "response".to_string()
570 },
571 file: PathBuf::from(format!("src/{}s/{module}.rs", kind)),
572 });
573 if has_markdown {
574 routes.push(RouteInfo {
575 method: "GET",
576 path: markdown_alias,
577 kind: "representation",
578 representations: "markdown".to_string(),
579 file: PathBuf::from(format!("src/pages/{module}.rs")),
580 });
581 }
582 }
583 routes.sort_by(|left, right| left.path.cmp(&right.path));
584 return Ok(routes);
585 }
586 let pages_dir = root.join("src/pages");
587 let mut routes = Vec::new();
588 if !pages_dir.exists() {
589 return Ok(routes);
590 }
591
592 for file in rust_files(&pages_dir)? {
593 if file.file_name().and_then(|name| name.to_str()) == Some("mod.rs") {
594 continue;
595 }
596 let rel = file.strip_prefix(&pages_dir).unwrap_or(&file);
597 routes.push(RouteInfo {
598 method: "GET",
599 path: route_path_for_page(rel),
600 kind: "page",
601 representations: "html".to_string(),
602 file: display_rel_path(&root, &file),
603 });
604 }
605 routes.sort_by(|a, b| a.path.cmp(&b.path));
606 Ok(routes)
607}
608
609pub fn print_routes(routes: &[RouteInfo], json: bool) -> Result<()> {
610 if json {
611 println!("{}", serde_json::to_string_pretty(routes)?);
612 return Ok(());
613 }
614
615 println!("METHOD PATH KIND REPRESENTATIONS SOURCE");
616 for route in routes {
617 println!(
618 "{:<7} {:<32} {:<15} {:<27} {}",
619 route.method,
620 route.path,
621 route.kind,
622 route.representations,
623 route.file.display()
624 );
625 }
626 Ok(())
627}
628
629impl ScaffoldPlan {
630 fn new(root: PathBuf) -> Self {
631 Self {
632 root,
633 operations: Vec::new(),
634 warnings: Vec::new(),
635 follow_up: Vec::new(),
636 }
637 }
638
639 fn write_file(&mut self, path: PathBuf, content: String) {
640 self.operations.push(PlanOperation::WriteFile {
641 description: "write file".to_string(),
642 path,
643 bytes: content.len(),
644 content,
645 });
646 }
647
648 fn write_template(&mut self, path: PathBuf, source: String) -> Result<()> {
649 let formatted = format_generated_rust(&path, &source)?;
650 self.write_file(path, formatted);
651 Ok(())
652 }
653
654 fn append_line(&mut self, path: PathBuf, line: String, description: impl Into<String>) {
655 self.operations.push(PlanOperation::AppendLine {
656 path,
657 line,
658 description: description.into(),
659 });
660 }
661}
662
663pub(crate) fn format_generated_rust(path: &Path, source: &str) -> Result<String> {
664 let formatted = crate::fmt::format_file(path, source)?;
665 if !formatted.diagnostics.is_empty() {
666 bail!(
667 "Proa formatting failed for generated {}: {:?}",
668 path.display(),
669 formatted.diagnostics
670 );
671 }
672 let verification = crate::fmt::verify_render_preserving(path, source, &formatted.output);
673 if !verification.is_empty() {
674 bail!(
675 "Proa formatting changed render semantics for generated {}: {:?}",
676 path.display(),
677 verification
678 );
679 }
680 Ok(formatted.output)
681}
682
683fn finish_plan(plan: ScaffoldPlan, dry_run: Option<DryRunFormat>, force: bool) -> Result<()> {
684 if let Some(format) = dry_run {
685 match format {
686 DryRunFormat::Text => print_plan(&plan),
687 DryRunFormat::Json => println!("{}", serde_json::to_string_pretty(&plan)?),
688 }
689 return Ok(());
690 }
691
692 preflight(&plan, force)?;
693 apply_plan(&plan, force)?;
694 print_plan(&plan);
695 Ok(())
696}
697
698fn print_plan(plan: &ScaffoldPlan) {
699 for operation in &plan.operations {
700 match operation {
701 PlanOperation::WriteFile { path, .. } => println!("create {}", path.display()),
702 PlanOperation::AppendLine { path, .. } => println!("update {}", path.display()),
703 }
704 }
705 for warning in &plan.warnings {
706 eprintln!("warning: {warning}");
707 }
708 if !plan.follow_up.is_empty() {
709 println!("\nNext steps:");
710 for step in &plan.follow_up {
711 println!("- {step}");
712 }
713 }
714}
715
716fn preflight(plan: &ScaffoldPlan, force: bool) -> Result<()> {
717 if force {
718 return Ok(());
719 }
720
721 for operation in &plan.operations {
722 if let PlanOperation::WriteFile { path, .. } = operation {
723 if path.exists() {
724 bail!(
725 "{} already exists (use --force to overwrite)",
726 path.display()
727 );
728 }
729 }
730 }
731 Ok(())
732}
733
734fn apply_plan(plan: &ScaffoldPlan, force: bool) -> Result<()> {
735 let mut journal: Vec<(PathBuf, Option<String>)> = Vec::new();
738 let outcome = apply_operations(plan, force, &mut journal);
739 if outcome.is_err() {
740 rollback(&journal);
741 }
742 outcome
743}
744
745fn apply_operations(
746 plan: &ScaffoldPlan,
747 force: bool,
748 journal: &mut Vec<(PathBuf, Option<String>)>,
749) -> Result<()> {
750 for operation in &plan.operations {
751 match operation {
752 PlanOperation::WriteFile { path, content, .. } => {
753 if path.exists() && !force {
754 bail!(
755 "{} already exists (use --force to overwrite)",
756 path.display()
757 );
758 }
759 if let Some(parent) = path.parent() {
760 fs::create_dir_all(parent)
761 .with_context(|| format!("create {}", parent.display()))?;
762 }
763 journal.push((path.clone(), fs::read_to_string(path).ok()));
764 fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
765 }
766 PlanOperation::AppendLine { path, line, .. } => {
767 if let Some(parent) = path.parent() {
768 fs::create_dir_all(parent)
769 .with_context(|| format!("create {}", parent.display()))?;
770 }
771 let mut current = fs::read_to_string(path).unwrap_or_default();
772 if !current
773 .lines()
774 .any(|existing| existing.trim() == line.trim())
775 {
776 journal.push((path.clone(), fs::read_to_string(path).ok()));
777 if !current.is_empty() && !current.ends_with('\n') {
778 current.push('\n');
779 }
780 current.push_str(line);
781 current.push('\n');
782 fs::write(path, current)
783 .with_context(|| format!("update {}", path.display()))?;
784 }
785 }
786 }
787 }
788 Ok(())
789}
790
791fn rollback(journal: &[(PathBuf, Option<String>)]) {
792 for (path, prior) in journal.iter().rev() {
793 let restored = match prior {
794 Some(content) => fs::write(path, content),
795 None => fs::remove_file(path),
796 };
797 if restored.is_err() {
798 eprintln!(
799 "warning: could not roll back {} after a failed scaffold",
800 path.display()
801 );
802 }
803 }
804}
805
806struct ModuleTarget {
807 leaf: String,
808 file_path: PathBuf,
809 mod_updates: Vec<(PathBuf, String)>,
810}
811
812impl ModuleTarget {
813 fn new(root: &Path, bucket: &str, raw_name: &str) -> Result<Self> {
814 let parts: Vec<String> = raw_name
815 .split('/')
816 .filter(|part| !part.is_empty())
817 .map(snake_case)
818 .collect();
819 if parts.is_empty() {
820 bail!("name cannot be empty");
821 }
822 let leaf = parts.last().cloned().unwrap();
823 let base = root.join("src").join(bucket);
824 let mut dir = base.clone();
825 let mut mod_updates = Vec::new();
826
827 for (index, part) in parts.iter().enumerate() {
828 let mod_path = if index == 0 {
829 base.join("mod.rs")
830 } else {
831 base.join(parts[..index].join("/")).join("mod.rs")
832 };
833 mod_updates.push((mod_path, format!("pub mod {part};")));
834 if index + 1 < parts.len() {
835 dir.push(part);
836 }
837 }
838
839 Ok(Self {
840 leaf,
841 file_path: dir.join(format!("{}.rs", parts.last().unwrap())),
842 mod_updates,
843 })
844 }
845
846 fn plan_mod_updates(&self, plan: &mut ScaffoldPlan) {
847 for (path, line) in &self.mod_updates {
848 plan.append_line(path.clone(), line.clone(), "add module export");
849 }
850 }
851}
852
853pub fn resolve_root(root: Option<PathBuf>) -> Result<PathBuf> {
854 if let Some(root) = root {
855 return Ok(root);
856 }
857
858 let mut current = env::current_dir()?;
859 loop {
860 if current.join("Cargo.toml").exists() && current.join("src").exists() {
861 return Ok(current);
862 }
863 if !current.pop() {
864 bail!("could not find a Proa project root (pass --root)");
865 }
866 }
867}
868
869fn rust_files(root: &Path) -> Result<Vec<PathBuf>> {
870 let mut files = Vec::new();
871 collect_rust_files(root, &mut files)?;
872 Ok(files)
873}
874
875fn collect_rust_files(root: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
876 for entry in fs::read_dir(root).with_context(|| format!("read {}", root.display()))? {
877 let entry = entry?;
878 let path = entry.path();
879 if path.is_dir() {
880 collect_rust_files(&path, files)?;
881 } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
882 files.push(path);
883 }
884 }
885 Ok(())
886}
887
888fn route_path_for_page(rel: &Path) -> String {
889 let mut parts: Vec<String> = rel
890 .with_extension("")
891 .components()
892 .filter_map(|component| component.as_os_str().to_str().map(str::to_string))
893 .collect();
894 if parts.last().is_some_and(|part| part == "index") {
895 parts.pop();
896 }
897 if parts.len() == 1 && parts[0] == "home" {
898 return "/".to_string();
899 }
900 if parts.is_empty() {
901 "/".to_string()
902 } else {
903 format!("/{}", parts.join("/").replace('_', "-"))
904 }
905}
906
907fn display_rel(root: &Path, path: &Path) -> String {
908 display_rel_path(root, path).display().to_string()
909}
910
911fn display_rel_path(root: &Path, path: &Path) -> PathBuf {
912 path.strip_prefix(root).unwrap_or(path).to_path_buf()
913}
914
915fn snake_case(value: &str) -> String {
916 normalize_case(value, '_')
917}
918
919fn kebab_case(value: &str) -> String {
920 normalize_case(value, '-')
921}
922
923fn normalize_case(value: &str, separator: char) -> String {
924 let mut out = String::new();
925 let mut last_was_sep = false;
926 for ch in value.chars() {
927 if ch.is_ascii_alphanumeric() {
928 out.push(ch.to_ascii_lowercase());
929 last_was_sep = false;
930 } else if !last_was_sep && !out.is_empty() {
931 out.push(separator);
932 last_was_sep = true;
933 }
934 }
935 while out.ends_with(separator) {
936 out.pop();
937 }
938 if out.is_empty() {
939 out.push_str("generated");
940 }
941 if out.starts_with(|ch: char| ch.is_ascii_digit()) {
942 out.insert(0, separator);
943 }
944 out
945}
946
947fn pascal_case(value: &str) -> String {
948 let mut out = String::new();
949 for part in value
950 .split(|ch: char| !ch.is_ascii_alphanumeric())
951 .filter(|part| !part.is_empty())
952 {
953 let mut chars = part.chars();
954 if let Some(first) = chars.next() {
955 out.push(first.to_ascii_uppercase());
956 for ch in chars {
957 out.push(ch.to_ascii_lowercase());
958 }
959 }
960 }
961 if out.is_empty() {
962 out.push_str("Generated");
963 }
964 if out.starts_with(|ch: char| ch.is_ascii_digit()) {
965 out.insert_str(0, "Generated");
966 }
967 out
968}
969
970fn fill(mut template: String, replacements: &[(&str, &str)]) -> String {
971 for (needle, value) in replacements {
972 template = template.replace(needle, value);
973 }
974 template
975}
976
977fn nav_data() -> String {
978 "pub struct NavItem {\n pub label: &'static str,\n pub href: &'static str,\n}\n\npub const NAV_ITEMS: &[NavItem] = &[\n NavItem { label: \"Home\", href: \"/\" },\n];\n".to_string()
979}
980
981fn component_source(
984 struct_name: &str,
985 data_attr: &str,
986 children: bool,
987 asynchronous: bool,
988 markdown: bool,
989 recipe: bool,
990) -> String {
991 let base = if recipe {
992 "use super::recipe::BASE_CLASS;\n"
993 } else {
994 "const BASE_CLASS: &str = \"rounded-lg border p-4\";\n"
995 };
996 let template = match (children, asynchronous) {
997 (true, false) => {
998 r#"use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
999use proa::html_sync;
1000
1001__BASE__
1002pub struct __STRUCT__<C = ()> {
1003 pub class: Option<&'static str>,
1004 pub children: C,
1005}
1006
1007impl<C> __STRUCT__<C> {
1008 pub const fn new(children: C) -> Self {
1009 Self { class: None, children }
1010 }
1011
1012 pub const fn class(mut self, class: &'static str) -> Self {
1013 self.class = Some(class);
1014 self
1015 }
1016}
1017
1018impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1019where
1020 L: DataLoader,
1021 C: WebRenderSync<L>,
1022{
1023 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1024 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1025 html_sync! {
1026 <div __DATA__ class={classes}>{self.children}</div>
1027 }
1028 .render(cx)
1029 }
1030}
1031"#
1032 }
1033 (false, false) => {
1034 r#"use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
1035use proa::html_sync;
1036
1037__BASE__
1038#[derive(Debug, Clone, Copy, Default)]
1039pub struct __STRUCT__ {
1040 pub class: Option<&'static str>,
1041}
1042
1043impl __STRUCT__ {
1044 pub const fn new() -> Self {
1045 Self { class: None }
1046 }
1047
1048 pub const fn class(mut self, class: &'static str) -> Self {
1049 self.class = Some(class);
1050 self
1051 }
1052}
1053
1054impl<L: DataLoader> WebRenderSync<L> for __STRUCT__ {
1055 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1056 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1057 html_sync! {
1058 <div __DATA__ class={classes}>"__STRUCT__"</div>
1059 }
1060 .render(cx)
1061 }
1062}
1063"#
1064 }
1065 (true, true) => {
1066 r#"use std::future::Future;
1067
1068use proa::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
1069use proa::html;
1070
1071__BASE__
1072pub struct __STRUCT__<C = ()> {
1073 pub class: Option<&'static str>,
1074 pub children: C,
1075}
1076
1077impl<C> __STRUCT__<C> {
1078 pub const fn new(children: C) -> Self {
1079 Self { class: None, children }
1080 }
1081
1082 pub const fn class(mut self, class: &'static str) -> Self {
1083 self.class = Some(class);
1084 self
1085 }
1086}
1087
1088impl<L, C> WebRender<L> for __STRUCT__<C>
1089where
1090 L: DataLoader,
1091 C: WebRender<L>,
1092{
1093 fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
1094 RenderOutcome::pending(async move {
1095 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1096 html! {
1097 <div __DATA__ class={classes}>{self.children}</div>
1098 }
1099 .render(cx)
1100 .resolve()
1101 .await
1102 })
1103 }
1104}
1105"#
1106 }
1107 (false, true) => {
1108 r#"use std::future::Future;
1109
1110use proa::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
1111use proa::html;
1112
1113__BASE__
1114#[derive(Debug, Clone, Copy, Default)]
1115pub struct __STRUCT__ {
1116 pub class: Option<&'static str>,
1117}
1118
1119impl __STRUCT__ {
1120 pub const fn new() -> Self {
1121 Self { class: None }
1122 }
1123
1124 pub const fn class(mut self, class: &'static str) -> Self {
1125 self.class = Some(class);
1126 self
1127 }
1128}
1129
1130impl<L: DataLoader> WebRender<L> for __STRUCT__ {
1131 fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
1132 RenderOutcome::pending(async move {
1133 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1134 html! {
1135 <div __DATA__ class={classes}>
1136 {proa::await_component(async { proa::text::text("__STRUCT__") })}
1137 </div>
1138 }
1139 .render(cx)
1140 .resolve()
1141 .await
1142 })
1143 }
1144}
1145"#
1146 }
1147 };
1148
1149 let markdown_source = if markdown {
1150 if children {
1151 r####"
1152use proa::{MdRenderSync, WriteBuf};
1153use proa::md_sync;
1154
1155impl<L: proa::DataLoader, B, C> MdRenderSync<L, B> for __STRUCT__<C>
1156where
1157 B: WriteBuf,
1158 C: MdRenderSync<L, B>,
1159{
1160 fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
1161 md_sync! { r###"
1162 ### __STRUCT__
1163
1164 {self.children}
1165 "###
1166 }
1167 .render_md(cx)
1168 }
1169}
1170"####
1171 } else {
1172 r####"
1173use proa::{MdRenderSync, WriteBuf};
1174use proa::md_sync;
1175
1176impl<L: proa::DataLoader, B: WriteBuf> MdRenderSync<L, B> for __STRUCT__ {
1177 fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
1178 md_sync! { r###"__STRUCT__"### }.render_md(cx)
1179 }
1180}
1181"####
1182 }
1183 } else {
1184 ""
1185 };
1186
1187 fill(
1188 format!("{template}{markdown_source}"),
1189 &[
1190 ("__BASE__", base),
1191 ("__STRUCT__", struct_name),
1192 ("__DATA__", data_attr),
1193 ],
1194 )
1195}
1196
1197fn component_recipe_source(struct_name: &str) -> String {
1198 fill(
1199 r#"pub const BASE_CLASS: &str = "rounded-lg border p-4";
1200
1201pub struct __STRUCT__Recipe {
1202 pub class: &'static str,
1203}
1204
1205impl Default for __STRUCT__Recipe {
1206 fn default() -> Self {
1207 Self { class: BASE_CLASS }
1208 }
1209}
1210"#
1211 .to_string(),
1212 &[("__STRUCT__", struct_name)],
1213 )
1214}
1215
1216fn section_layout_source(struct_name: &str) -> String {
1217 fill(
1218 r#"use proa::{DataLoader, WebContext, WebRenderSync, WriteError};
1219use proa::html_sync;
1220
1221pub struct __STRUCT__<C> {
1222 pub content: C,
1223}
1224
1225impl<C> __STRUCT__<C> {
1226 pub const fn new(content: C) -> Self {
1227 Self { content }
1228 }
1229}
1230
1231impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1232where
1233 L: DataLoader,
1234 C: WebRenderSync<L>,
1235{
1236 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1237 html_sync! {
1238 <section class="mx-auto max-w-5xl px-6 py-12">{self.content}</section>
1239 }
1240 .render(cx)
1241 }
1242}
1243"#
1244 .to_string(),
1245 &[("__STRUCT__", struct_name)],
1246 )
1247}
1248
1249fn document_layout_source(struct_name: &str) -> String {
1250 fill(
1251 r#"// proa:document-root
1252use proa::{raw_text_ok, DataLoader, WebContext, WebRenderSync, WriteError};
1253use proa::html_sync;
1254
1255pub struct __STRUCT__<C> {
1256 pub title: &'static str,
1257 pub description: &'static str,
1258 pub content: C,
1259}
1260
1261impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1262where
1263 L: DataLoader,
1264 C: WebRenderSync<L>,
1265{
1266 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1267 html_sync! {
1268 <!DOCTYPE html>
1269 <html lang="en">
1270 <head>
1271 <meta charset="utf-8" />
1272 <meta name="viewport" content="width=device-width, initial-scale=1" />
1273 <title>{raw_text_ok(self.title)}</title>
1274 <meta name="description" content={self.description} />
1275 </head>
1276 <body>{self.content}</body>
1277 </html>
1278 }
1279 .render(cx)
1280 }
1281}
1282"#
1283 .to_string(),
1284 &[("__STRUCT__", struct_name)],
1285 )
1286}
1287
1288fn data_source(name: &str) -> String {
1289 if name == "routes" {
1290 "pub const ROUTES: &[&str] = &[\"/\"];\n".to_string()
1291 } else if name == "nav" {
1292 nav_data()
1293 } else {
1294 format!(
1295 "pub struct {}Item {{\n pub label: &'static str,\n}}\n\npub const ITEMS: &[{}Item] = &[];\n",
1296 pascal_case(name),
1297 pascal_case(name)
1298 )
1299 }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304 use super::*;
1305
1306 #[test]
1307 fn apply_plan_rolls_back_files_on_mid_plan_failure() {
1308 let temp = tempfile::tempdir().unwrap();
1309 let root = temp.path().to_path_buf();
1310 let mut plan = ScaffoldPlan::new(root.clone());
1311 plan.write_file(root.join("ok.txt"), "hello".to_string());
1312 let blocked = root.join("blocked");
1314 fs::create_dir_all(&blocked).unwrap();
1315 plan.write_file(blocked.clone(), "nope".to_string());
1316
1317 apply_plan(&plan, true).unwrap_err();
1318 assert!(
1319 !root.join("ok.txt").exists(),
1320 "files from the failed plan should be rolled back"
1321 );
1322 }
1323
1324 #[test]
1325 fn apply_plan_rollback_restores_overwritten_files() {
1326 let temp = tempfile::tempdir().unwrap();
1327 let root = temp.path().to_path_buf();
1328 fs::write(root.join("keep.txt"), "original").unwrap();
1329 let mut plan = ScaffoldPlan::new(root.clone());
1330 plan.write_file(root.join("keep.txt"), "replaced".to_string());
1331 let blocked = root.join("blocked");
1332 fs::create_dir_all(&blocked).unwrap();
1333 plan.write_file(blocked.clone(), "nope".to_string());
1334
1335 apply_plan(&plan, true).unwrap_err();
1336 assert_eq!(
1337 fs::read_to_string(root.join("keep.txt")).unwrap(),
1338 "original",
1339 "overwritten files should be restored on rollback"
1340 );
1341 }
1342
1343 #[test]
1344 fn generate_component_updates_mod_file() {
1345 let temp = tempfile::tempdir().unwrap();
1346 fs::create_dir_all(temp.path().join("src/components")).unwrap();
1347 fs::write(temp.path().join("Cargo.toml"), "[package]\nname=\"demo\"\n").unwrap();
1348 fs::write(temp.path().join("src/components/mod.rs"), "").unwrap();
1349
1350 generate_component(GenerateComponentOptions {
1351 name: "marketing-card".to_string(),
1352 root: Some(temp.path().to_path_buf()),
1353 folder: false,
1354 recipe: false,
1355 children: false,
1356 asynchronous: false,
1357 markdown: false,
1358 dry_run: None,
1359 force: false,
1360 })
1361 .unwrap();
1362
1363 let module = fs::read_to_string(temp.path().join("src/components/mod.rs")).unwrap();
1364 assert!(module.contains("pub mod marketing_card;"));
1365 assert!(temp
1366 .path()
1367 .join("src/components/marketing_card.rs")
1368 .exists());
1369
1370 let source =
1371 fs::read_to_string(temp.path().join("src/components/marketing_card.rs")).unwrap();
1372 assert!(source
1373 .contains("use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};"));
1374 assert!(source.contains("impl<L: DataLoader> WebRenderSync<L> for MarketingCard"));
1375 assert!(source.contains("fn render(self, cx: &mut WebContext<L>)"));
1376 syn::parse_file(&source).expect("generated component must be valid Rust syntax");
1377 }
1378
1379 #[test]
1380 fn generated_component_with_children_uses_default_writer() {
1381 let source = component_source(
1382 "MarketingCard",
1383 "data-marketing-card",
1384 true,
1385 false,
1386 false,
1387 false,
1388 );
1389
1390 assert!(source.contains("impl<L, C> WebRenderSync<L> for MarketingCard<C>"));
1391 assert!(source.contains("C: WebRenderSync<L>"));
1392 syn::parse_file(&source).expect("generated child component must be valid Rust syntax");
1393 }
1394
1395 #[test]
1396 fn generated_modules_pass_build_source_checks() {
1397 let project = tempfile::tempdir().unwrap();
1398 let root = Some(project.path().to_path_buf());
1399 fs::write(
1400 project.path().join("Cargo.toml"),
1401 "[package]\nname = \"app\"\nversion = \"0.1.0\"\n",
1402 )
1403 .unwrap();
1404 for (name, children) in [
1405 ("notice", false),
1406 (
1407 "account-settings-preferences-notification-subscription-panel",
1408 true,
1409 ),
1410 ] {
1411 generate_component(GenerateComponentOptions {
1412 name: name.into(),
1413 root: root.clone(),
1414 folder: children,
1415 recipe: children,
1416 children,
1417 asynchronous: true,
1418 markdown: true,
1419 dry_run: None,
1420 force: false,
1421 })
1422 .unwrap();
1423 }
1424 generate_layout(GenerateLayoutOptions {
1425 name: "section".into(),
1426 root,
1427 section: true,
1428 document: false,
1429 replace_root: false,
1430 dry_run: None,
1431 force: false,
1432 })
1433 .unwrap();
1434 let paths = [project.path().join("src")];
1435 fs::write(paths[0].join("lib.rs"), "mod components;\nmod layouts;\n").unwrap();
1436 let checked = crate::fmt::format_paths_with_options(&paths, true, true).unwrap();
1437 assert!(checked.diagnostics.is_empty(), "{:?}", checked.diagnostics);
1438 assert!(checked.changed.is_empty(), "{:?}", checked.changed);
1439 let lint = crate::lint::lint_paths(&paths, Default::default()).unwrap();
1440 assert!(
1441 lint.iter()
1442 .all(|diagnostic| diagnostic.severity == crate::diagnostic::Severity::Info),
1443 "{lint:?}"
1444 );
1445 }
1446
1447 #[test]
1448 fn generated_layouts_use_default_writer() {
1449 for source in [
1450 section_layout_source("MarketingLayout"),
1451 document_layout_source("DocumentLayout"),
1452 ] {
1453 assert!(source.contains("impl<L, C> WebRenderSync<L>"));
1454 assert!(source.contains("C: WebRenderSync<L>"));
1455 assert!(source.contains("DataLoader"));
1456 assert!(!source.contains("WriteBuf"));
1457 syn::parse_file(&source).expect("generated layout must be valid Rust syntax");
1458 }
1459 }
1460}