use std::{
fs::{self, OpenOptions},
io::Write,
path::{Path, PathBuf},
process::Command,
};
use anyhow::{bail, Context, Result};
use serde::Serialize;
use crate::{config, scaffold::rust_string_literal, util::resolve_config_root};
mod registered_routes;
use registered_routes::ensure_routes_unregistered;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct GenerateReport {
operation_id: &'static str,
command_version: u16,
project_root: PathBuf,
planned_filesystem_operations: Vec<GenerateOperation>,
configuration_changes: Vec<String>,
warnings: Vec<String>,
result: &'static str,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct GenerateOperation {
operation: &'static str,
path: PathBuf,
bytes: usize,
}
pub fn migration(
raw_name: String,
root: Option<PathBuf>,
simple: bool,
open: bool,
dry_run: bool,
json: bool,
) -> Result<()> {
let root = resolve_config_root(root)?;
require_sqlite(&root)?;
let migrations = root.join("migrations");
fs::create_dir_all(&migrations)?;
let _lock = DirectoryLock::acquire(&migrations)?;
let name = snake_name(&raw_name)?;
let version = next_migration_version(&migrations)?;
let base = format!("{version:04}_{name}");
let files = if simple {
vec![(migrations.join(format!("{base}.sql")), simple_sql(&name))]
} else {
vec![
(migrations.join(format!("{base}.up.sql")), up_sql(&name)),
(migrations.join(format!("{base}.down.sql")), down_sql(&name)),
]
};
for (path, _) in &files {
if path.exists() {
bail!("migration already exists: {}", path.display());
}
}
let report = GenerateReport {
operation_id: "generate.migration",
command_version: 1,
project_root: root.clone(),
planned_filesystem_operations: files
.iter()
.map(|(path, source)| GenerateOperation {
operation: "create",
path: path.strip_prefix(&root).unwrap_or(path).to_path_buf(),
bytes: source.len(),
})
.collect(),
configuration_changes: Vec::new(),
warnings: Vec::new(),
result: if dry_run { "planned" } else { "created" },
};
if dry_run {
print_report(&report, json)?;
return Ok(());
}
commit_new_files(&files)?;
print_report(&report, json)?;
if open {
open_files(files.iter().map(|(path, _)| path))?;
}
Ok(())
}
pub fn page(
raw_path: String,
root: Option<PathBuf>,
_layout: Option<String>,
force_markdown: bool,
no_markdown: bool,
dry_run: bool,
json: bool,
) -> Result<()> {
let root = resolve_config_root(root)?;
let route = route_name(&raw_path)?;
let configured_markdown = config::load_component_lock(&root)?.scaffold_markdown() == Some(true);
let markdown = force_markdown || (!no_markdown && configured_markdown);
if force_markdown && !configured_markdown {
bail!("Markdown is not installed for this project; run `proa add representation markdown` first");
}
let module_path = root.join("src/pages").join(format!("{}.rs", route.module));
if module_path.exists() {
bail!("page already exists: {}", module_path.display());
}
let mut modules = fs::read_to_string(root.join("src/pages/mod.rs"))?;
add_module(&mut modules, &route.module);
let routes_path = root.join("src/routes.rs");
let mut routes = fs::read_to_string(&routes_path)?;
let captured_alias = markdown && route.canonical.ends_with('}');
let explicit_alias = (markdown && !captured_alias).then_some(route.markdown_alias.as_str());
ensure_routes_unregistered(&routes, &route.canonical, explicit_alias)?;
let handler = if captured_alias {
"handler_with_markdown_alias"
} else {
"handler"
};
add_route_spec(
&mut routes,
&format!(
" Route::endpoint({}, get(pages::{}::{handler})),",
rust_string_literal(&route.canonical),
route.module
),
)?;
if let Some(alias) = explicit_alias {
add_explicit_route(
&mut routes,
&format!(
" .route({}, get(pages::{}::markdown))",
rust_string_literal(alias),
route.module
),
)?;
}
let files = vec![
(
PathBuf::from(format!("src/pages/{}.rs", route.module)),
crate::scaffold::format_generated_rust(
&module_path,
&page_source(&route, markdown, crate::scaffold::site_manages_head(&root)),
)?,
),
(PathBuf::from("src/pages/mod.rs"), modules),
(PathBuf::from("src/routes.rs"), routes),
];
finish_generated(&root, "generate.page", files, dry_run, json)
}
pub fn endpoint(
raw_path: String,
root: Option<PathBuf>,
method: &'static str,
response: &'static str,
dry_run: bool,
json: bool,
) -> Result<()> {
let root = resolve_config_root(root)?;
let route = route_name(&raw_path)?;
let module_path = root
.join("src/endpoints")
.join(format!("{}.rs", route.module));
if module_path.exists() {
bail!("endpoint already exists: {}", module_path.display());
}
let mut modules = fs::read_to_string(root.join("src/endpoints/mod.rs"))?;
add_module(&mut modules, &route.module);
let routes_path = root.join("src/routes.rs");
let mut routes = fs::read_to_string(&routes_path)?;
let registration = format!(
" Route::endpoint({}, axum::routing::{}(endpoints::{}::handler)),",
rust_string_literal(&route.canonical),
method,
route.module
);
ensure_routes_unregistered(&routes, &route.canonical, None)?;
add_route_spec(&mut routes, ®istration)?;
let files = vec![
(
PathBuf::from(format!("src/endpoints/{}.rs", route.module)),
endpoint_source(response),
),
(PathBuf::from("src/endpoints/mod.rs"), modules),
(PathBuf::from("src/routes.rs"), routes),
];
finish_generated(&root, "generate.endpoint", files, dry_run, json)
}
pub fn model(
raw_name: String,
raw_fields: Vec<String>,
root: Option<PathBuf>,
dry_run: bool,
json: bool,
) -> Result<()> {
let root = resolve_config_root(root)?;
require_sqlite(&root)?;
let name = snake_name(&raw_name)?;
let struct_name = rust_type_name(&name);
let fields = raw_fields
.iter()
.map(|field| parse_model_field(field))
.collect::<Result<Vec<_>>>()?;
let model_path = root.join("src/models").join(format!("{name}.rs"));
if model_path.exists() {
bail!("model already exists: {}", model_path.display());
}
let migrations = root.join("migrations");
fs::create_dir_all(&migrations)?;
let _lock = DirectoryLock::acquire(&migrations)?;
let version = next_migration_version(&migrations)?;
let table = format!("{name}s");
let mut modules = fs::read_to_string(root.join("src/models/mod.rs")).unwrap_or_default();
add_module(&mut modules, &name);
let files = vec![
(
PathBuf::from(format!("src/models/{name}.rs")),
model_source(&struct_name, &fields),
),
(PathBuf::from("src/models/mod.rs"), modules),
(
PathBuf::from(format!("migrations/{version:04}_create_{table}.up.sql")),
model_up_sql(&table, &fields),
),
(
PathBuf::from(format!("migrations/{version:04}_create_{table}.down.sql")),
format!("DROP TABLE {table};\n"),
),
];
finish_generated(&root, "generate.model", files, dry_run, json)
}
#[derive(Debug)]
struct RouteName {
canonical: String,
markdown_alias: String,
module: String,
rust_type: String,
title: String,
}
fn route_name(raw: &str) -> Result<RouteName> {
let trimmed = raw.trim().trim_matches('/');
if trimmed.is_empty()
|| trimmed
.split('/')
.any(|part| part.is_empty() || part == "." || part == "..")
{
bail!("route path must contain safe, nonempty segments");
}
if let Some(character) = trimmed.chars().find(|&character| {
!character.is_ascii_alphanumeric() && !"/-._~!$&'()*+,;=:@%{}".contains(character)
}) {
bail!(
"route path `{trimmed}` contains {character:?}; use URL path characters and `{{name}}` captures"
);
}
let mut module_parts = Vec::new();
let canonical = canonical_route(&format!("/{trimmed}"));
for part in canonical.trim_start_matches('/').split('/') {
let name = part
.strip_prefix('{')
.and_then(|name| name.strip_suffix('}'))
.unwrap_or(part);
module_parts.push(snake_name(name)?);
}
let module = module_parts.join("_");
Ok(RouteName {
markdown_alias: format!("{canonical}.md"),
rust_type: format!("{}Page", rust_type_name(&module)),
title: human_title(&module),
canonical,
module,
})
}
fn canonical_route(path: &str) -> String {
path.split('/')
.map(|segment| {
if let Some(name) = segment.strip_prefix(':') {
format!("{{{name}}}")
} else if let Some(name) = segment.strip_prefix('*') {
format!("{{*{name}}}")
} else {
segment.to_string()
}
})
.collect::<Vec<_>>()
.join("/")
}
fn human_title(name: &str) -> String {
name.split('_')
.filter(|part| !part.is_empty())
.map(|part| {
let mut characters = part.chars();
characters
.next()
.map(|first| format!("{}{}", first.to_ascii_uppercase(), characters.as_str()))
.unwrap_or_default()
})
.collect::<Vec<_>>()
.join(" ")
}
fn rust_type_name(name: &str) -> String {
name.split('_')
.filter(|part| !part.is_empty())
.map(|part| {
let mut characters = part.chars();
characters
.next()
.map(|first| format!("{}{}", first.to_ascii_uppercase(), characters.as_str()))
.unwrap_or_default()
})
.collect()
}
fn add_module(source: &mut String, module: &str) {
let declaration = format!("pub mod {module};");
if !source.lines().any(|line| line.trim() == declaration) {
if !source.ends_with('\n') {
source.push('\n');
}
source.push_str(&declaration);
source.push('\n');
}
}
fn add_route_spec(source: &mut String, line: &str) -> Result<()> {
insert_before_marker(source, " // proa:route-specs:end", line)
}
fn add_explicit_route(source: &mut String, line: &str) -> Result<()> {
insert_before_marker(source, " // proa:explicit-routes:end", line)
}
fn insert_before_marker(source: &mut String, marker: &str, line: &str) -> Result<()> {
let offset = source.find(marker).with_context(|| {
format!("generated ownership marker `{marker}` is missing; no arbitrary Rust was changed")
})?;
source.insert_str(offset, &format!("{line}\n"));
Ok(())
}
fn page_source(route: &RouteName, markdown: bool, managed_head: bool) -> String {
let title = rust_string_literal(&route.title);
let (head_imports, title_field, page_head) = if managed_head {
(
"ComponentRole, SyncHeadOperation, ",
String::new(),
format!(
" const ROLE: ComponentRole = ComponentRole::PAGE;\n\n fn render_head(&self, cx: &mut WebContext<L>) -> impl SyncHeadOperation {{\n cx.head_mut().title({title})\n }}\n\n"
),
)
} else {
("", format!("\n title: {title},"), String::new())
};
let document = format!(
"RootDocument {{{title_field}\n content: proa::to_async({}),\n }}",
route.rust_type
);
let imports = if markdown {
format!("use axum::{{http::HeaderMap, response::IntoResponse}};\nuse proa::{{{head_imports}DataLoader, MdRenderSync, WebContext, WebRenderSync, WriteBuf, WriteError}};\nuse proa::axum::{{negotiate, MarkdownAlternate, RouteResponse}};\nuse proa::{{html_sync, md_sync}};")
} else {
format!("use axum::response::IntoResponse;\nuse proa::{{{head_imports}DataLoader, WebContext, WebRenderSync, WriteError}};\nuse proa::axum::RouteResponse;\nuse proa::html_sync;")
};
let markdown_impl = if markdown {
let alias_handler = if route.canonical.ends_with('}') {
r#"
pub async fn handler_with_markdown_alias(uri: axum::http::Uri, headers: HeaderMap) -> Result<impl IntoResponse, AppError> {
if uri.path().ends_with(".md") {
return Ok(markdown().await?.into_response());
}
Ok(handler(headers).await?.into_response())
}
"#
} else {
""
};
format!(
r####"
impl<L: proa::DataLoader, B: WriteBuf> MdRenderSync<L, B> for {ty} {{
fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {{
md_sync! {{ r###"
# {title}
Canonical route: `{path}`
"###
}}
.render_md(cx)
}}
}}
const MARKDOWN_ALTERNATE: MarkdownAlternate = MarkdownAlternate::new({alias});
pub async fn handler(headers: HeaderMap) -> Result<impl IntoResponse, AppError> {{
let html = RouteResponse::ssr_async({document});
Ok(negotiate(&headers, html, {ty}, MARKDOWN_ALTERNATE)?)
}}
pub async fn markdown() -> Result<impl IntoResponse, AppError> {{
Ok(MARKDOWN_ALTERNATE.render_explicit({ty})?)
}}
{alias_handler}"####,
ty = route.rust_type,
title = route.title,
path = route.canonical,
alias = rust_string_literal(&route.markdown_alias)
)
} else {
format!(
"\npub async fn handler() -> Result<impl IntoResponse, AppError> {{\n Ok(RouteResponse::ssr_async({document}))\n}}\n"
)
};
let slug = route.module.replace('_', "-");
format!(
r#"{imports}
use crate::{{error::AppError, layouts::RootDocument}};
#[derive(Debug, Clone, Copy)]
pub struct {ty};
impl<L: DataLoader> WebRenderSync<L> for {ty} {{
{page_head} fn render(self, cx: &mut WebContext<L>) -> Result<(), WriteError> {{
html_sync! {{
<main data-page-{slug}>
<h1>{title}</h1>
</main>
}}
.render(cx)
}}
}}
{markdown_impl}
"#,
imports = imports,
ty = route.rust_type,
title = title,
slug = slug,
markdown_impl = markdown_impl
)
}
fn endpoint_source(response: &str) -> String {
match response {
"json" => "use axum::Json;\nuse serde::Serialize;\n\n#[derive(Serialize)]\npub struct Response { pub ok: bool }\n\npub async fn handler() -> Json<Response> { Json(Response { ok: true }) }\n".to_string(),
"redirect" => "use axum::response::Redirect;\n\npub async fn handler() -> Redirect { Redirect::to(\"/\") }\n".to_string(),
"empty" => "use axum::http::StatusCode;\n\npub async fn handler() -> StatusCode { StatusCode::NO_CONTENT }\n".to_string(),
"html" => "use axum::response::Html;\n\npub async fn handler() -> Html<&'static str> { Html(\"<section data-endpoint-fragment></section>\") }\n".to_string(),
_ => unreachable!("clap validates endpoint response values"),
}
}
#[derive(Debug)]
struct ModelField {
name: String,
rust_type: &'static str,
sql_type: &'static str,
optional: bool,
unique: bool,
default: Option<String>,
reference: Option<String>,
}
fn parse_model_field(raw: &str) -> Result<ModelField> {
let mut parts = raw.split(':');
let name = snake_name(parts.next().unwrap_or_default())?;
let kind = parts
.next()
.context("model fields use name:type[:modifier...]")?;
let (rust_type, sql_type) = match kind {
"text" | "string" => ("String", "TEXT"),
"integer" | "bigint" => ("i64", "INTEGER"),
"real" => ("f64", "REAL"),
"boolean" => ("bool", "INTEGER"),
"blob" => ("Vec<u8>", "BLOB"),
"datetime" => ("String", "TEXT"),
"uuid" => ("String", "TEXT"),
other => bail!("unsupported model field type `{other}`"),
};
let mut field = ModelField {
name,
rust_type,
sql_type,
optional: false,
unique: false,
default: None,
reference: None,
};
for modifier in parts {
if modifier == "optional" {
field.optional = true;
} else if modifier == "unique" {
field.unique = true;
} else if modifier == "index" {
} else if let Some(value) = modifier.strip_prefix("default=") {
field.default = Some(value.to_string());
} else if let Some(value) = modifier.strip_prefix("references=") {
field.reference = Some(snake_name(value)?);
} else {
bail!("unsupported field modifier `{modifier}`");
}
}
Ok(field)
}
fn model_source(struct_name: &str, fields: &[ModelField]) -> String {
let fields = fields
.iter()
.map(|field| {
format!(
" pub {}: {}{},",
field.name,
if field.optional { "Option<" } else { "" },
if field.optional {
format!("{}>", field.rust_type)
} else {
field.rust_type.to_string()
}
)
})
.collect::<Vec<_>>()
.join("\n");
format!("#[derive(Debug, Clone, sqlx::FromRow)]\npub struct {struct_name} {{\n pub id: i64,\n{fields}\n pub created_at: String,\n pub updated_at: String,\n}}\n")
}
fn model_up_sql(table: &str, fields: &[ModelField]) -> String {
let mut columns = vec![" id INTEGER PRIMARY KEY".to_string()];
for field in fields {
let mut column = format!(" {} {}", field.name, field.sql_type);
if !field.optional {
column.push_str(" NOT NULL");
}
if field.unique {
column.push_str(" UNIQUE");
}
if let Some(default) = &field.default {
column.push_str(" DEFAULT ");
column.push_str(default);
}
if let Some(reference) = &field.reference {
column.push_str(" REFERENCES ");
column.push_str(reference);
column.push_str("s(id)");
}
columns.push(column);
}
columns.push(" created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP".to_string());
columns.push(" updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP".to_string());
format!("CREATE TABLE {table} (\n{}\n);\n", columns.join(",\n"))
}
fn finish_generated(
root: &Path,
operation_id: &'static str,
files: Vec<(PathBuf, String)>,
dry_run: bool,
json: bool,
) -> Result<()> {
let report = GenerateReport {
operation_id,
command_version: 1,
project_root: root.to_path_buf(),
planned_filesystem_operations: files
.iter()
.map(|(path, source)| GenerateOperation {
operation: if root.join(path).exists() {
"update"
} else {
"create"
},
path: path.clone(),
bytes: source.len(),
})
.collect(),
configuration_changes: Vec::new(),
warnings: Vec::new(),
result: if dry_run { "planned" } else { "created" },
};
if !dry_run {
commit_mutations(root, &files)?;
}
print_report(&report, json)
}
fn commit_mutations(root: &Path, files: &[(PathBuf, String)]) -> Result<()> {
let mut staged = Vec::with_capacity(files.len());
for (relative, source) in files {
let target = root.join(relative);
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
let name = target
.file_name()
.and_then(|value| value.to_str())
.context("generated filename must be UTF-8")?;
let temporary = target.with_file_name(format!(".{name}.proa-{}.tmp", std::process::id()));
fs::write(&temporary, source)?;
staged.push((temporary, target));
}
for (temporary, target) in staged {
fs::rename(temporary, target)?;
}
Ok(())
}
fn require_sqlite(root: &Path) -> Result<()> {
let project = config::load_project_config(root)?;
if project.database.as_ref().map(|database| database.driver)
!= Some(crate::config::DatabaseDriver::Sqlite)
{
bail!("No database capability is configured.\nAdd one with: proa add database sqlite");
}
Ok(())
}
fn snake_name(raw: &str) -> Result<String> {
let mut name = String::with_capacity(raw.len());
let mut previous_separator = false;
for character in raw.trim().chars() {
if character.is_ascii_alphanumeric() {
if character.is_ascii_uppercase() && !name.is_empty() && !previous_separator {
name.push('_');
}
name.push(character.to_ascii_lowercase());
previous_separator = false;
} else if !name.is_empty() && !previous_separator {
name.push('_');
previous_separator = true;
}
}
while name.ends_with('_') {
name.pop();
}
if name.is_empty() {
bail!("migration name must contain a letter or number");
}
Ok(name)
}
fn next_migration_version(directory: &Path) -> Result<u32> {
let mut maximum = 0;
for entry in fs::read_dir(directory)? {
let name = entry?.file_name();
let name = name.to_string_lossy();
let prefix: String = name.chars().take_while(char::is_ascii_digit).collect();
if !prefix.is_empty() {
maximum = maximum.max(prefix.parse::<u32>().unwrap_or(0));
}
}
maximum.checked_add(1).context("migration version overflow")
}
fn up_sql(name: &str) -> String {
format!(
"-- {name}\n-- Write the forward schema change here.\n\n-- Example:\n-- CREATE TABLE {name} (id INTEGER PRIMARY KEY);\n"
)
}
fn down_sql(name: &str) -> String {
format!(
"-- Revert {name}\n-- Write the exact inverse operation here; Proa does not guess destructive SQL.\n"
)
}
fn simple_sql(name: &str) -> String {
format!("-- {name}\n-- Irreversible migration.\n")
}
fn commit_new_files(files: &[(PathBuf, String)]) -> Result<()> {
let mut staged = Vec::with_capacity(files.len());
for (path, source) in files {
let file_name = path
.file_name()
.and_then(|value| value.to_str())
.context("generated path must have a UTF-8 filename")?;
let temporary =
path.with_file_name(format!(".{file_name}.proa-{}.tmp", std::process::id()));
let mut handle = OpenOptions::new()
.create_new(true)
.write(true)
.open(&temporary)
.with_context(|| format!("stage {}", path.display()))?;
handle.write_all(source.as_bytes())?;
handle.sync_all()?;
staged.push((temporary, path));
}
for (temporary, path) in &staged {
fs::rename(temporary, path).with_context(|| format!("commit {}", path.display()))?;
}
Ok(())
}
fn print_report(report: &GenerateReport, json: bool) -> Result<()> {
if json {
println!("{}", serde_json::to_string_pretty(report)?);
} else {
println!(
"{}",
if report.result == "planned" {
"Plan"
} else {
"Created"
}
);
for operation in &report.planned_filesystem_operations {
println!(" {:<8} {}", operation.operation, operation.path.display());
}
}
Ok(())
}
fn open_files<'a>(files: impl IntoIterator<Item = &'a PathBuf>) -> Result<()> {
let editor = std::env::var_os("VISUAL").or_else(|| std::env::var_os("EDITOR"));
let Some(editor) = editor else {
bail!("--open requires VISUAL or EDITOR");
};
let status = Command::new(editor).args(files).status()?;
if !status.success() {
bail!("editor exited with {status}");
}
Ok(())
}
struct DirectoryLock {
path: PathBuf,
}
impl DirectoryLock {
fn acquire(directory: &Path) -> Result<Self> {
let path = directory.join(".proa-generate.lock");
OpenOptions::new()
.create_new(true)
.write(true)
.open(&path)
.with_context(|| format!("migration directory is locked: {}", directory.display()))?;
Ok(Self { path })
}
}
impl Drop for DirectoryLock {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_migration_names() {
assert_eq!(snake_name("CreatePosts").unwrap(), "create_posts");
assert_eq!(snake_name("add posts-slug").unwrap(), "add_posts_slug");
}
#[test]
fn generates_axum_capture_syntax_for_both_route_spellings() {
for input in ["blog/:slug", "blog/{slug}"] {
let route = route_name(input).unwrap();
assert_eq!(route.canonical, "/blog/{slug}");
assert_eq!(route.markdown_alias, "/blog/{slug}.md");
assert_eq!(route.module, "blog_slug");
let source = page_source(&route, true, true);
syn::parse_file(&source).unwrap();
assert!(source.contains("fn handler_with_markdown_alias("));
}
for input in ["files/*rest", "files/{*rest}"] {
let route = route_name(input).unwrap();
assert_eq!(route.canonical, "/files/{*rest}");
assert_eq!(route.module, "files_rest");
}
}
#[test]
fn route_paths_outside_url_syntax_are_rejected_before_reaching_rust() {
for input in ["a\"b", "x\\y", "q#\"##", "sp ace", "caf\u{e9}", "a`b"] {
let error = route_name(input).unwrap_err().to_string();
assert!(error.contains("URL path characters"), "{input}: {error}");
}
let route = route_name("it's/a+b=c@d").unwrap();
for (markdown, managed_head) in [(false, true), (true, true), (true, false)] {
syn::parse_file(&page_source(&route, markdown, managed_head)).unwrap();
}
}
#[test]
fn generated_page_source_is_formatted_and_uses_human_titles() {
let route = route_name("user-settings").unwrap();
assert_eq!(route.rust_type, "UserSettingsPage");
assert_eq!(route.title, "User Settings");
for (markdown, managed_head) in [(false, true), (true, true), (false, false), (true, false)]
{
let source = page_source(&route, markdown, managed_head);
syn::parse_file(&source).unwrap();
assert!(source.contains("<h1>\"User Settings\"</h1>"), "{source}");
assert_eq!(
source.contains("cx.head_mut().title(\"User Settings\")"),
managed_head,
"{source}"
);
assert_eq!(
source.contains("ComponentRole::PAGE"),
managed_head,
"{source}"
);
assert_eq!(
source.contains("title: \"User Settings\","),
!managed_head,
"{source}"
);
assert!(!source.contains("with_head"), "{source}");
let formatted = proa_source_tools::fmt::format_file(
Path::new("src/pages/user_settings.rs"),
&source,
)
.unwrap();
assert!(
formatted.diagnostics.is_empty(),
"{:?}",
formatted.diagnostics
);
assert_eq!(
formatted.output, source,
"generated page must pass proa fmt"
);
}
}
}