proa-cli 0.2.2

CLI for scaffolding, inspecting, formatting, and validating Proa web projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Application-first Proa site planning and transactional creation.

mod plan;
mod templates;
mod transaction;

use std::{
    env,
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::{bail, Context, Result};
use serde::Serialize;

use crate::{
    capabilities::{CapabilityOverrides, CapabilitySelection, SiteTemplate},
    scaffold::DryRunFormat,
};

pub use plan::{PlannedFile, SitePlan};

pub(crate) fn deployment_dockerfile(has_database: bool) -> String {
    templates::current_deployment_dockerfile(has_database)
}

/// The `src/db.rs` that `proa new site` and `proa add database sqlite` both write.
pub(crate) fn database_module() -> &'static str {
    templates::database_module()
}

/// The managed-head `src/layouts/root.rs` that `proa new site` writes.
#[cfg(test)]
pub(crate) fn root_layout() -> &'static str {
    templates::root_layout()
}

#[derive(Debug, Clone)]
pub struct NewSiteOptions {
    pub path: PathBuf,
    pub destination: Option<PathBuf>,
    pub title: Option<String>,
    pub template: String,
    pub overrides: CapabilityOverrides,
    pub vscode: bool,
    pub agents_md: bool,
    pub no_git: bool,
    pub verify: bool,
    pub start: bool,
    pub open: bool,
    pub offline: bool,
    pub dry_run: Option<DryRunFormat>,
    pub json: bool,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct OperationReport<'a> {
    operation_id: &'static str,
    command_version: u16,
    project_root: &'a Path,
    planned_filesystem_operations: Vec<FilesystemOperation<'a>>,
    configuration_changes: CapabilitySelection,
    warnings: Vec<&'static str>,
    result: OperationResult<'a>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct FilesystemOperation<'a> {
    operation: &'static str,
    path: &'a Path,
    bytes: usize,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct OperationResult<'a> {
    status: &'a str,
    destination: &'a Path,
    package: &'a str,
    title: &'a str,
    selection: CapabilitySelection,
    files: usize,
    next: String,
}

pub(crate) fn scaffold_version(package: &str) -> String {
    let versions: std::collections::BTreeMap<String, String> = toml::from_str(include_str!(
        concat!(env!("OUT_DIR"), "/scaffold-versions.toml")
    ))
    .expect("bundled scaffold versions are valid TOML");
    let version = versions
        .get(package)
        .expect("scaffold dependency is listed");
    if package == "proa" {
        return proa_scaffold_requirement(version);
    }
    version.clone()
}

fn proa_scaffold_requirement(requirement: &str) -> String {
    // Cargo treats `0.4` and `0.4.0` alike, but `0.0` admits more than `0.0.0`.
    if let Ok(version) = semver::Version::parse(requirement) {
        if version.patch == 0
            && version.pre.is_empty()
            && version.build.is_empty()
            && (version.major != 0 || version.minor != 0)
        {
            return format!("{}.{}", version.major, version.minor);
        }
    }
    requirement.to_owned()
}

pub fn new_site(options: NewSiteOptions) -> Result<()> {
    let template = SiteTemplate::parse_compat(&options.template)?;
    let selection = CapabilitySelection::resolve(template, options.overrides)?;
    let root = resolve_destination(&options.path, options.destination.as_deref())?;
    transaction::ensure_destination_available(&root)?;
    let package = package_name(&root)?;
    let title = options.title.unwrap_or_else(|| display_title(&package));
    let capabilities = selection
        .capabilities()
        .into_iter()
        .map(|capability| capability.id.to_string())
        .collect();
    let mut plan = SitePlan::new(root.clone(), capabilities);
    templates::populate(
        &mut plan,
        &package,
        &title,
        selection,
        options.vscode,
        options.agents_md,
    )?;
    plan.validate()?;

    if let Some(format) = options.dry_run {
        print_plan(&plan, &package, &title, selection, format)?;
        return Ok(());
    }

    transaction::commit(&plan)?;
    if !options.no_git {
        transaction::initialize_git(&root)?;
    }
    print_success(&plan, &package, &title, selection, options.json)?;

    if options.verify {
        run_child(
            &root,
            &["check", "--all", "--root", root.to_string_lossy().as_ref()],
        )
        .context(
            "project was created, but verification failed; repair it and run `proa check --all`",
        )?;
    }
    if options.start || options.open {
        let root_arg = root.to_string_lossy().into_owned();
        let mut args = vec!["run", "--root", root_arg.as_str(), "dev"];
        if options.open {
            args.push("--open");
        }
        if options.offline {
            args.push("--offline");
        }
        run_child(&root, &args)?;
    }
    Ok(())
}

fn resolve_destination(path: &Path, parent: Option<&Path>) -> Result<PathBuf> {
    if path.as_os_str().is_empty() {
        bail!("site path cannot be empty");
    }
    if path.is_absolute() {
        if parent.is_some() {
            bail!("--destination cannot be combined with an absolute site path");
        }
        Ok(path.to_path_buf())
    } else {
        Ok(parent
            .map(Path::to_path_buf)
            .unwrap_or(env::current_dir()?)
            .join(path))
    }
}

fn package_name(root: &Path) -> Result<String> {
    let raw = root
        .file_name()
        .and_then(|value| value.to_str())
        .context("site path must end in a UTF-8 directory name")?;
    let mut package = String::with_capacity(raw.len());
    for character in raw.chars() {
        if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
            package.push(character.to_ascii_lowercase());
        } else if character.is_whitespace() {
            package.push('-');
        } else {
            package.push('_');
        }
    }
    while package.starts_with(|character: char| !character.is_ascii_alphabetic()) {
        package.remove(0);
    }
    if package.is_empty() {
        bail!("site path does not contain a valid package name");
    }
    Ok(package)
}

