use std::collections::BTreeMap;
use serde::Serialize;
use super::{FormatRegistry, IdTemplate, Shape};
use crate::{Severity, Spanned};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scope {
Document,
Host(String),
}
impl Scope {
pub fn parse(s: Option<&str>) -> Scope {
match s {
None | Some("document") => Scope::Document,
Some(host) => Scope::Host(host.to_string()),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Only(pub BTreeMap<String, Vec<String>>);
impl Only {
pub fn admits(&self, states: &States) -> bool {
self.0.iter().all(|(dim, admitted)| {
states
.0
.get(dim)
.is_some_and(|have| have.iter().any(|s| admitted.contains(s)))
})
}
pub fn overlaps(&self, other: &Only) -> bool {
self.0.iter().all(|(dim, admitted)| {
other
.0
.get(dim)
.is_none_or(|theirs| theirs.iter().any(|s| admitted.contains(s)))
})
}
pub fn is_gated(&self) -> bool {
!self.0.is_empty()
}
pub fn render(&self) -> String {
self.0
.iter()
.map(|(k, v)| format!("{k}={}", v.join(",")))
.collect::<Vec<_>>()
.join(" ")
}
}
#[derive(Debug, Clone, Default)]
pub struct Condition(pub Vec<Only>);
impl PartialEq for Condition {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0 || self.normal() == other.normal()
}
}
impl Eq for Condition {}
impl Condition {
pub fn new(maps: impl IntoIterator<Item = Only>) -> Self {
let maps: Vec<Only> = maps.into_iter().collect();
if maps.iter().any(|only| only.0.is_empty()) {
return Condition::default();
}
let mut keyed: Vec<(Vec<Only>, Only)> = maps
.into_iter()
.map(|only| (Condition(vec![only.clone()]).normal(), only))
.collect();
keyed.sort_by(|a, b| a.0.cmp(&b.0));
keyed.dedup_by(|a, b| a.0 == b.0);
Condition(keyed.into_iter().map(|(_, only)| only).collect())
}
fn normal(&self) -> Vec<Only> {
let mut maps: Vec<Only> = self
.0
.iter()
.map(|only| {
Only(
only.0
.iter()
.map(|(dim, states)| {
let mut states = states.clone();
states.sort();
states.dedup();
(dim.clone(), states)
})
.collect(),
)
})
.collect();
maps.sort();
maps.dedup();
maps
}
pub fn admits_known(&self, states: &States, lifecycle: &[LifecycleDimension]) -> bool {
self.0.is_empty()
|| self.0.iter().any(|only| {
only.0.iter().all(|(dim, admitted)| {
let Some(declared) = lifecycle.iter().find(|d| &d.key == dim) else {
return false;
};
let mut known = states
.0
.get(dim)
.into_iter()
.flatten()
.filter(|s| declared.states.contains(s))
.peekable();
known.peek().is_none() || known.all(|s| admitted.contains(s))
})
})
}
pub fn admits(&self, states: &States) -> bool {
self.0.is_empty() || self.0.iter().any(|only| only.admits(states))
}
pub fn overlaps(&self, other: &Condition) -> bool {
self.0.is_empty()
|| other.0.is_empty()
|| self.0.iter().any(|a| other.0.iter().any(|b| a.overlaps(b)))
}
pub fn is_gated(&self) -> bool {
!self.0.is_empty()
}
pub fn render(&self) -> String {
self.0
.iter()
.map(Only::render)
.collect::<Vec<_>>()
.join(" | ")
}
}
impl From<Only> for Condition {
fn from(only: Only) -> Self {
Condition::new([only])
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct States(pub BTreeMap<String, Vec<String>>);
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleCommon {
pub severity: Severity,
pub only: Condition,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Text {
Literal(String),
From(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyDerivation {
pub source: DerivationSource,
pub separator: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DerivationSource {
Rule(String),
From(String),
}
impl KeyDerivation {
pub fn source_label(&self) -> String {
match &self.source {
DerivationSource::Rule(r) => format!("rule `{r}`"),
DerivationSource::From(k) => format!("the frontmatter `{k}`"),
}
}
pub fn prefix_of<'a>(
&self,
key: &str,
prefixes: impl IntoIterator<Item = &'a str>,
) -> Option<&'a str> {
prefixes
.into_iter()
.filter(|p| {
key.strip_prefix(p)
.is_some_and(|rest| rest.starts_with(&self.separator))
})
.max_by_key(|p| p.len())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FmFormat {
Url,
Slug,
Host(String),
}
impl FmFormat {
pub fn name(&self) -> &str {
match self {
FmFormat::Url => "url",
FmFormat::Slug => "slug",
FmFormat::Host(name) => name,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum LimitKind {
Soft,
Hard,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Limit {
pub kind: LimitKind,
pub count: usize,
pub when_at_limit: String,
}
impl Limit {
pub fn hard(&self) -> Option<usize> {
(self.kind == LimitKind::Hard).then_some(self.count)
}
}
#[derive(Debug, Clone)]
pub struct FrontmatterConstraint {
pub common: RuleCommon,
pub const_: Option<String>,
pub shape: Option<Shape>,
pub enum_: Option<Vec<String>>,
pub format: Option<FmFormat>,
pub id_template: Option<IdTemplate>,
pub list: bool,
pub min: Option<usize>,
pub max: Option<Limit>,
pub optional: bool,
pub example: Option<String>,
pub guidance: Option<String>,
}
impl FrontmatterConstraint {
pub fn fixed_value(&self, states: &States) -> Option<String> {
if let Some(v) = &self.const_ {
return Some(v.clone());
}
if let Some(t) = &self.id_template
&& let Ok(v) = t.render_with(1, t.has_slug().then_some("example"), states)
{
return Some(v);
}
self.example.clone()
}
pub fn scaffold_value(&self, states: &States) -> Option<String> {
self.fixed_value(states)
.or_else(|| self.enum_.as_ref()?.first().cloned())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LifecycleDimension {
pub key: String,
pub states: Vec<String>,
pub guidance: Option<String>,
pub line: usize,
pub extensions: BTreeMap<String, Spanned>,
}
impl LifecycleDimension {
pub fn state_in<'a>(&'a self, states: &'a States) -> Option<&'a String> {
states
.0
.get(&self.key)
.and_then(|s| s.first())
.or_else(|| self.states.first())
}
}
#[derive(Debug, Clone)]
pub struct Example {
pub document: String,
pub line: usize,
}
#[derive(Debug, Clone)]
pub struct CoreSchema {
pub line_limit: i64,
pub lifecycle: Vec<LifecycleDimension>,
pub frontmatter: Vec<(String, FrontmatterConstraint)>,
pub frontmatter_open: bool,
pub prohibited_patterns: Vec<super::Prohibition>,
pub formats: FormatRegistry,
pub guidance: Option<String>,
pub language: Option<String>,
pub examples: Vec<Example>,
pub line: usize,
pub key_lines: BTreeMap<String, usize>,
}
impl CoreSchema {
pub fn demand_nothing() -> CoreSchema {
CoreSchema {
line_limit: 0,
lifecycle: vec![],
frontmatter: vec![],
frontmatter_open: true,
prohibited_patterns: vec![],
formats: FormatRegistry::default(),
guidance: None,
language: None,
examples: vec![],
line: 0,
key_lines: BTreeMap::new(),
}
}
pub fn states(&self, frontmatter: Option<&Spanned>) -> States {
let mut states = States::default();
for dim in &self.lifecycle {
if let Some(value) = frontmatter
.and_then(|f| f.get(&dim.key))
.and_then(Spanned::scalar_text)
{
states.0.insert(dim.key.clone(), vec![value]);
}
}
states
}
pub fn type_const(&self) -> Option<&str> {
self.constraint("type")?.const_.as_deref()
}
pub fn constraint(&self, key: &str) -> Option<&FrontmatterConstraint> {
self.frontmatter
.iter()
.find(|(k, _)| k == key)
.map(|(_, c)| c)
}
pub fn id_template(&self) -> Option<&IdTemplate> {
self.constraint("id")?.id_template.as_ref()
}
pub fn dimension(&self, key: &str) -> Option<&LifecycleDimension> {
self.lifecycle.iter().find(|d| d.key == key)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_key_derives_from_the_longest_prefix_that_starts_it() {
let kd = KeyDerivation {
source: DerivationSource::From("code".into()),
separator: "-".into(),
};
assert_eq!(kd.prefix_of("CE-BUG-1", ["CE", "CE-BUG"]), Some("CE-BUG"));
assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BUG", "CE"]), Some("CE-BUG"));
assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BU"]), None);
assert_eq!(kd.prefix_of("CE-BUG", ["CE-BUG"]), None);
assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-FIX"]), None);
}
fn map(pairs: &[(&str, &str)]) -> Only {
Only(
pairs
.iter()
.map(|(k, v)| (k.to_string(), vec![v.to_string()]))
.collect(),
)
}
#[test]
fn a_condition_matches_where_any_of_its_maps_does() {
let either = Condition(vec![
map(&[("plan", "planned")]),
map(&[("state", "closed")]),
]);
let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
assert!(either.admits(&at(&[("plan", "planned"), ("state", "open")])));
assert!(either.admits(&at(&[("plan", "unplanned"), ("state", "closed")])));
assert!(!either.admits(&at(&[("plan", "unplanned"), ("state", "open")])));
assert!(Condition::default().admits(&at(&[("state", "open")])));
assert!(either.overlaps(&Condition(vec![map(&[("state", "closed")])])));
assert!(!either.overlaps(&Condition(vec![map(&[
("plan", "unplanned"),
("state", "open")
])])));
assert!(either.overlaps(&Condition::default()));
assert_eq!(either.render(), "plan=planned | state=closed");
assert_eq!(Condition::from(Only::default()), Condition::default());
let closed = map(&[("state", "closed")]);
let planned = map(&[("plan", "planned")]);
assert_eq!(
Condition::new([closed.clone(), planned.clone(), closed.clone()]),
Condition::new([planned.clone(), closed.clone()])
);
assert_eq!(
Condition::new([planned.clone(), Only::default()]),
Condition::default()
);
let two = |a: &str, b: &str| {
Only(BTreeMap::from([(
"state".to_string(),
vec![a.to_string(), b.to_string()],
)]))
};
assert_eq!(
Condition::new([two("open", "closed")]),
Condition::new([two("closed", "open")])
);
assert_eq!(
Condition::new([two("open", "closed"), two("closed", "open")]).0,
vec![two("open", "closed")]
);
}
#[test]
fn a_condition_counts_an_unknown_state_as_admitted() {
let lifecycle = [LifecycleDimension {
key: "plan".into(),
states: vec!["unplanned".into(), "planned".into()],
guidance: None,
line: 0,
extensions: BTreeMap::new(),
}];
let unplanned = Condition::new([map(&[("plan", "unplanned")])]);
let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
assert!(unplanned.admits_known(&at(&[("plan", "unplanned")]), &lifecycle));
assert!(!unplanned.admits_known(&at(&[("plan", "planned")]), &lifecycle));
assert!(unplanned.admits_known(&at(&[]), &lifecycle));
assert!(unplanned.admits_known(&at(&[("plan", "later")]), &lifecycle));
let both = States(BTreeMap::from([(
"plan".to_string(),
vec!["unplanned".to_string(), "planned".to_string()],
)]));
assert!(!unplanned.admits_known(&both, &lifecycle));
let unknown = Condition::new([map(&[("phase", "closed")])]);
assert!(!unknown.admits_known(&at(&[("plan", "planned")]), &lifecycle));
assert!(!Condition::from(Only::default()).is_gated());
}
}