Skip to main content

rustango_cms/starter/
cli.rs

1//! `cargo run -- theme …`: pack a site into a theme package, install one,
2//! or check one.
3//!
4//! ```text
5//! theme pack <file.zip> [--site <slug>] [--no-pages]
6//! theme install <file.zip> [--site <slug>]
7//! theme check <file.zip | theme.json>
8//! ```
9//!
10//! The site is a tenant: `--site` names it, and it may be left out when the
11//! registry has a single active site. Templates are read from and written
12//! to `$RCMS_SITE_DIR/templates` (default `./templates`). `install` first
13//! copies the current folder to `templates.bak-<timestamp>`, then writes
14//! the package's templates over it: files the package does not have stay,
15//! so pages of a type the package doesn't know keep their template.
16
17use std::error::Error;
18use std::path::{Path, PathBuf};
19
20use rustango::sql::{sqlx, FetcherPool as _, Pool};
21use rustango::tenancy::{Org, TenantPools};
22
23use super::package;
24use super::Outcome;
25
26pub const COMMAND: &str = "theme";
27
28const USAGE: &str = "usage:
29  theme pack <file.zip> [--site <slug>] [--no-pages]
30  theme install <file.zip> [--site <slug>]
31  theme check <file.zip | theme.json>";
32
33type BoxError = Box<dyn Error>;
34
35/// Run the `theme` command; `args` are the words after `theme`.
36///
37/// # Errors
38/// Bad arguments, an unknown site, an invalid package, or I/O and
39/// database errors, each described for the person at the terminal.
40pub async fn run(args: &[String]) -> Result<(), BoxError> {
41    let (verb, rest) = args.split_first().ok_or(USAGE)?;
42    let mut file: Option<PathBuf> = None;
43    let mut site: Option<String> = None;
44    let mut with_pages = true;
45    let mut i = 0;
46    while i < rest.len() {
47        match rest[i].as_str() {
48            "--site" => {
49                i += 1;
50                site = Some(rest.get(i).ok_or("--site needs a slug")?.clone());
51            }
52            "--no-pages" => with_pages = false,
53            flag if flag.starts_with('-') => return Err(format!("unknown flag `{flag}`\n{USAGE}").into()),
54            path if file.is_none() => file = Some(PathBuf::from(path)),
55            extra => return Err(format!("unexpected `{extra}`\n{USAGE}").into()),
56        }
57        i += 1;
58    }
59    let file = file.ok_or(USAGE)?;
60    let templates = templates_dir();
61
62    match verb.as_str() {
63        "check" => {
64            let json = if file.extension().is_some_and(|e| e == "json") {
65                std::fs::read_to_string(&file)?
66            } else {
67                package::read_seed(&file)?
68            };
69            let seed = super::parse(&json)?;
70            println!(
71                "{}: valid — {} page type(s), {} menu(s){}",
72                seed.name,
73                seed.page_types.len(),
74                seed.menus.len(),
75                if seed.pages.is_empty() { ", look only (no pages)" } else { "" }
76            );
77        }
78        "pack" => {
79            let (org, pool) = site_pool(site.as_deref()).await?;
80            let seed = package::export(&pool, &org.display_name, with_pages).await?;
81            let files = package::pack(&seed, &templates, &file)?;
82            println!(
83                "packed `{}` into {}: theme.json + {files} template file(s){}",
84                org.slug,
85                file.display(),
86                if with_pages { "" } else { " (look only, no pages)" }
87            );
88        }
89        "install" => {
90            // Validate before touching anything on disk.
91            let json = package::read_seed(&file)?;
92            super::parse(&json)?;
93            let (org, pool) = site_pool(site.as_deref()).await?;
94            let backup = copy_aside(&templates)?;
95            let (_, written) = package::unpack(&file, &templates)?;
96            let outcome = package::install(&pool, &json).await?;
97            match outcome {
98                Outcome::Applied { pages, .. } => {
99                    println!("installed on `{}` (an empty site): {pages} page(s), menus and colours", org.slug);
100                }
101                Outcome::Switched { page_types_added, page_types_retemplated, error_pages_added } => println!(
102                    "switched `{}` to the package's look: {written} template file(s), \
103                     {page_types_added} page type(s) added, {page_types_retemplated} re-templated, \
104                     {error_pages_added} error page(s) added; other pages, menus and settings unchanged",
105                    org.slug
106                ),
107                Outcome::AlreadyApplied | Outcome::SiteNotEmpty => {}
108            }
109            if let Some(b) = backup {
110                println!("previous templates kept in {}", b.display());
111            }
112            for (type_name, template) in missing_templates(&pool, &templates).await? {
113                println!(
114                    "warning: pages of type `{type_name}` render with `{template}`, which is not in {}",
115                    templates.display()
116                );
117            }
118            println!("restart the server to load the new templates");
119        }
120        other => return Err(format!("unknown theme command `{other}`\n{USAGE}").into()),
121    }
122    Ok(())
123}
124
125fn templates_dir() -> PathBuf {
126    std::env::var_os("RCMS_SITE_DIR")
127        .map(PathBuf::from)
128        .unwrap_or_else(|| PathBuf::from("."))
129        .join("templates")
130}
131
132/// Copy `dir` to `dir.bak-<timestamp>`; `None` when it does not exist.
133fn copy_aside(dir: &Path) -> Result<Option<PathBuf>, BoxError> {
134    if !dir.exists() {
135        return Ok(None);
136    }
137    let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
138    let name = format!("{}.bak-{stamp}", dir.file_name().and_then(|n| n.to_str()).unwrap_or("templates"));
139    let backup = dir.with_file_name(name);
140    copy_dir(dir, &backup)?;
141    Ok(Some(backup))
142}
143
144fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
145    std::fs::create_dir_all(to)?;
146    for entry in std::fs::read_dir(from)? {
147        let path = entry?.path();
148        let dest = to.join(path.file_name().unwrap_or_default());
149        if path.is_dir() {
150            copy_dir(&path, &dest)?;
151        } else {
152            std::fs::copy(&path, &dest)?;
153        }
154    }
155    Ok(())
156}
157
158/// Page types with live pages whose template file is not under
159/// `templates` (only names that look like a file in that folder; the
160/// CMS's own `rcms_admin/…` templates are built in).
161async fn missing_templates(pool: &Pool, templates: &Path) -> Result<Vec<(String, String)>, BoxError> {
162    use crate::page::Page;
163    use crate::page_type_model::PageType;
164    let used: std::collections::HashSet<i64> = Page::objects()
165        .fetch(pool)
166        .await?
167        .into_iter()
168        .map(|p| p.page_type_id)
169        .collect();
170    let mut missing = Vec::new();
171    for t in PageType::objects().fetch(pool).await? {
172        let in_use = t.id.get().is_some_and(|id| used.contains(id));
173        let template = t.default_template.clone();
174        if in_use
175            && !template.is_empty()
176            && !template.starts_with("rcms_admin/")
177            && !templates.join(&template).exists()
178        {
179            missing.push((t.type_name, template));
180        }
181    }
182    Ok(missing)
183}
184
185/// The tenant pool of the site named `slug`, or of the only active site.
186async fn site_pool(slug: Option<&str>) -> Result<(Org, Pool), BoxError> {
187    let url = std::env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set (see .env)")?;
188    let registry = Pool::connect(&url).await?;
189    match registry {
190        #[cfg(feature = "postgres")]
191        Pool::Postgres(pg) => pick(TenantPools::<sqlx::Postgres>::new(pg), slug).await,
192        #[cfg(feature = "sqlite")]
193        Pool::Sqlite(sq) => pick(TenantPools::<sqlx::Sqlite>::new(sq), slug).await,
194        #[cfg(feature = "mysql")]
195        Pool::Mysql(my) => pick(TenantPools::<sqlx::MySql>::new(my), slug).await,
196    }
197}
198
199async fn pick<DB>(pools: TenantPools<DB>, slug: Option<&str>) -> Result<(Org, Pool), BoxError>
200where
201    DB: sqlx::Database,
202    Pool: From<sqlx::Pool<DB>>,
203{
204    let orgs: Vec<Org> = Org::objects()
205        .fetch(&pools.registry_pool())
206        .await?
207        .into_iter()
208        .filter(|o| o.active)
209        .collect();
210    let names = || orgs.iter().map(|o| o.slug.as_str()).collect::<Vec<_>>().join(", ");
211    let org = match slug {
212        Some(s) => orgs
213            .iter()
214            .find(|o| o.slug == s)
215            .ok_or_else(|| format!("no active site `{s}` (sites: {})", names()))?,
216        None if orgs.len() == 1 => &orgs[0],
217        None => return Err(format!("name the site with --site (sites: {})", names()).into()),
218    };
219    let pool = pools.scoped_pool_dyn(org).await?;
220    Ok((org.clone(), pool))
221}