1use std::collections::BTreeMap;
6
7use serde::Serialize;
8
9use super::{FormatRegistry, IdTemplate, Shape};
10use crate::{Severity, Spanned};
11
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub enum Scope {
15 Document,
17 Host(String),
19}
20
21impl Scope {
22 pub fn parse(s: Option<&str>) -> Scope {
24 match s {
25 None | Some("document") => Scope::Document,
26 Some(host) => Scope::Host(host.to_string()),
27 }
28 }
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
33pub struct Only(pub BTreeMap<String, Vec<String>>);
34
35impl Only {
36 pub fn admits(&self, states: &States) -> bool {
39 self.0.iter().all(|(dim, admitted)| {
40 states
41 .0
42 .get(dim)
43 .is_some_and(|have| have.iter().any(|s| admitted.contains(s)))
44 })
45 }
46
47 pub fn overlaps(&self, other: &Only) -> bool {
50 self.0.iter().all(|(dim, admitted)| {
51 other
52 .0
53 .get(dim)
54 .is_none_or(|theirs| theirs.iter().any(|s| admitted.contains(s)))
55 })
56 }
57
58 pub fn is_gated(&self) -> bool {
60 !self.0.is_empty()
61 }
62
63 pub fn render(&self) -> String {
65 self.0
66 .iter()
67 .map(|(k, v)| format!("{k}={}", v.join(",")))
68 .collect::<Vec<_>>()
69 .join(" ")
70 }
71}
72
73#[derive(Debug, Clone, Default)]
82pub struct Condition(pub Vec<Only>);
83
84impl PartialEq for Condition {
85 fn eq(&self, other: &Self) -> bool {
86 self.0 == other.0 || self.normal() == other.normal()
87 }
88}
89
90impl Eq for Condition {}
91
92impl Condition {
93 pub fn new(maps: impl IntoIterator<Item = Only>) -> Self {
98 let maps: Vec<Only> = maps.into_iter().collect();
99 if maps.iter().any(|only| only.0.is_empty()) {
100 return Condition::default();
101 }
102 let mut keyed: Vec<(Vec<Only>, Only)> = maps
105 .into_iter()
106 .map(|only| (Condition(vec![only.clone()]).normal(), only))
107 .collect();
108 keyed.sort_by(|a, b| a.0.cmp(&b.0));
109 keyed.dedup_by(|a, b| a.0 == b.0);
110 Condition(keyed.into_iter().map(|(_, only)| only).collect())
111 }
112
113 fn normal(&self) -> Vec<Only> {
116 let mut maps: Vec<Only> = self
117 .0
118 .iter()
119 .map(|only| {
120 Only(
121 only.0
122 .iter()
123 .map(|(dim, states)| {
124 let mut states = states.clone();
125 states.sort();
126 states.dedup();
127 (dim.clone(), states)
128 })
129 .collect(),
130 )
131 })
132 .collect();
133 maps.sort();
134 maps.dedup();
135 maps
136 }
137
138 pub fn admits_known(&self, states: &States, lifecycle: &[LifecycleDimension]) -> bool {
148 self.0.is_empty()
149 || self.0.iter().any(|only| {
150 only.0.iter().all(|(dim, admitted)| {
151 let Some(declared) = lifecycle.iter().find(|d| &d.key == dim) else {
152 return false;
153 };
154 let mut known = states
155 .0
156 .get(dim)
157 .into_iter()
158 .flatten()
159 .filter(|s| declared.states.contains(s))
160 .peekable();
161 known.peek().is_none() || known.all(|s| admitted.contains(s))
162 })
163 })
164 }
165
166 pub fn admits(&self, states: &States) -> bool {
170 self.0.is_empty() || self.0.iter().any(|only| only.admits(states))
171 }
172
173 pub fn overlaps(&self, other: &Condition) -> bool {
176 self.0.is_empty()
177 || other.0.is_empty()
178 || self.0.iter().any(|a| other.0.iter().any(|b| a.overlaps(b)))
179 }
180
181 pub fn is_gated(&self) -> bool {
183 !self.0.is_empty()
184 }
185
186 pub fn render(&self) -> String {
189 self.0
190 .iter()
191 .map(Only::render)
192 .collect::<Vec<_>>()
193 .join(" | ")
194 }
195}
196
197impl From<Only> for Condition {
198 fn from(only: Only) -> Self {
200 Condition::new([only])
201 }
202}
203
204#[derive(Debug, Clone, Default, PartialEq, Eq)]
207pub struct States(pub BTreeMap<String, Vec<String>>);
208
209#[derive(Debug, Clone, Default, PartialEq, Eq)]
211pub struct RuleCommon {
212 pub severity: Severity,
214 pub only: Condition,
216 pub line: usize,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
224pub enum Text {
225 Literal(String),
227 From(String),
229}
230
231#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct KeyDerivation {
234 pub source: DerivationSource,
236 pub separator: String,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
242pub enum DerivationSource {
243 Rule(String),
245 From(String),
247}
248
249impl KeyDerivation {
250 pub fn source_label(&self) -> String {
252 match &self.source {
253 DerivationSource::Rule(r) => format!("set `{r}`"),
254 DerivationSource::From(k) => format!("the frontmatter `{k}`"),
255 }
256 }
257
258 pub fn prefix_of<'a>(
263 &self,
264 key: &str,
265 prefixes: impl IntoIterator<Item = &'a str>,
266 ) -> Option<&'a str> {
267 prefixes
268 .into_iter()
269 .filter(|p| {
270 key.strip_prefix(p)
271 .is_some_and(|rest| rest.starts_with(&self.separator))
272 })
273 .max_by_key(|p| p.len())
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum FmFormat {
280 Url,
282 Slug,
284 Host(String),
286}
287
288impl FmFormat {
289 pub fn name(&self) -> &str {
291 match self {
292 FmFormat::Url => "url",
293 FmFormat::Slug => "slug",
294 FmFormat::Host(name) => name,
295 }
296 }
297}
298
299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
303#[serde(rename_all = "kebab-case")]
304pub enum LimitKind {
305 Soft,
307 Hard,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
315pub struct Limit {
316 pub kind: LimitKind,
318 pub count: usize,
320 pub when_at_limit: String,
323}
324
325impl Limit {
326 pub fn hard(&self) -> Option<usize> {
331 (self.kind == LimitKind::Hard).then_some(self.count)
332 }
333}
334#[derive(Debug, Clone)]
338pub struct FrontmatterConstraint {
339 pub common: RuleCommon,
341 pub const_: Option<String>,
343 pub shape: Option<Shape>,
345 pub enum_: Option<Vec<String>>,
347 pub format: Option<FmFormat>,
349 pub id_template: Option<IdTemplate>,
351 pub list: bool,
353 pub min: Option<usize>,
355 pub max: Option<Limit>,
357 pub optional: bool,
359 pub example: Option<String>,
361 pub guidance: Option<String>,
363}
364
365impl FrontmatterConstraint {
366 pub fn fixed_value(&self, states: &States) -> Option<String> {
370 if let Some(v) = &self.const_ {
371 return Some(v.clone());
372 }
373 if let Some(t) = &self.id_template
374 && let Ok(v) = t.render_with(1, t.has_slug().then_some("example"), states)
375 {
376 return Some(v);
377 }
378 self.example.clone()
379 }
380
381 pub fn scaffold_value(&self, states: &States) -> Option<String> {
385 self.fixed_value(states)
386 .or_else(|| self.enum_.as_ref()?.first().cloned())
387 }
388}
389
390#[derive(Debug, Clone, PartialEq)]
392pub struct LifecycleDimension {
393 pub key: String,
395 pub states: Vec<String>,
397 pub guidance: Option<String>,
399 pub line: usize,
401 pub extensions: BTreeMap<String, Spanned>,
404}
405
406impl LifecycleDimension {
407 pub fn state_in<'a>(&'a self, states: &'a States) -> Option<&'a String> {
410 states
411 .0
412 .get(&self.key)
413 .and_then(|s| s.first())
414 .or_else(|| self.states.first())
415 }
416}
417
418#[derive(Debug, Clone)]
420pub struct Example {
421 pub document: String,
423 pub line: usize,
425}
426
427#[derive(Debug, Clone)]
431pub struct CoreSchema {
432 pub line_limit: i64,
434 pub lifecycle: Vec<LifecycleDimension>,
436 pub frontmatter: Vec<(String, FrontmatterConstraint)>,
438 pub frontmatter_open: bool,
440 pub prohibited_patterns: Vec<super::Prohibition>,
442 pub formats: FormatRegistry,
444 pub guidance: Option<String>,
446 pub language: Option<String>,
448 pub examples: Vec<Example>,
450 pub line: usize,
452 pub key_lines: BTreeMap<String, usize>,
454}
455impl CoreSchema {
458 pub fn demand_nothing() -> CoreSchema {
460 CoreSchema {
461 line_limit: 0,
462 lifecycle: vec![],
463 frontmatter: vec![],
464 frontmatter_open: true,
465 prohibited_patterns: vec![],
466 formats: FormatRegistry::default(),
467 guidance: None,
468 language: None,
469 examples: vec![],
470 line: 0,
471 key_lines: BTreeMap::new(),
472 }
473 }
474
475 pub fn states(&self, frontmatter: Option<&Spanned>) -> States {
478 let mut states = States::default();
479 for dim in &self.lifecycle {
480 if let Some(value) = frontmatter
481 .and_then(|f| f.get(&dim.key))
482 .and_then(Spanned::scalar_text)
483 {
484 states.0.insert(dim.key.clone(), vec![value]);
485 }
486 }
487 states
488 }
489
490 pub fn type_const(&self) -> Option<&str> {
492 self.constraint("type")?.const_.as_deref()
493 }
494
495 pub fn constraint(&self, key: &str) -> Option<&FrontmatterConstraint> {
498 self.frontmatter
501 .iter()
502 .find(|(k, _)| k == key)
503 .map(|(_, c)| c)
504 }
505
506 pub fn id_template(&self) -> Option<&IdTemplate> {
508 self.constraint("id")?.id_template.as_ref()
509 }
510
511 pub fn dimension(&self, key: &str) -> Option<&LifecycleDimension> {
513 self.lifecycle.iter().find(|d| d.key == key)
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520
521 #[test]
523 fn a_key_derives_from_the_longest_prefix_that_starts_it() {
524 let kd = KeyDerivation {
525 source: DerivationSource::From("code".into()),
526 separator: "-".into(),
527 };
528 assert_eq!(kd.prefix_of("CE-BUG-1", ["CE", "CE-BUG"]), Some("CE-BUG"));
529 assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BUG", "CE"]), Some("CE-BUG"));
530 assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-BU"]), None);
531 assert_eq!(kd.prefix_of("CE-BUG", ["CE-BUG"]), None);
532 assert_eq!(kd.prefix_of("CE-BUG-1", ["CE-FIX"]), None);
533 }
534
535 fn map(pairs: &[(&str, &str)]) -> Only {
537 Only(
538 pairs
539 .iter()
540 .map(|(k, v)| (k.to_string(), vec![v.to_string()]))
541 .collect(),
542 )
543 }
544
545 #[test]
549 fn a_condition_matches_where_any_of_its_maps_does() {
550 let either = Condition(vec![
551 map(&[("plan", "planned")]),
552 map(&[("state", "closed")]),
553 ]);
554 let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
555 assert!(either.admits(&at(&[("plan", "planned"), ("state", "open")])));
556 assert!(either.admits(&at(&[("plan", "unplanned"), ("state", "closed")])));
557 assert!(!either.admits(&at(&[("plan", "unplanned"), ("state", "open")])));
558 assert!(Condition::default().admits(&at(&[("state", "open")])));
559 assert!(either.overlaps(&Condition(vec![map(&[("state", "closed")])])));
560 assert!(!either.overlaps(&Condition(vec![map(&[
561 ("plan", "unplanned"),
562 ("state", "open")
563 ])])));
564 assert!(either.overlaps(&Condition::default()));
565 assert_eq!(either.render(), "plan=planned | state=closed");
566 assert_eq!(Condition::from(Only::default()), Condition::default());
567 let closed = map(&[("state", "closed")]);
568 let planned = map(&[("plan", "planned")]);
569 assert_eq!(
570 Condition::new([closed.clone(), planned.clone(), closed.clone()]),
571 Condition::new([planned.clone(), closed.clone()])
572 );
573 assert_eq!(
574 Condition::new([planned.clone(), Only::default()]),
575 Condition::default()
576 );
577 let two = |a: &str, b: &str| {
578 Only(BTreeMap::from([(
579 "state".to_string(),
580 vec![a.to_string(), b.to_string()],
581 )]))
582 };
583 assert_eq!(
584 Condition::new([two("open", "closed")]),
585 Condition::new([two("closed", "open")])
586 );
587 assert_eq!(
588 Condition::new([two("open", "closed"), two("closed", "open")]).0,
589 vec![two("open", "closed")]
590 );
591 }
592
593 #[test]
599 fn a_condition_counts_an_unknown_state_as_admitted() {
600 let lifecycle = [LifecycleDimension {
601 key: "plan".into(),
602 states: vec!["unplanned".into(), "planned".into()],
603 guidance: None,
604 line: 0,
605 extensions: BTreeMap::new(),
606 }];
607 let unplanned = Condition::new([map(&[("plan", "unplanned")])]);
608 let at = |pairs: &[(&str, &str)]| States(map(pairs).0);
609 assert!(unplanned.admits_known(&at(&[("plan", "unplanned")]), &lifecycle));
610 assert!(!unplanned.admits_known(&at(&[("plan", "planned")]), &lifecycle));
611 assert!(unplanned.admits_known(&at(&[]), &lifecycle));
612 assert!(unplanned.admits_known(&at(&[("plan", "later")]), &lifecycle));
613 let both = States(BTreeMap::from([(
614 "plan".to_string(),
615 vec!["unplanned".to_string(), "planned".to_string()],
616 )]));
617 assert!(!unplanned.admits_known(&both, &lifecycle));
618 let unknown = Condition::new([map(&[("phase", "closed")])]);
619 assert!(!unknown.admits_known(&at(&[("plan", "planned")]), &lifecycle));
620 assert!(!Condition::from(Only::default()).is_gated());
621 }
622}