rustango_cms/migrations.rs
1//! Embed + materialize the bundled CMS migrations.
2//!
3//! `rustango-cms` ships its own per-tenant schema (cms_page,
4//! cms_page_type, cms_locale, cms_media, …) as JSON migration files
5//! under `migrations/`. Downstream apps need those migrations applied
6//! against every active tenant, but they live inside the library
7//! crate — not the user's project — so the manage CLI's
8//! migration-runner has nowhere to find them by default.
9//!
10//! Solution: `rustango::embed_migrations!` bakes the JSON into the
11//! library at compile time as `&'static [(name, json)]`. The
12//! [`materialize`] helper writes any missing entries into the user
13//! project's `migrations/` dir on first boot. Idempotent — existing
14//! files (with matching names) are left alone, so user customizations
15//! are not clobbered.
16//!
17//! ## Wiring
18//!
19//! ```ignore
20//! use rustango::manage::Cli;
21//!
22//! #[rustango::main]
23//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
24//! let migrations_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
25//! .join("migrations");
26//! // Materialize CMS-bundled migrations before the runner reads
27//! // the directory. Safe to call on every boot.
28//! rustango_cms::migrations::materialize(&migrations_dir)?;
29//!
30//! Cli::new()
31//! .tenancy()
32//! .migrations_dir(migrations_dir)
33//! /* … */
34//! .run().await
35//! }
36//! ```
37
38use std::path::Path;
39
40/// The CMS migrations embedded at compile time. One entry per JSON
41/// file in `rustango-cms/migrations/`. The macro also performs static
42/// chain validation — a broken `prev` reference fails the build
43/// rather than the runner.
44///
45/// Order is lex-sorted by file stem to match the on-disk apply order.
46pub const MIGRATIONS: &[(&str, &str)] = rustango::embed_migrations!("migrations");
47
48/// Write every embedded CMS migration into `target_dir` if a file
49/// with the matching name doesn't already exist. Idempotent — safe
50/// to call on every boot. Existing files are not overwritten so user
51/// edits / squashed-migration overrides survive.
52///
53/// # Errors
54/// I/O errors creating the directory or writing files.
55///
56/// # Example
57///
58/// ```no_run
59/// let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("migrations");
60/// rustango_cms::migrations::materialize(&dir).expect("materialize CMS migrations");
61/// ```
62pub fn materialize(target_dir: &Path) -> std::io::Result<()> {
63 std::fs::create_dir_all(target_dir)?;
64 let mut wrote = 0usize;
65 for (name, json) in MIGRATIONS {
66 let path = target_dir.join(format!("{name}.json"));
67 if path.exists() {
68 continue;
69 }
70 std::fs::write(&path, json)?;
71 wrote += 1;
72 }
73 if wrote > 0 {
74 tracing::info!(
75 target: "rustango_cms::migrations",
76 dir = %target_dir.display(),
77 count = wrote,
78 "materialized bundled CMS migrations",
79 );
80 }
81 Ok(())
82}