use std::path::Path;
use anyhow::{Context, Result};
use serde::Deserialize;
const BUILTINS: &[(&str, &str)] = &[("cnmi-rules", include_str!("../profiles/cnmi-rules.toml"))];
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {
pub name: String,
pub jurisdiction: String,
pub kind: String,
pub citation_template: String,
#[serde(default)]
pub draft: bool,
pub heading_patterns: Vec<String>,
#[serde(default)]
pub history_patterns: Vec<String>,
#[serde(default)]
pub date_formats: Vec<String>,
#[serde(default)]
pub skip_patterns: Vec<String>,
#[serde(default)]
pub expected_gaps: Vec<String>,
}
impl Profile {
pub fn from_toml(src: &str) -> Result<Self> {
let p: Profile = toml::from_str(src).context("invalid profile TOML")?;
p.validate()?;
Ok(p)
}
pub fn from_path(path: &Path) -> Result<Self> {
let src = std::fs::read_to_string(path)
.with_context(|| format!("reading profile {}", path.display()))?;
Self::from_toml(&src)
}
pub fn builtin(name: &str) -> Result<Self> {
let src = BUILTINS
.iter()
.find(|(n, _)| *n == name)
.map(|(_, s)| *s)
.with_context(|| {
format!(
"no built-in profile {name:?} (known: {})",
builtin_names().join(", ")
)
})?;
Self::from_toml(src)
}
fn validate(&self) -> Result<()> {
anyhow::ensure!(
!self.jurisdiction.is_empty(),
"profile: jurisdiction must not be empty"
);
anyhow::ensure!(
self.kind == "rule" || self.kind == "statute",
"profile: kind must be \"rule\" or \"statute\", got {:?}",
self.kind
);
anyhow::ensure!(
self.citation_template.contains("{num}"),
"profile: citation_template must contain {{num}}"
);
anyhow::ensure!(
!self.heading_patterns.is_empty(),
"profile: at least one heading pattern is required"
);
for pat in self
.heading_patterns
.iter()
.chain(&self.history_patterns)
.chain(&self.skip_patterns)
{
regex::Regex::new(pat).with_context(|| format!("invalid profile regex {pat:?}"))?;
}
Ok(())
}
}
pub fn builtin_names() -> Vec<&'static str> {
BUILTINS.iter().map(|(n, _)| *n).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_cnmi_rules_parses() {
let p = Profile::builtin("cnmi-rules").expect("built-in must parse");
assert_eq!(p.jurisdiction, "northern_mariana_islands");
assert_eq!(p.kind, "rule");
assert!(p.citation_template.contains("{num}"));
assert!(p.draft, "template not signed off yet โ must stay draft");
}
#[test]
fn unknown_builtin_errors() {
assert!(Profile::builtin("nope").is_err());
}
#[test]
fn missing_routing_keys_rejected() {
let err = Profile::from_toml(
r#"
name = "x"
citation_template = "X {num}"
heading_patterns = ["^RULE"]
jurisdiction = "guam"
kind = "regulation"
"#,
)
.unwrap_err();
assert!(err.to_string().contains("kind"));
}
#[test]
fn bad_regex_rejected() {
let err = Profile::from_toml(
r#"
name = "x"
jurisdiction = "guam"
kind = "rule"
citation_template = "X {num}"
heading_patterns = ["("]
"#,
)
.unwrap_err();
assert!(err.to_string().contains("invalid profile regex"));
}
}