Skip to main content

proa_cli/site_scaffold/
plan.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::path::{Path, PathBuf};
5
6use anyhow::{bail, Context, Result};
7use serde::Serialize;
8
9#[derive(Debug, Clone, Serialize)]
10#[serde(rename_all = "camelCase")]
11pub struct PlannedFile {
12    pub path: PathBuf,
13    pub bytes: usize,
14    #[serde(skip)]
15    pub content: String,
16}
17
18#[derive(Debug, Clone, Serialize)]
19#[serde(rename_all = "camelCase")]
20pub struct SitePlan {
21    pub destination: PathBuf,
22    pub files: Vec<PlannedFile>,
23    pub capabilities: Vec<String>,
24}
25
26impl SitePlan {
27    pub fn new(destination: PathBuf, capabilities: Vec<String>) -> Self {
28        Self {
29            destination,
30            files: Vec::new(),
31            capabilities,
32        }
33    }
34
35    pub fn write(&mut self, relative: impl AsRef<Path>, content: impl Into<String>) -> Result<()> {
36        let relative = relative.as_ref();
37        validate_relative(relative)?;
38        if self.files.iter().any(|file| file.path == relative) {
39            bail!("scaffold planned `{}` more than once", relative.display());
40        }
41        let content = content.into();
42        self.files.push(PlannedFile {
43            path: relative.to_path_buf(),
44            bytes: content.len(),
45            content,
46        });
47        Ok(())
48    }
49
50    pub fn validate(&self) -> Result<()> {
51        for required in [
52            "Cargo.toml",
53            "src/main.rs",
54            "proa.config.json",
55            "proa.lock.json",
56            "public/styles.css",
57        ] {
58            if !self
59                .files
60                .iter()
61                .any(|file| file.path == Path::new(required))
62            {
63                bail!("scaffold plan is missing required file `{required}`");
64            }
65        }
66        for file in &self.files {
67            if file.content.contains("__PACKAGE__")
68                || file.content.contains("__TITLE__")
69                || file.content.contains("__DATABASE_URL__")
70            {
71                bail!(
72                    "scaffold template placeholder remained in `{}`",
73                    file.path.display()
74                );
75            }
76            if file.path.extension().and_then(|value| value.to_str()) == Some("json") {
77                serde_json::from_str::<serde_json::Value>(&file.content)
78                    .with_context(|| format!("validate generated {}", file.path.display()))?;
79            }
80            if file.path.extension().and_then(|value| value.to_str()) == Some("rs") {
81                syn::parse_file(&file.content)
82                    .with_context(|| format!("parse generated {}", file.path.display()))?;
83            }
84        }
85        Ok(())
86    }
87}
88
89fn validate_relative(path: &Path) -> Result<()> {
90    if path.is_absolute() || path.as_os_str().is_empty() {
91        bail!("planned file paths must be nonempty and relative");
92    }
93    if path.components().any(|component| {
94        matches!(
95            component,
96            std::path::Component::ParentDir
97                | std::path::Component::RootDir
98                | std::path::Component::Prefix(_)
99        )
100    }) {
101        bail!("planned file path escapes the project: {}", path.display());
102    }
103    Ok(())
104}