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