fn display_title(package: &str) -> String {
    package
        .split(['-', '_'])
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut characters = part.chars();
            match characters.next() {
                Some(first) => format!("{}{}", first.to_ascii_uppercase(), characters.as_str()),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn print_plan(
    plan: &SitePlan,
    package: &str,
    title: &str,
    selection: CapabilitySelection,
    format: DryRunFormat,
) -> Result<()> {
    match format {
        DryRunFormat::Json => println!(
            "{}",
            serde_json::to_string_pretty(&operation_report(
                plan, package, title, selection, "planned"
            ))?
        ),
        DryRunFormat::Text => {
            println!("Plan {}", plan.destination.display());
            for capability in &plan.capabilities {
                println!("  capability  {capability}");
            }
            for file in &plan.files {
                println!("  create      {} ({} B)", file.path.display(), file.bytes);
            }
        }
    }
    Ok(())
}

fn print_success(
    plan: &SitePlan,
    package: &str,
    title: &str,
    selection: CapabilitySelection,
    json: bool,
) -> Result<()> {
    let root = &plan.destination;
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&operation_report(
                plan, package, title, selection, "created"
            ))?
        );
        return Ok(());
    }
    println!("Created {package}\n");
    println!("  App         Proa + Axum");
    println!(
        "  Database    {}",
        if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
            "SQLite + SQLx"
        } else {
            "none"
        }
    );
    if selection.database == crate::capabilities::DatabaseChoice::Sqlite {
        println!("  Data        keyed loading through cx");
    }
    println!(
        "  UI          {}",
        match selection.ui {
            crate::capabilities::UiChoice::Proa => "proa-ui · 3 components vendored",
            crate::capabilities::UiChoice::ProaDocs => "proa-docs",
            crate::capabilities::UiChoice::None => "none",
        }
    );
    println!(
        "  Markdown    {}",
        if selection.markdown {
            "/index.md · Accept: text/markdown"
        } else {
            "disabled"
        }
    );
    println!(
        "  Client      {}",
        if selection.template == crate::capabilities::SiteTemplate::Origin {
            "rsjs flood-the-table island on /"
        } else {
            "no client root on /"
        }
    );
    println!("  Health      /healthz · /readyz");
    println!("\nNext:\n  cd {} && proa run dev --open", root.display());
    Ok(())
}

