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, site_manages_head(&root))
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 rust_string_literal(value: &str) -> String {
667 proc_macro2::Literal::string(value).to_string()
668}
669
670pub(crate) fn site_manages_head(root: &Path) -> bool {
678 let Ok(source) = fs::read_to_string(root.join("src/layouts/root.rs")) else {
679 return true;
680 };
681 let Ok(file) = syn::parse_file(&source) else {
682 return true;
683 };
684 let mut title_field = false;
685 for item in &file.items {
686 match item {
687 syn::Item::Struct(item) if item.ident == "RootDocument" => {
688 title_field = item
689 .fields
690 .iter()
691 .any(|field| field.ident.as_ref().is_some_and(|ident| ident == "title"));
692 }
693 syn::Item::Impl(item) => {
694 let layout = item.items.iter().any(|item| {
695 matches!(item, syn::ImplItem::Const(constant)
696 if constant.ident == "ROLE"
697 && matches!(&constant.expr, syn::Expr::Path(path)
698 if path.path.segments.last().is_some_and(|segment| segment.ident == "LAYOUT")))
699 });
700 if layout {
701 return true;
702 }
703 }
704 _ => {}
705 }
706 }
707 renders_head_outlet(quote::ToTokens::into_token_stream(file)) || !title_field
708}
709
710fn renders_head_outlet(tokens: proc_macro2::TokenStream) -> bool {
713 use proc_macro2::{Delimiter, TokenTree};
714 let tokens: Vec<TokenTree> = tokens.into_iter().collect();
715 tokens.windows(3).any(|window| {
716 matches!(window, [TokenTree::Punct(dot), TokenTree::Ident(name), TokenTree::Group(arguments)]
717 if dot.as_char() == '.'
718 && name == "head"
719 && arguments.delimiter() == Delimiter::Parenthesis
720 && arguments.stream().is_empty())
721 }) || tokens.iter().any(
722 |token| matches!(token, TokenTree::Group(group) if renders_head_outlet(group.stream())),
723 )
724}
725
726pub(crate) fn format_generated_rust(path: &Path, source: &str) -> Result<String> {
727 let formatted = crate::fmt::format_file(path, source)?;
728 if !formatted.diagnostics.is_empty() {
729 bail!(
730 "Proa formatting failed for generated {}: {:?}",
731 path.display(),
732 formatted.diagnostics
733 );
734 }
735 let verification = crate::fmt::verify_render_preserving(path, source, &formatted.output);
736 if !verification.is_empty() {
737 bail!(
738 "Proa formatting changed render semantics for generated {}: {:?}",
739 path.display(),
740 verification
741 );
742 }
743 Ok(formatted.output)
744}
745
746fn finish_plan(plan: ScaffoldPlan, dry_run: Option<DryRunFormat>, force: bool) -> Result<()> {
747 if let Some(format) = dry_run {
748 match format {
749 DryRunFormat::Text => print_plan(&plan),
750 DryRunFormat::Json => println!("{}", serde_json::to_string_pretty(&plan)?),
751 }
752 return Ok(());
753 }
754
755 preflight(&plan, force)?;
756 apply_plan(&plan, force)?;
757 print_plan(&plan);
758 Ok(())
759}
760
761fn print_plan(plan: &ScaffoldPlan) {
762 for operation in &plan.operations {
763 match operation {
764 PlanOperation::WriteFile { path, .. } => println!("create {}", path.display()),
765 PlanOperation::AppendLine { path, .. } => println!("update {}", path.display()),
766 }
767 }
768 for warning in &plan.warnings {
769 eprintln!("warning: {warning}");
770 }
771 if !plan.follow_up.is_empty() {
772 println!("\nNext steps:");
773 for step in &plan.follow_up {
774 println!("- {step}");
775 }
776 }
777}
778
779fn preflight(plan: &ScaffoldPlan, force: bool) -> Result<()> {
780 if force {
781 return Ok(());
782 }
783
784 for operation in &plan.operations {
785 if let PlanOperation::WriteFile { path, .. } = operation {
786 if path.exists() {
787 bail!(
788 "{} already exists (use --force to overwrite)",
789 path.display()
790 );
791 }
792 }
793 }
794 Ok(())
795}
796
797fn apply_plan(plan: &ScaffoldPlan, force: bool) -> Result<()> {
798 let mut journal: Vec<(PathBuf, Option<String>)> = Vec::new();
801 let outcome = apply_operations(plan, force, &mut journal);
802 if outcome.is_err() {
803 rollback(&journal);
804 }
805 outcome
806}
807
808fn apply_operations(
809 plan: &ScaffoldPlan,
810 force: bool,
811 journal: &mut Vec<(PathBuf, Option<String>)>,
812) -> Result<()> {
813 for operation in &plan.operations {
814 match operation {
815 PlanOperation::WriteFile { path, content, .. } => {
816 if path.exists() && !force {
817 bail!(
818 "{} already exists (use --force to overwrite)",
819 path.display()
820 );
821 }
822 if let Some(parent) = path.parent() {
823 fs::create_dir_all(parent)
824 .with_context(|| format!("create {}", parent.display()))?;
825 }
826 journal.push((path.clone(), fs::read_to_string(path).ok()));
827 fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
828 }
829 PlanOperation::AppendLine { path, line, .. } => {
830 if let Some(parent) = path.parent() {
831 fs::create_dir_all(parent)
832 .with_context(|| format!("create {}", parent.display()))?;
833 }
834 let mut current = fs::read_to_string(path).unwrap_or_default();
835 if !current
836 .lines()
837 .any(|existing| existing.trim() == line.trim())
838 {
839 journal.push((path.clone(), fs::read_to_string(path).ok()));
840 if !current.is_empty() && !current.ends_with('\n') {
841 current.push('\n');
842 }
843 current.push_str(line);
844 current.push('\n');
845 fs::write(path, current)
846 .with_context(|| format!("update {}", path.display()))?;
847 }
848 }
849 }
850 }
851 Ok(())
852}
853
854fn rollback(journal: &[(PathBuf, Option<String>)]) {
855 for (path, prior) in journal.iter().rev() {
856 let restored = match prior {
857 Some(content) => fs::write(path, content),
858 None => fs::remove_file(path),
859 };
860 if restored.is_err() {
861 eprintln!(
862 "warning: could not roll back {} after a failed scaffold",
863 path.display()
864 );
865 }
866 }
867}
868
869struct ModuleTarget {
870 leaf: String,
871 file_path: PathBuf,
872 mod_updates: Vec<(PathBuf, String)>,
873}
874
875impl ModuleTarget {
876 fn new(root: &Path, bucket: &str, raw_name: &str) -> Result<Self> {
877 let parts: Vec<String> = raw_name
878 .split('/')
879 .filter(|part| !part.is_empty())
880 .map(snake_case)
881 .collect();
882 if parts.is_empty() {
883 bail!("name cannot be empty");
884 }
885 let leaf = parts.last().cloned().unwrap();
886 let base = root.join("src").join(bucket);
887 let mut dir = base.clone();
888 let mut mod_updates = Vec::new();
889
890 for (index, part) in parts.iter().enumerate() {
891 let mod_path = if index == 0 {
892 base.join("mod.rs")
893 } else {
894 base.join(parts[..index].join("/")).join("mod.rs")
895 };
896 mod_updates.push((mod_path, format!("pub mod {part};")));
897 if index + 1 < parts.len() {
898 dir.push(part);
899 }
900 }
901
902 Ok(Self {
903 leaf,
904 file_path: dir.join(format!("{}.rs", parts.last().unwrap())),
905 mod_updates,
906 })
907 }
908
909 fn plan_mod_updates(&self, plan: &mut ScaffoldPlan) {
910 for (path, line) in &self.mod_updates {
911 plan.append_line(path.clone(), line.clone(), "add module export");
912 }
913 }
914}
915
916pub fn resolve_root(root: Option<PathBuf>) -> Result<PathBuf> {
917 if let Some(root) = root {
918 return Ok(root);
919 }
920
921 let mut current = env::current_dir()?;
922 loop {
923 if current.join("Cargo.toml").exists() && current.join("src").exists() {
924 return Ok(current);
925 }
926 if !current.pop() {
927 bail!("could not find a Proa project root (pass --root)");
928 }
929 }
930}
931
932fn rust_files(root: &Path) -> Result<Vec<PathBuf>> {
933 let mut files = Vec::new();
934 collect_rust_files(root, &mut files)?;
935 Ok(files)
936}
937
938fn collect_rust_files(root: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
939 for entry in fs::read_dir(root).with_context(|| format!("read {}", root.display()))? {
940 let entry = entry?;
941 let path = entry.path();
942 if path.is_dir() {
943 collect_rust_files(&path, files)?;
944 } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
945 files.push(path);
946 }
947 }
948 Ok(())
949}
950
951fn route_path_for_page(rel: &Path) -> String {
952 let mut parts: Vec<String> = rel
953 .with_extension("")
954 .components()
955 .filter_map(|component| component.as_os_str().to_str().map(str::to_string))
956 .collect();
957 if parts.last().is_some_and(|part| part == "index") {
958 parts.pop();
959 }
960 if parts.len() == 1 && parts[0] == "home" {
961 return "/".to_string();
962 }
963 if parts.is_empty() {
964 "/".to_string()
965 } else {
966 format!("/{}", parts.join("/").replace('_', "-"))
967 }
968}
969
970fn display_rel(root: &Path, path: &Path) -> String {
971 display_rel_path(root, path).display().to_string()
972}
973
974fn display_rel_path(root: &Path, path: &Path) -> PathBuf {
975 path.strip_prefix(root).unwrap_or(path).to_path_buf()
976}
977
978fn snake_case(value: &str) -> String {
979 normalize_case(value, '_')
980}
981
982fn kebab_case(value: &str) -> String {
983 normalize_case(value, '-')
984}
985
986fn normalize_case(value: &str, separator: char) -> String {
987 let mut out = String::new();
988 let mut last_was_sep = false;
989 for ch in value.chars() {
990 if ch.is_ascii_alphanumeric() {
991 out.push(ch.to_ascii_lowercase());
992 last_was_sep = false;
993 } else if !last_was_sep && !out.is_empty() {
994 out.push(separator);
995 last_was_sep = true;
996 }
997 }
998 while out.ends_with(separator) {
999 out.pop();
1000 }
1001 if out.is_empty() {
1002 out.push_str("generated");
1003 }
1004 if out.starts_with(|ch: char| ch.is_ascii_digit()) {
1005 out.insert(0, separator);
1006 }
1007 out
1008}
1009
1010fn pascal_case(value: &str) -> String {
1011 let mut out = String::new();
1012 for part in value
1013 .split(|ch: char| !ch.is_ascii_alphanumeric())
1014 .filter(|part| !part.is_empty())
1015 {
1016 let mut chars = part.chars();
1017 if let Some(first) = chars.next() {
1018 out.push(first.to_ascii_uppercase());
1019 for ch in chars {
1020 out.push(ch.to_ascii_lowercase());
1021 }
1022 }
1023 }
1024 if out.is_empty() {
1025 out.push_str("Generated");
1026 }
1027 if out.starts_with(|ch: char| ch.is_ascii_digit()) {
1028 out.insert_str(0, "Generated");
1029 }
1030 out
1031}
1032
1033fn fill(mut template: String, replacements: &[(&str, &str)]) -> String {
1034 for (needle, value) in replacements {
1035 template = template.replace(needle, value);
1036 }
1037 template
1038}
1039
1040fn nav_data() -> String {
1041 "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()
1042}
1043
1044fn component_source(
1047 struct_name: &str,
1048 data_attr: &str,
1049 children: bool,
1050 asynchronous: bool,
1051 markdown: bool,
1052 recipe: bool,
1053) -> String {
1054 let base = if recipe {
1055 "use super::recipe::BASE_CLASS;\n"
1056 } else {
1057 "const BASE_CLASS: &str = \"rounded-lg border p-4\";\n"
1058 };
1059 let template = match (children, asynchronous) {
1060 (true, false) => {
1061 r#"use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
1062use proa::html_sync;
1063
1064__BASE__
1065pub struct __STRUCT__<C = ()> {
1066 pub class: Option<&'static str>,
1067 pub children: C,
1068}
1069
1070impl<C> __STRUCT__<C> {
1071 pub const fn new(children: C) -> Self {
1072 Self { class: None, children }
1073 }
1074
1075 pub const fn class(mut self, class: &'static str) -> Self {
1076 self.class = Some(class);
1077 self
1078 }
1079}
1080
1081impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1082where
1083 L: DataLoader,
1084 C: WebRenderSync<L>,
1085{
1086 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1087 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1088 html_sync! {
1089 <div __DATA__ class={classes}>{self.children}</div>
1090 }
1091 .render(cx)
1092 }
1093}
1094"#
1095 }
1096 (false, false) => {
1097 r#"use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};
1098use proa::html_sync;
1099
1100__BASE__
1101#[derive(Debug, Clone, Copy, Default)]
1102pub struct __STRUCT__ {
1103 pub class: Option<&'static str>,
1104}
1105
1106impl __STRUCT__ {
1107 pub const fn new() -> Self {
1108 Self { class: None }
1109 }
1110
1111 pub const fn class(mut self, class: &'static str) -> Self {
1112 self.class = Some(class);
1113 self
1114 }
1115}
1116
1117impl<L: DataLoader> WebRenderSync<L> for __STRUCT__ {
1118 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1119 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1120 html_sync! {
1121 <div __DATA__ class={classes}>"__STRUCT__"</div>
1122 }
1123 .render(cx)
1124 }
1125}
1126"#
1127 }
1128 (true, true) => {
1129 r#"use std::future::Future;
1130
1131use proa::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
1132use proa::html;
1133
1134__BASE__
1135pub struct __STRUCT__<C = ()> {
1136 pub class: Option<&'static str>,
1137 pub children: C,
1138}
1139
1140impl<C> __STRUCT__<C> {
1141 pub const fn new(children: C) -> Self {
1142 Self { class: None, children }
1143 }
1144
1145 pub const fn class(mut self, class: &'static str) -> Self {
1146 self.class = Some(class);
1147 self
1148 }
1149}
1150
1151impl<L, C> WebRender<L> for __STRUCT__<C>
1152where
1153 L: DataLoader,
1154 C: WebRender<L>,
1155{
1156 fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
1157 RenderOutcome::pending(async move {
1158 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1159 html! {
1160 <div __DATA__ class={classes}>{self.children}</div>
1161 }
1162 .render(cx)
1163 .resolve()
1164 .await
1165 })
1166 }
1167}
1168"#
1169 }
1170 (false, true) => {
1171 r#"use std::future::Future;
1172
1173use proa::{ClassList, DataLoader, RenderOutcome, WebContext, WebRender, WriteError};
1174use proa::html;
1175
1176__BASE__
1177#[derive(Debug, Clone, Copy, Default)]
1178pub struct __STRUCT__ {
1179 pub class: Option<&'static str>,
1180}
1181
1182impl __STRUCT__ {
1183 pub const fn new() -> Self {
1184 Self { class: None }
1185 }
1186
1187 pub const fn class(mut self, class: &'static str) -> Self {
1188 self.class = Some(class);
1189 self
1190 }
1191}
1192
1193impl<L: DataLoader> WebRender<L> for __STRUCT__ {
1194 fn render(self, cx: &mut WebContext<L>) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
1195 RenderOutcome::pending(async move {
1196 let classes = ClassList::<2>::new().add(BASE_CLASS).add_opt(self.class);
1197 html! {
1198 <div __DATA__ class={classes}>
1199 {proa::await_component(async { proa::text::text("__STRUCT__") })}
1200 </div>
1201 }
1202 .render(cx)
1203 .resolve()
1204 .await
1205 })
1206 }
1207}
1208"#
1209 }
1210 };
1211
1212 let markdown_source = if markdown {
1213 if children {
1214 r####"
1215use proa::{MdRenderSync, WriteBuf};
1216use proa::md_sync;
1217
1218impl<L: proa::DataLoader, B, C> MdRenderSync<L, B> for __STRUCT__<C>
1219where
1220 B: WriteBuf,
1221 C: MdRenderSync<L, B>,
1222{
1223 fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
1224 md_sync! { r###"
1225 ### __STRUCT__
1226
1227 {self.children}
1228 "###
1229 }
1230 .render_md(cx)
1231 }
1232}
1233"####
1234 } else {
1235 r####"
1236use proa::{MdRenderSync, WriteBuf};
1237use proa::md_sync;
1238
1239impl<L: proa::DataLoader, B: WriteBuf> MdRenderSync<L, B> for __STRUCT__ {
1240 fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
1241 md_sync! { r###"__STRUCT__"### }.render_md(cx)
1242 }
1243}
1244"####
1245 }
1246 } else {
1247 ""
1248 };
1249
1250 fill(
1251 format!("{template}{markdown_source}"),
1252 &[
1253 ("__BASE__", base),
1254 ("__STRUCT__", struct_name),
1255 ("__DATA__", data_attr),
1256 ],
1257 )
1258}
1259
1260fn component_recipe_source(struct_name: &str) -> String {
1261 fill(
1262 r#"pub const BASE_CLASS: &str = "rounded-lg border p-4";
1263
1264pub struct __STRUCT__Recipe {
1265 pub class: &'static str,
1266}
1267
1268impl Default for __STRUCT__Recipe {
1269 fn default() -> Self {
1270 Self { class: BASE_CLASS }
1271 }
1272}
1273"#
1274 .to_string(),
1275 &[("__STRUCT__", struct_name)],
1276 )
1277}
1278
1279fn section_layout_source(struct_name: &str) -> String {
1280 fill(
1281 r#"use proa::{DataLoader, WebContext, WebRenderSync, WriteError};
1282use proa::html_sync;
1283
1284pub struct __STRUCT__<C> {
1285 pub content: C,
1286}
1287
1288impl<C> __STRUCT__<C> {
1289 pub const fn new(content: C) -> Self {
1290 Self { content }
1291 }
1292}
1293
1294impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1295where
1296 L: DataLoader,
1297 C: WebRenderSync<L>,
1298{
1299 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1300 html_sync! {
1301 <section class="mx-auto max-w-5xl px-6 py-12">{self.content}</section>
1302 }
1303 .render(cx)
1304 }
1305}
1306"#
1307 .to_string(),
1308 &[("__STRUCT__", struct_name)],
1309 )
1310}
1311
1312fn document_layout_source(struct_name: &str, managed_head: bool) -> String {
1316 let template = if managed_head {
1317 r#"// proa:document-root
1318use proa::{ComponentRole, DataLoader, WebContext, WebRenderSync, WriteError};
1319use proa::html_sync;
1320
1321pub struct __STRUCT__<C> {
1322 pub content: C,
1323}
1324
1325impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1326where
1327 L: DataLoader,
1328 C: WebRenderSync<L>,
1329{
1330 const ROLE: ComponentRole = ComponentRole::LAYOUT;
1331
1332 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1333 html_sync! {
1334 <!DOCTYPE html>
1335 <html lang="en">
1336 <head>
1337 <meta charset="utf-8" />
1338 <meta name="viewport" content="width=device-width, initial-scale=1" />
1339 {cx.head()}
1340 </head>
1341 <body>{self.content}</body>
1342 </html>
1343 }
1344 .render(cx)
1345 }
1346}
1347"#
1348 } else {
1349 r#"// proa:document-root
1350use proa::{raw_text_ok, DataLoader, WebContext, WebRenderSync, WriteError};
1351use proa::html_sync;
1352
1353pub struct __STRUCT__<C> {
1354 pub title: &'static str,
1355 pub description: &'static str,
1356 pub content: C,
1357}
1358
1359impl<L, C> WebRenderSync<L> for __STRUCT__<C>
1360where
1361 L: DataLoader,
1362 C: WebRenderSync<L>,
1363{
1364 fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {
1365 html_sync! {
1366 <!DOCTYPE html>
1367 <html lang="en">
1368 <head>
1369 <meta charset="utf-8" />
1370 <meta name="viewport" content="width=device-width, initial-scale=1" />
1371 <title>{raw_text_ok(self.title)}</title>
1372 <meta name="description" content={self.description} />
1373 </head>
1374 <body>{self.content}</body>
1375 </html>
1376 }
1377 .render(cx)
1378 }
1379}
1380"#
1381 };
1382 fill(template.to_string(), &[("__STRUCT__", struct_name)])
1383}
1384
1385fn data_source(name: &str) -> String {
1386 if name == "routes" {
1387 "pub const ROUTES: &[&str] = &[\"/\"];\n".to_string()
1388 } else if name == "nav" {
1389 nav_data()
1390 } else {
1391 format!(
1392 "pub struct {}Item {{\n pub label: &'static str,\n}}\n\npub const ITEMS: &[{}Item] = &[];\n",
1393 pascal_case(name),
1394 pascal_case(name)
1395 )
1396 }
1397}
1398
1399#[cfg(test)]
1400mod tests {
1401 use super::*;
1402
1403 #[test]
1404 fn apply_plan_rolls_back_files_on_mid_plan_failure() {
1405 let temp = tempfile::tempdir().unwrap();
1406 let root = temp.path().to_path_buf();
1407 let mut plan = ScaffoldPlan::new(root.clone());
1408 plan.write_file(root.join("ok.txt"), "hello".to_string());
1409 let blocked = root.join("blocked");
1411 fs::create_dir_all(&blocked).unwrap();
1412 plan.write_file(blocked.clone(), "nope".to_string());
1413
1414 apply_plan(&plan, true).unwrap_err();
1415 assert!(
1416 !root.join("ok.txt").exists(),
1417 "files from the failed plan should be rolled back"
1418 );
1419 }
1420
1421 #[test]
1422 fn apply_plan_rollback_restores_overwritten_files() {
1423 let temp = tempfile::tempdir().unwrap();
1424 let root = temp.path().to_path_buf();
1425 fs::write(root.join("keep.txt"), "original").unwrap();
1426 let mut plan = ScaffoldPlan::new(root.clone());
1427 plan.write_file(root.join("keep.txt"), "replaced".to_string());
1428 let blocked = root.join("blocked");
1429 fs::create_dir_all(&blocked).unwrap();
1430 plan.write_file(blocked.clone(), "nope".to_string());
1431
1432 apply_plan(&plan, true).unwrap_err();
1433 assert_eq!(
1434 fs::read_to_string(root.join("keep.txt")).unwrap(),
1435 "original",
1436 "overwritten files should be restored on rollback"
1437 );
1438 }
1439
1440 #[test]
1441 fn generate_component_updates_mod_file() {
1442 let temp = tempfile::tempdir().unwrap();
1443 fs::create_dir_all(temp.path().join("src/components")).unwrap();
1444 fs::write(temp.path().join("Cargo.toml"), "[package]\nname=\"demo\"\n").unwrap();
1445 fs::write(temp.path().join("src/components/mod.rs"), "").unwrap();
1446
1447 generate_component(GenerateComponentOptions {
1448 name: "marketing-card".to_string(),
1449 root: Some(temp.path().to_path_buf()),
1450 folder: false,
1451 recipe: false,
1452 children: false,
1453 asynchronous: false,
1454 markdown: false,
1455 dry_run: None,
1456 force: false,
1457 })
1458 .unwrap();
1459
1460 let module = fs::read_to_string(temp.path().join("src/components/mod.rs")).unwrap();
1461 assert!(module.contains("pub mod marketing_card;"));
1462 assert!(temp
1463 .path()
1464 .join("src/components/marketing_card.rs")
1465 .exists());
1466
1467 let source =
1468 fs::read_to_string(temp.path().join("src/components/marketing_card.rs")).unwrap();
1469 assert!(source
1470 .contains("use proa::{ClassList, DataLoader, WebContext, WebRenderSync, WriteError};"));
1471 assert!(source.contains("impl<L: DataLoader> WebRenderSync<L> for MarketingCard"));
1472 assert!(source.contains("fn render(self, cx: &mut WebContext<L>)"));
1473 syn::parse_file(&source).expect("generated component must be valid Rust syntax");
1474 }
1475
1476 #[test]
1477 fn generated_component_with_children_uses_default_writer() {
1478 let source = component_source(
1479 "MarketingCard",
1480 "data-marketing-card",
1481 true,
1482 false,
1483 false,
1484 false,
1485 );
1486
1487 assert!(source.contains("impl<L, C> WebRenderSync<L> for MarketingCard<C>"));
1488 assert!(source.contains("C: WebRenderSync<L>"));
1489 syn::parse_file(&source).expect("generated child component must be valid Rust syntax");
1490 }
1491
1492 #[test]
1493 fn generated_modules_pass_build_source_checks() {
1494 let project = tempfile::tempdir().unwrap();
1495 let root = Some(project.path().to_path_buf());
1496 fs::write(
1497 project.path().join("Cargo.toml"),
1498 "[package]\nname = \"app\"\nversion = \"0.1.0\"\n",
1499 )
1500 .unwrap();
1501 for (name, children) in [
1502 ("notice", false),
1503 (
1504 "account-settings-preferences-notification-subscription-panel",
1505 true,
1506 ),
1507 ] {
1508 generate_component(GenerateComponentOptions {
1509 name: name.into(),
1510 root: root.clone(),
1511 folder: children,
1512 recipe: children,
1513 children,
1514 asynchronous: true,
1515 markdown: true,
1516 dry_run: None,
1517 force: false,
1518 })
1519 .unwrap();
1520 }
1521 generate_layout(GenerateLayoutOptions {
1522 name: "section".into(),
1523 root,
1524 section: true,
1525 document: false,
1526 replace_root: false,
1527 dry_run: None,
1528 force: false,
1529 })
1530 .unwrap();
1531 let paths = [project.path().join("src")];
1532 fs::write(paths[0].join("lib.rs"), "mod components;\nmod layouts;\n").unwrap();
1533 let checked = crate::fmt::format_paths_with_options(&paths, true, true).unwrap();
1534 assert!(checked.diagnostics.is_empty(), "{:?}", checked.diagnostics);
1535 assert!(checked.changed.is_empty(), "{:?}", checked.changed);
1536 let lint = crate::lint::lint_paths(&paths, Default::default()).unwrap();
1537 assert!(
1538 lint.iter()
1539 .all(|diagnostic| diagnostic.severity == crate::diagnostic::Severity::Info),
1540 "{lint:?}"
1541 );
1542 }
1543
1544 #[test]
1545 fn generated_layouts_use_default_writer() {
1546 for source in [
1547 section_layout_source("MarketingLayout"),
1548 document_layout_source("DocumentLayout", true),
1549 document_layout_source("DocumentLayout", false),
1550 ] {
1551 assert!(source.contains("impl<L, C> WebRenderSync<L>"));
1552 assert!(source.contains("C: WebRenderSync<L>"));
1553 assert!(source.contains("DataLoader"));
1554 assert!(!source.contains("WriteBuf"));
1555 syn::parse_file(&source).expect("generated layout must be valid Rust syntax");
1556 }
1557 }
1558
1559 #[test]
1560 fn document_layouts_match_the_site_head_mode() {
1561 let managed = document_layout_source("DocumentLayout", true);
1562 assert!(managed.contains("const ROLE: ComponentRole = ComponentRole::LAYOUT;"));
1563 assert!(managed.contains("{cx.head()}"));
1564 assert!(!managed.contains("<title>"), "{managed}");
1565 assert!(!managed.contains("pub title"), "{managed}");
1566
1567 let manual = document_layout_source("DocumentLayout", false);
1568 assert!(manual.contains("<title>{raw_text_ok(self.title)}</title>"));
1569 assert!(!manual.contains("ComponentRole"), "{manual}");
1570 assert!(!manual.contains("cx.head()"), "{manual}");
1571 }
1572
1573 #[test]
1574 fn head_mode_follows_the_root_layout_not_comments() {
1575 let site = tempfile::tempdir().unwrap();
1576 let layout = site.path().join("src/layouts/root.rs");
1577 fs::create_dir_all(layout.parent().unwrap()).unwrap();
1578 let manual = "pub struct RootDocument<C> {\n pub title: &'static str,\n pub content: C,\n}\n\nfn render() {\n html! { <head><title>{raw_text_ok(title)}</title></head> }\n}\n";
1579 for (source, managed) in [
1580 (crate::site_scaffold::root_layout().to_string(), true),
1581 (manual.to_string(), false),
1582 (
1584 format!("// const ROLE: ComponentRole = ComponentRole::LAYOUT;\n// {{cx.head()}}\n{manual}"),
1585 false,
1586 ),
1587 (manual.replace("<title>{raw_text_ok(title)}</title>", "{cx.head()}"), true),
1589 (
1590 format!("{manual}\nimpl<C> WebRender<L> for RootDocument<C> {{\n const ROLE: ComponentRole = ComponentRole::LAYOUT;\n}}\n"),
1591 true,
1592 ),
1593 ] {
1594 fs::write(&layout, &source).unwrap();
1595 assert_eq!(site_manages_head(site.path()), managed, "{source}");
1596 }
1597 fs::remove_file(&layout).unwrap();
1598 assert!(site_manages_head(site.path()), "no root layout");
1599 }
1600}