Skip to main content

proa_cli/site_scaffold/
mod.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Application-first Proa site planning and transactional creation.
5
6mod plan;
7mod templates;
8mod transaction;
9
10use std::{
11    env,
12    path::{Path, PathBuf},
13    process::Command,
14};
15
16use anyhow::{bail, Context, Result};
17use serde::Serialize;
18
19use crate::{
20    capabilities::{CapabilityOverrides, CapabilitySelection, SiteTemplate},
21    scaffold::DryRunFormat,
22};
23
24pub use plan::{PlannedFile, SitePlan};
25
26pub(crate) fn deployment_dockerfile(has_database: bool) -> String {
27    templates::current_deployment_dockerfile(has_database)
28}
29
30/// The `src/db.rs` that `proa new site` and `proa add database sqlite` both write.
31pub(crate) fn database_module() -> &'static str {
32    templates::database_module()
33}
34
35/// The managed-head `src/layouts/root.rs` that `proa new site` writes.
36#[cfg(test)]
37pub(crate) fn root_layout() -> &'static str {
38    templates::root_layout()
39}
40
41#[derive(Debug, Clone)]
42pub struct NewSiteOptions {
43    pub path: PathBuf,
44    pub destination: Option<PathBuf>,
45    pub title: Option<String>,
46    pub template: String,
47    pub overrides: CapabilityOverrides,
48    pub vscode: bool,
49    pub agents_md: bool,
50    pub no_git: bool,
51    pub verify: bool,
52    pub start: bool,
53    pub open: bool,
54    pub offline: bool,
55    pub dry_run: Option<DryRunFormat>,
56    pub json: bool,
57}
58
59#[derive(Debug, Serialize)]
60#[serde(rename_all = "camelCase")]
61struct OperationReport<'a> {
62    operation_id: &'static str,
63    command_version: u16,
64    project_root: &'a Path,
65    planned_filesystem_operations: Vec<FilesystemOperation<'a>>,
66    configuration_changes: CapabilitySelection,
67    warnings: Vec<&'static str>,
68    result: OperationResult<'a>,
69}
70
71#[derive(Debug, Serialize)]
72#[serde(rename_all = "camelCase")]
73struct FilesystemOperation<'a> {
74    operation: &'static str,
75    path: &'a Path,
76    bytes: usize,
77}
78
79#[derive(Debug, Serialize)]
80#[serde(rename_all = "camelCase")]
81struct OperationResult<'a> {
82    status: &'a str,
83    destination: &'a Path,
84    package: &'a str,
85    title: &'a str,
86    selection: CapabilitySelection,
87    files: usize,
88    next: String,
89}
90
91pub(crate) fn scaffold_version(package: &str) -> String {
92    let versions: std::collections::BTreeMap<String, String> = toml::from_str(include_str!(
93        concat!(env!("OUT_DIR"), "/scaffold-versions.toml")
94    ))
95    .expect("bundled scaffold versions are valid TOML");
96    let version = versions
97        .get(package)
98        .expect("scaffold dependency is listed");
99    if package == "proa" {
100        return proa_scaffold_requirement(version);
101    }
102    version.clone()
103}
104
105fn proa_scaffold_requirement(requirement: &str) -> String {
106    // Cargo treats `0.4` and `0.4.0` alike, but `0.0` admits more than `0.0.0`.
107    if let Ok(version) = semver::Version::parse(requirement) {
108        if version.patch == 0
109            && version.pre.is_empty()
110            && version.build.is_empty()
111            && (version.major != 0 || version.minor != 0)
112        {
113            return format!("{}.{}", version.major, version.minor);
114        }
115    }
116    requirement.to_owned()
117}
118
119pub fn new_site(options: NewSiteOptions) -> Result<()> {
120    let template = SiteTemplate::parse_compat(&options.template)?;
121    let selection = CapabilitySelection::resolve(template, options.overrides)?;
122    let root = resolve_destination(&options.path, options.destination.as_deref())?;
123    transaction::ensure_destination_available(&root)?;
124    let package = package_name(&root)?;
125    let title = options.title.unwrap_or_else(|| display_title(&package));
126    let capabilities = selection
127        .capabilities()
128        .into_iter()
129        .map(|capability| capability.id.to_string())
130        .collect();
131    let mut plan = SitePlan::new(root.clone(), capabilities);
132    templates::populate(
133        &mut plan,
134        &package,
135        &title,
136        selection,
137        options.vscode,
138        options.agents_md,
139    )?;
140    plan.validate()?;
141
142    if let Some(format) = options.dry_run {
143        print_plan(&plan, &package, &title, selection, format)?;
144        return Ok(());
145    }
146
147    transaction::commit(&plan)?;
148    if !options.no_git {
149        transaction::initialize_git(&root)?;
150    }
151    print_success(&plan, &package, &title, selection, options.json)?;
152
153    if options.verify {
154        run_child(
155            &root,
156            &["check", "--all", "--root", root.to_string_lossy().as_ref()],
157        )
158        .context(
159            "project was created, but verification failed; repair it and run `proa check --all`",
160        )?;
161    }
162    if options.start || options.open {
163        let root_arg = root.to_string_lossy().into_owned();
164        let mut args = vec!["run", "--root", root_arg.as_str(), "dev"];
165        if options.open {
166            args.push("--open");
167        }
168        if options.offline {
169            args.push("--offline");
170        }
171        run_child(&root, &args)?;
172    }
173    Ok(())
174}
175
176fn resolve_destination(path: &Path, parent: Option<&Path>) -> Result<PathBuf> {
177    if path.as_os_str().is_empty() {
178        bail!("site path cannot be empty");
179    }
180    if path.is_absolute() {
181        if parent.is_some() {
182            bail!("--destination cannot be combined with an absolute site path");
183        }
184        Ok(path.to_path_buf())
185    } else {
186        Ok(parent
187            .map(Path::to_path_buf)
188            .unwrap_or(env::current_dir()?)
189            .join(path))
190    }
191}
192
193fn package_name(root: &Path) -> Result<String> {
194    let raw = root
195        .file_name()
196        .and_then(|value| value.to_str())
197        .context("site path must end in a UTF-8 directory name")?;
198    let mut package = String::with_capacity(raw.len());
199    for character in raw.chars() {
200        if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
201            package.push(character.to_ascii_lowercase());
202        } else if character.is_whitespace() {
203            package.push('-');
204        } else {
205            package.push('_');
206        }
207    }
208    while package.starts_with(|character: char| !character.is_ascii_alphabetic()) {
209        package.remove(0);
210    }
211    if package.is_empty() {
212        bail!("site path does not contain a valid package name");
213    }
214    Ok(package)
215}
216
217fn display_title(package: &str) -> String {
218    package
219        .split(['-', '_'])
220        .filter(|part| !part.is_empty())
221        .map(|part| {
222            let mut characters = part.chars();
223            match characters.next() {
224                Some(first) => format!("{}{}", first.to_ascii_uppercase(), characters.as_str()),
225                None => String::new(),
226            }
227        })
228        .collect::<Vec<_>>()
229        .join(" ")
230}
231
232fn print_plan(
233    plan: &SitePlan,
234    package: &str,
235    title: &str,
236    selection: CapabilitySelection,
237    format: DryRunFormat,
238) -> Result<()> {
239    match format {
240        DryRunFormat::Json => println!(
241            "{}",
242            serde_json::to_string_pretty(&operation_report(
243                plan, package, title, selection, "planned"
244            ))?
245        ),
246        DryRunFormat::Text => {
247            println!("Plan {}", plan.destination.display());
248            for capability in &plan.capabilities {
249                println!("  capability  {capability}");
250            }
251            for file in &plan.files {
252                println!("  create      {} ({} B)", file.path.display(), file.bytes);
253            }
254        }
255    }
256    Ok(())
257}
258
259fn print_success(
260    plan: &SitePlan,
261    package: &str,
262    title: &str,
263    selection: CapabilitySelection,
264    json: bool,
265) -> Result<()> {
266    let root = &plan.destination;
267    if json {
268        println!(
269            "{}",
270            serde_json::to_string_pretty(&operation_report(
271                plan, package, title, selection, "created"
272            ))?
273        );
274        return Ok(());
275    }
276    println!("Created {package}\n");
277    println!("  App         Proa + Axum");
278    println!(
279        "  Database    {}",
280        if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
281            "SQLite + SQLx"
282        } else {
283            "none"
284        }
285    );
286    if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
287        println!("  Data        keyed loading through cx");
288    }
289    println!(
290        "  UI          {}",
291        match selection.ui {
292            crate::capabilities::UiChoice::Proa => "proa-ui · 3 components vendored",
293            crate::capabilities::UiChoice::ProaDocs => "proa-docs",
294            crate::capabilities::UiChoice::None => "none",
295        }
296    );
297    println!(
298        "  Markdown    {}",
299        if selection.markdown {
300            "/index.md · Accept: text/markdown"
301        } else {
302            "disabled"
303        }
304    );
305    println!(
306        "  Client      {}",
307        if selection.template == crate::capabilities::SiteTemplate::Origin {
308            "rsjs flood-the-table island on /"
309        } else {
310            "no client root on /"
311        }
312    );
313    println!("  Health      /healthz · /readyz");
314    println!("\nNext:\n  cd {} && proa run dev --open", root.display());
315    Ok(())
316}
317
318fn operation_report<'a>(
319    plan: &'a SitePlan,
320    package: &'a str,
321    title: &'a str,
322    selection: CapabilitySelection,
323    status: &'a str,
324) -> OperationReport<'a> {
325    OperationReport {
326        operation_id: "site.create",
327        command_version: 1,
328        project_root: &plan.destination,
329        planned_filesystem_operations: plan
330            .files
331            .iter()
332            .map(|file| FilesystemOperation {
333                operation: "create",
334                path: &file.path,
335                bytes: file.bytes,
336            })
337            .collect(),
338        configuration_changes: selection,
339        warnings: Vec::new(),
340        result: OperationResult {
341            status,
342            destination: &plan.destination,
343            package,
344            title,
345            selection,
346            files: plan.files.len(),
347            next: format!("cd {} && proa run dev --open", plan.destination.display()),
348        },
349    }
350}
351
352fn run_child(root: &Path, args: &[&str]) -> Result<()> {
353    let executable = crate::util::current_executable().context("locate the running Proa CLI")?;
354    let status = Command::new(executable)
355        .args(args)
356        .current_dir(root)
357        .status()
358        .context("start Proa child command")?;
359    if !status.success() {
360        bail!("Proa child command failed with {status}");
361    }
362    Ok(())
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use crate::capabilities::{DatabaseChoice, StarterChoice, StylingChoice, UiChoice};
369
370    #[test]
371    fn proa_requirement_shortens_only_equivalent_versions() {
372        for (declared, expected) in [
373            ("0.4.0", "0.4"),
374            ("0.5.0", "0.5"),
375            ("1.0.0", "1.0"),
376            ("0.4.1", "0.4.1"),
377            ("0.0.0", "0.0.0"),
378            ("0.5.0-rc.1", "0.5.0-rc.1"),
379            ("=0.4.0", "=0.4.0"),
380        ] {
381            assert_eq!(proa_scaffold_requirement(declared), expected);
382        }
383    }
384
385    fn options(path: PathBuf) -> NewSiteOptions {
386        NewSiteOptions {
387            path,
388            destination: None,
389            title: None,
390            template: "app".to_string(),
391            overrides: CapabilityOverrides::default(),
392            vscode: true,
393            agents_md: true,
394            no_git: true,
395            verify: false,
396            start: false,
397            open: false,
398            offline: true,
399            dry_run: None,
400            json: false,
401        }
402    }
403
404    #[test]
405    fn default_tree_has_application_first_contract() {
406        let temp = tempfile::tempdir().unwrap();
407        let root = temp.path().join("journal");
408        new_site(options(root.clone())).unwrap();
409        for path in [
410            "src/db.rs",
411            "src/loader.rs",
412            "src/components/database_badge.rs",
413            "src/components/database_card.rs",
414            "src/components/badge/md.rs",
415            "migrations/.gitkeep",
416            "data/.gitkeep",
417            "tests/dataloader.rs",
418            "tests/database.rs",
419            "tests/representations.rs",
420        ] {
421            assert!(root.join(path).exists(), "missing {path}");
422        }
423        // Tailwind owns the generated public output; its input must include
424        // the starter design so the first asset build retains that design.
425        let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
426        assert!(!config.contains("build: proa::config::BuildConfig"));
427        assert!(!config.contains("paths: proa::config::ProjectPaths"));
428        let config = crate::config::load_project_config(&root).unwrap();
429        assert_eq!(config.paths.public.as_deref(), Some(Path::new("public")));
430        let [asset] = config.build.assets() else {
431            panic!("expected one inferred Tailwind asset");
432        };
433        assert_eq!(asset.kind, "tailwind");
434        assert_eq!(asset.input, Path::new("styles/input.css"));
435        assert_eq!(asset.output, Path::new("public/styles.css"));
436        let input = std::fs::read_to_string(root.join("styles/input.css")).unwrap();
437        assert!(input.contains("@import \"./starter.css\" layer(components);"));
438        let starter = std::fs::read_to_string(root.join("styles/starter.css")).unwrap();
439        assert_eq!(
440            starter,
441            std::fs::read_to_string(root.join("public/styles.css")).unwrap()
442        );
443        assert!(!root.join("scripts").exists());
444        assert!(!root.join("src/islands").exists());
445        assert!(!root.join("rust-toolchain.toml").exists());
446        let cargo_toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
447        assert!(cargo_toml.contains("rust-version = \"1.98\""));
448        let home = std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap();
449        let parsed_home = syn::parse_file(&home).unwrap();
450        let mut saw_non_use_item = false;
451        for item in &parsed_home.items {
452            if matches!(item, syn::Item::Use(_)) {
453                assert!(
454                    !saw_non_use_item,
455                    "src/pages/home.rs should keep all `use` imports at the top of the file"
456                );
457            } else {
458                saw_non_use_item = true;
459            }
460        }
461        assert!(home.contains("const ROLE: ComponentRole = ComponentRole::PAGE;"));
462        assert!(home.contains("async fn render_head("));
463        assert!(!home.contains("with_head"));
464        let layout = std::fs::read_to_string(root.join("src/layouts/root.rs")).unwrap();
465        assert!(layout.contains("const ROLE: ComponentRole = ComponentRole::LAYOUT;"));
466        assert!(layout.contains("{cx.head()}"));
467        assert!(home.contains("DataResolver::request_scope"));
468        assert!(home.contains("MdRender<L> for HomePage"));
469        assert!(home.contains("# {HEADLINE}"));
470        assert!(!home.contains("Rust\\."));
471        assert!(!home.contains("multi\\-target"));
472        let routes = std::fs::read_to_string(root.join("src/routes.rs")).unwrap();
473        assert!(routes.contains("PublicAssets::configured()"));
474        assert!(routes.contains(".with_head(proa::HeadConfig::default())"));
475    }
476
477    #[test]
478    fn every_preset_has_canonical_macros_and_clean_component_hashes() {
479        let temp = tempfile::tempdir().unwrap();
480        for template in ["minimal", "app", "marketing", "docs", "origin"] {
481            let root = temp.path().join(template);
482            let mut value = options(root.clone());
483            value.template = template.to_string();
484            new_site(value).unwrap();
485            assert!(!root.join(".cargo/config.toml").exists(), "{template}");
486            assert!(!root.join("rust-toolchain.toml").exists(), "{template}");
487            let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
488            assert!(!config.contains("template:"), "{template}");
489            let formatting =
490                crate::fmt::format_paths_with_options(std::slice::from_ref(&root), true, true)
491                    .unwrap();
492            assert!(
493                formatting.changed.is_empty() && formatting.diagnostics.is_empty(),
494                "{template}: {:?}",
495                formatting.diagnostics
496            );
497            let diagnostics =
498                crate::lint::lint_paths(&[root.join("src")], crate::lint::LintOptions::default())
499                    .unwrap();
500            assert!(
501                diagnostics
502                    .iter()
503                    .all(|diagnostic| diagnostic.severity.rank()
504                        < crate::diagnostic::Severity::Warning.rank()),
505                "{template}: {diagnostics:?}"
506            );
507            let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
508            assert!(report.errors.is_empty(), "{template}: {:?}", report.errors);
509            let routes = crate::scaffold::site_routes(Some(root)).unwrap();
510            let markdown = routes.iter().find(|route| route.path == "/index.md");
511            match template {
512                "minimal" => assert!(markdown.is_none()),
513                "origin" => assert_eq!(markdown.unwrap().file, Path::new("src/lib.rs")),
514                _ => assert_eq!(markdown.unwrap().file, Path::new("src/pages/home.rs")),
515            }
516        }
517    }
518
519    #[test]
520    fn any_title_scaffolds_rust_that_parses_and_keeps_the_title() {
521        // Quotes, backslashes, braces, raw-string terminators, a newline,
522        // non-ASCII, and the home page template's own placeholder names.
523        let title =
524            "Sam's \"Quote\" \\ {x}} \"# \"## # caf\u{e9} \u{65e5}\u{672c} \u{1f680}\nline2 \
525            __IMPORTS__ __CONSTANTS__ __RENDER_IMPL__ __MARKDOWN_IMPL__ __ARGS__ \
526            __HTML_RESPONSE__ __RESPONSE__ __MD_HANDLER__ __HEAD__ __BODY__";
527        let temp = tempfile::tempdir().unwrap();
528        for (template, starter) in [
529            ("app", None),
530            ("app", Some(StarterChoice::Blank)),
531            ("marketing", None),
532            ("docs", None),
533            ("minimal", None),
534            ("origin", None),
535        ] {
536            let root = temp
537                .path()
538                .join(format!("{template}-{}", starter.is_some()));
539            let mut value = options(root.clone());
540            value.template = template.to_string();
541            value.overrides.starter = starter;
542            value.title = Some(title.to_string());
543            new_site(value).unwrap();
544            for entry in walkdir::WalkDir::new(&root) {
545                let path = entry.unwrap().into_path();
546                if path.extension().is_some_and(|extension| extension == "rs") {
547                    let source = std::fs::read_to_string(&path).unwrap();
548                    if let Err(error) = syn::parse_file(&source) {
549                        panic!("{template}: {} does not parse: {error}", path.display());
550                    }
551                }
552            }
553            if template == "origin" {
554                continue;
555            }
556            let home =
557                syn::parse_file(&std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap())
558                    .unwrap();
559            let constant = home
560                .items
561                .iter()
562                .find_map(|item| match item {
563                    syn::Item::Const(constant) if constant.ident == "TITLE" => Some(constant),
564                    _ => None,
565                })
566                .expect("home page declares TITLE");
567            let syn::Expr::Lit(syn::ExprLit {
568                lit: syn::Lit::Str(literal),
569                ..
570            }) = constant.expr.as_ref()
571            else {
572                panic!("TITLE is a string literal");
573            };
574            assert_eq!(literal.value(), title, "{template}");
575        }
576    }
577
578    #[test]
579    fn agents_md_states_the_head_role_contract() {
580        let temp = tempfile::tempdir().unwrap();
581        let root = temp.path().join("agents");
582        new_site(options(root.clone())).unwrap();
583        let agents = std::fs::read_to_string(root.join("AGENTS.md")).unwrap();
584        assert!(agents.contains("const ROLE: ComponentRole = ComponentRole::PAGE;"));
585        assert!(agents.contains("ComponentRole::LAYOUT"));
586        assert!(agents.contains("render_head"));
587    }
588
589    #[test]
590    fn customized_pages_preserve_capability_checks() {
591        let temp = tempfile::tempdir().unwrap();
592        let root = temp.path().join("customized");
593        new_site(options(root.clone())).unwrap();
594        let home_path = root.join("src/pages/home.rs");
595        let source = std::fs::read_to_string(&home_path)
596            .unwrap()
597            .replace("HomePage", "IssuePage")
598            .replace("/index.md", "/issues.md");
599        let issue_path = root.join("src/pages/issues.rs");
600        std::fs::write(&issue_path, &source).unwrap();
601        std::fs::write(
602            &home_path,
603            "pub async fn handler() -> &'static str { \"Welcome\" }\n",
604        )
605        .unwrap();
606        let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
607        assert!(report.errors.is_empty(), "{:?}", report.errors);
608
609        // Removing a capability still fails after moving the real page.
610        std::fs::write(
611            &issue_path,
612            source
613                .replace("DataResolver::request_scope", "DataResolver::new")
614                .replace("explicit_markdown_async_with_loader(", "other_response("),
615        )
616        .unwrap();
617        let report = crate::scaffold::site_check(Some(root)).unwrap();
618        assert!(report
619            .errors
620            .iter()
621            .any(|e| e.contains("request-scoped DataResolver")));
622        assert!(report
623            .errors
624            .iter()
625            .any(|e| e.contains("explicit_markdown(")));
626    }
627
628    #[test]
629    fn capability_deltas_remove_owned_outputs() {
630        let temp = tempfile::tempdir().unwrap();
631        let root = temp.path().join("bare");
632        let mut value = options(root.clone());
633        value.overrides.database = Some(DatabaseChoice::None);
634        value.overrides.ui = Some(UiChoice::None);
635        value.overrides.styling = Some(StylingChoice::Css);
636        value.vscode = false;
637        new_site(value).unwrap();
638        let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
639        assert!(config.contains("assets: Some(vec![])"));
640        assert!(!root.join("src/db.rs").exists());
641        assert!(!root.join("src/components/badge").exists());
642        assert!(!root.join("styles").exists());
643        assert!(!root.join(".vscode").exists());
644    }
645
646    #[test]
647    fn dry_run_and_nonempty_refusal_do_not_write() {
648        let temp = tempfile::tempdir().unwrap();
649        let root = temp.path().join("dry");
650        let mut value = options(root.clone());
651        value.dry_run = Some(DryRunFormat::Json);
652        new_site(value).unwrap();
653        assert!(!root.exists());
654
655        std::fs::create_dir(&root).unwrap();
656        std::fs::write(root.join("keep"), "mine").unwrap();
657        let error = new_site(options(root.clone())).unwrap_err();
658        assert!(error.to_string().contains("not empty"));
659        assert_eq!(std::fs::read_to_string(root.join("keep")).unwrap(), "mine");
660    }
661}