fn operation_report<'a>(
    plan: &'a SitePlan,
    package: &'a str,
    title: &'a str,
    selection: CapabilitySelection,
    status: &'a str,
) -> OperationReport<'a> {
    OperationReport {
        operation_id: "site.create",
        command_version: 1,
        project_root: &plan.destination,
        planned_filesystem_operations: plan
            .files
            .iter()
            .map(|file| FilesystemOperation {
                operation: "create",
                path: &file.path,
                bytes: file.bytes,
            })
            .collect(),
        configuration_changes: selection,
        warnings: Vec::new(),
        result: OperationResult {
            status,
            destination: &plan.destination,
            package,
            title,
            selection,
            files: plan.files.len(),
            next: format!("cd {} && proa run dev --open", plan.destination.display()),
        },
    }
}

fn run_child(root: &Path, args: &[&str]) -> Result<()> {
    let executable = crate::util::current_executable().context("locate the running Proa CLI")?;
    let status = Command::new(executable)
        .args(args)
        .current_dir(root)
        .status()
        .context("start Proa child command")?;
    if !status.success() {
        bail!("Proa child command failed with {status}");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::{DatabaseChoice, StarterChoice, StylingChoice, UiChoice};

    #[test]
    fn proa_requirement_shortens_only_equivalent_versions() {
        for (declared, expected) in [
            ("0.4.0", "0.4"),
            ("0.5.0", "0.5"),
            ("1.0.0", "1.0"),
            ("0.4.1", "0.4.1"),
            ("0.0.0", "0.0.0"),
            ("0.5.0-rc.1", "0.5.0-rc.1"),
            ("=0.4.0", "=0.4.0"),
        ] {
            assert_eq!(proa_scaffold_requirement(declared), expected);
        }
    }

    fn options(path: PathBuf) -> NewSiteOptions {
        NewSiteOptions {
            path,
            destination: None,
            title: None,
            template: "app".to_string(),
            overrides: CapabilityOverrides::default(),
            vscode: true,
            agents_md: true,
            no_git: true,
            verify: false,
            start: false,
            open: false,
            offline: true,
            dry_run: None,
            json: false,
        }
    }

    #[test]
    fn default_tree_has_application_first_contract() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("journal");
        new_site(options(root.clone())).unwrap();
        for path in [
            "src/db.rs",
            "src/loader.rs",
            "src/components/database_badge.rs",
            "src/components/database_card.rs",
            "src/components/badge/md.rs",
            "migrations/.gitkeep",
            "data/.gitkeep",
            "tests/dataloader.rs",
            "tests/database.rs",
            "tests/representations.rs",
        ] {
            assert!(root.join(path).exists(), "missing {path}");
        }
        // Tailwind owns the generated public output; its input must include
        // the starter design so the first asset build retains that design.
        let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
        assert!(!config.contains("build: proa::config::BuildConfig"));
        assert!(!config.contains("paths: proa::config::ProjectPaths"));
        let config = crate::config::load_project_config(&root).unwrap();
        assert_eq!(config.paths.public.as_deref(), Some(Path::new("public")));
        let [asset] = config.build.assets() else {
            panic!("expected one inferred Tailwind asset");
        };
        assert_eq!(asset.kind, "tailwind");
        assert_eq!(asset.input, Path::new("styles/input.css"));
        assert_eq!(asset.output, Path::new("public/styles.css"));
        let input = std::fs::read_to_string(root.join("styles/input.css")).unwrap();
        assert!(input.contains("@import \"./starter.css\" layer(components);"));
        let starter = std::fs::read_to_string(root.join("styles/starter.css")).unwrap();
        assert_eq!(
            starter,
            std::fs::read_to_string(root.join("public/styles.css")).unwrap()
        );
        assert!(!root.join("scripts").exists());
        assert!(!root.join("src/islands").exists());
        assert!(!root.join("rust-toolchain.toml").exists());
        let cargo_toml = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
        assert!(cargo_toml.contains("rust-version = \"1.98\""));
        let home = std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap();
        let parsed_home = syn::parse_file(&home).unwrap();
        let mut saw_non_use_item = false;
        for item in &parsed_home.items {
            if matches!(item, syn::Item::Use(_)) {
                assert!(
                    !saw_non_use_item,
                    "src/pages/home.rs should keep all `use` imports at the top of the file"
                );
            } else {
                saw_non_use_item = true;
            }
        }
        assert!(home.contains("const ROLE: ComponentRole = ComponentRole::PAGE;"));
        assert!(home.contains("async fn render_head("));
        assert!(!home.contains("with_head"));
        let layout = std::fs::read_to_string(root.join("src/layouts/root.rs")).unwrap();
        assert!(layout.contains("const ROLE: ComponentRole = ComponentRole::LAYOUT;"));
        assert!(layout.contains("{cx.head()}"));
        assert!(home.contains("DataResolver::request_scope"));
        assert!(home.contains("MdRender<L> for HomePage"));
        assert!(home.contains("# {HEADLINE}"));
        assert!(!home.contains("Rust\\."));
        assert!(!home.contains("multi\\-target"));
        let routes = std::fs::read_to_string(root.join("src/routes.rs")).unwrap();
        assert!(routes.contains("PublicAssets::configured()"));
        assert!(routes.contains(".with_head(proa::HeadConfig::default())"));
    }

    #[test]
    fn every_preset_has_canonical_macros_and_clean_component_hashes() {
        let temp = tempfile::tempdir().unwrap();
        for template in ["minimal", "app", "marketing", "docs", "origin"] {
            let root = temp.path().join(template);
            let mut value = options(root.clone());
            value.template = template.to_string();
            new_site(value).unwrap();
            assert!(!root.join(".cargo/config.toml").exists(), "{template}");
            assert!(!root.join("rust-toolchain.toml").exists(), "{template}");
            let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
            assert!(!config.contains("template:"), "{template}");
            let formatting =
                crate::fmt::format_paths_with_options(std::slice::from_ref(&root), true, true)
                    .unwrap();
            assert!(
                formatting.changed.is_empty() && formatting.diagnostics.is_empty(),
                "{template}: {:?}",
                formatting.diagnostics
            );
            let diagnostics =
                crate::lint::lint_paths(&[root.join("src")], crate::lint::LintOptions::default())
                    .unwrap();
            assert!(
                diagnostics
                    .iter()
                    .all(|diagnostic| diagnostic.severity.rank()
                        < crate::diagnostic::Severity::Warning.rank()),
                "{template}: {diagnostics:?}"
            );
            let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
            assert!(report.errors.is_empty(), "{template}: {:?}", report.errors);
            let routes = crate::scaffold::site_routes(Some(root)).unwrap();
            let markdown = routes.iter().find(|route| route.path == "/index.md");
            match template {
                "minimal" => assert!(markdown.is_none()),
                "origin" => assert_eq!(markdown.unwrap().file, Path::new("src/lib.rs")),
                _ => assert_eq!(markdown.unwrap().file, Path::new("src/pages/home.rs")),
            }
        }
    }

    #[test]
    fn any_title_scaffolds_rust_that_parses_and_keeps_the_title() {
        // Quotes, backslashes, braces, raw-string terminators, a newline,
        // non-ASCII, and the home page template's own placeholder names.
        let title =
            "Sam's \"Quote\" \\ {x}} \"# \"## # caf\u{e9} \u{65e5}\u{672c} \u{1f680}\nline2 \
            __IMPORTS__ __CONSTANTS__ __RENDER_IMPL__ __MARKDOWN_IMPL__ __ARGS__ \
            __HTML_RESPONSE__ __RESPONSE__ __MD_HANDLER__ __HEAD__ __BODY__";
        let temp = tempfile::tempdir().unwrap();
        for (template, starter) in [
            ("app", None),
            ("app", Some(StarterChoice::Blank)),
            ("marketing", None),
            ("docs", None),
            ("minimal", None),
            ("origin", None),
        ] {
            let root = temp
                .path()
                .join(format!("{template}-{}", starter.is_some()));
            let mut value = options(root.clone());
            value.template = template.to_string();
            value.overrides.starter = starter;
            value.title = Some(title.to_string());
            new_site(value).unwrap();
            for entry in walkdir::WalkDir::new(&root) {
                let path = entry.unwrap().into_path();
                if path.extension().is_some_and(|extension| extension == "rs") {
                    let source = std::fs::read_to_string(&path).unwrap();
                    if let Err(error) = syn::parse_file(&source) {
                        panic!("{template}: {} does not parse: {error}", path.display());
                    }
                }
            }
            if template == "origin" {
                continue;
            }
            let home =
                syn::parse_file(&std::fs::read_to_string(root.join("src/pages/home.rs")).unwrap())
                    .unwrap();
            let constant = home
                .items
                .iter()
                .find_map(|item| match item {
                    syn::Item::Const(constant) if constant.ident == "TITLE" => Some(constant),
                    _ => None,
                })
                .expect("home page declares TITLE");
            let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(literal),
                ..
            }) = constant.expr.as_ref()
            else {
                panic!("TITLE is a string literal");
            };
            assert_eq!(literal.value(), title, "{template}");
        }
    }

    #[test]
    fn agents_md_states_the_head_role_contract() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("agents");
        new_site(options(root.clone())).unwrap();
        let agents = std::fs::read_to_string(root.join("AGENTS.md")).unwrap();
        assert!(agents.contains("const ROLE: ComponentRole = ComponentRole::PAGE;"));
        assert!(agents.contains("ComponentRole::LAYOUT"));
        assert!(agents.contains("render_head"));
    }

    #[test]
    fn customized_pages_preserve_capability_checks() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("customized");
        new_site(options(root.clone())).unwrap();
        let home_path = root.join("src/pages/home.rs");
        let source = std::fs::read_to_string(&home_path)
            .unwrap()
            .replace("HomePage", "IssuePage")
            .replace("/index.md", "/issues.md");
        let issue_path = root.join("src/pages/issues.rs");
        std::fs::write(&issue_path, &source).unwrap();
        std::fs::write(
            &home_path,
            "pub async fn handler() -> &'static str { \"Welcome\" }\n",
        )
        .unwrap();
        let report = crate::scaffold::site_check(Some(root.clone())).unwrap();
        assert!(report.errors.is_empty(), "{:?}", report.errors);

        // Removing a capability still fails after moving the real page.
        std::fs::write(
            &issue_path,
            source
                .replace("DataResolver::request_scope", "DataResolver::new")
                .replace("explicit_markdown_async_with_loader(", "other_response("),
        )
        .unwrap();
        let report = crate::scaffold::site_check(Some(root)).unwrap();
        assert!(report
            .errors
            .iter()
            .any(|e| e.contains("request-scoped DataResolver")));
        assert!(report
            .errors
            .iter()
            .any(|e| e.contains("explicit_markdown(")));
    }

    #[test]
    fn capability_deltas_remove_owned_outputs() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("bare");
        let mut value = options(root.clone());
        value.overrides.database = Some(DatabaseChoice::None);
        value.overrides.ui = Some(UiChoice::None);
        value.overrides.styling = Some(StylingChoice::Css);
        value.vscode = false;
        new_site(value).unwrap();
        let config = std::fs::read_to_string(root.join(crate::config::CONFIG_FILE)).unwrap();
        assert!(config.contains("assets: Some(vec![])"));
        assert!(!root.join("src/db.rs").exists());
        assert!(!root.join("src/components/badge").exists());
        assert!(!root.join("styles").exists());
        assert!(!root.join(".vscode").exists());
    }

    #[test]
    fn dry_run_and_nonempty_refusal_do_not_write() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("dry");
        let mut value = options(root.clone());
        value.dry_run = Some(DryRunFormat::Json);
        new_site(value).unwrap();
        assert!(!root.exists());

        std::fs::create_dir(&root).unwrap();
        std::fs::write(root.join("keep"), "mine").unwrap();
        let error = new_site(options(root.clone())).unwrap_err();
        assert!(error.to_string().contains("not empty"));
        assert_eq!(std::fs::read_to_string(root.join("keep")).unwrap(), "mine");
    }
}