Skip to main content

specfold_core/model/
registry.rs

1//! The type registry: the built-in preset with a project's overrides applied.
2
3use super::doctype::{self, FieldKind, Form, KeyKind, TypeDef};
4use serde::{Deserialize, Serialize};
5use std::collections::BTreeMap;
6
7/// `fields` in a type table: a list of keys (replacing the built-in list), or a table of keys
8/// and value kinds (`{ approvers = "people" }`), which adds the keys and gives rule S8 their kinds.
9#[derive(Debug, Clone, Deserialize, Serialize)]
10#[serde(untagged)]
11pub enum FieldsDecl {
12    List(Vec<String>),
13    Kinds(BTreeMap<String, FieldKind>),
14}
15
16/// Overrides for one type from spec.toml.
17#[derive(Debug, Clone, Default, Deserialize, Serialize)]
18#[serde(deny_unknown_fields)]
19pub struct TypeOverride {
20    pub enabled: Option<bool>,
21    pub about: Option<String>,
22    pub key: Option<KeyKind>,
23    pub form: Option<Form>,
24    pub statuses: Option<Vec<String>>,
25    pub initial: Option<String>,
26    pub sealed: Option<bool>,
27    pub fields: Option<FieldsDecl>,
28    pub template: Option<String>,
29    pub transitions: Option<BTreeMap<String, Vec<String>>>,
30    pub require_when: Option<BTreeMap<String, Vec<String>>>,
31    pub sections: Option<Vec<String>>,
32    pub placeholders: Option<Vec<String>>,
33    pub distinct: Option<Vec<Vec<String>>>,
34    pub dir: Option<String>,
35    pub current: Option<Vec<String>>,
36    pub ignore: Option<Vec<String>>,
37}
38
39#[derive(Debug, Clone)]
40pub struct Registry {
41    pub types: Vec<TypeDef>,
42}
43
44fn apply(t: &mut TypeDef, o: &TypeOverride) {
45    if let Some(v) = &o.about {
46        t.about = v.clone();
47    }
48    if let Some(v) = o.key {
49        t.key = v;
50    }
51    if let Some(v) = o.form {
52        t.form = v;
53    }
54    if let Some(v) = &o.statuses {
55        t.statuses = v.clone();
56    }
57    if let Some(v) = &o.initial {
58        t.initial = v.clone();
59    }
60    if let Some(v) = o.sealed {
61        t.sealed = v;
62    }
63    match &o.fields {
64        Some(FieldsDecl::List(v)) => t.fields = v.clone(),
65        Some(FieldsDecl::Kinds(m)) => {
66            for k in m.keys() {
67                if !t.fields.contains(k) && !k.starts_with("rel.") {
68                    t.fields.push(k.clone());
69                }
70            }
71            t.kinds = m.clone();
72        }
73        None => {}
74    }
75    if let Some(v) = &o.placeholders {
76        t.placeholders = v.clone();
77    }
78    if let Some(v) = &o.distinct {
79        t.distinct = v.clone();
80    }
81    if let Some(v) = &o.template {
82        t.template = v.clone();
83    }
84    if let Some(v) = &o.transitions {
85        t.transitions = v.clone();
86    }
87    if let Some(v) = &o.require_when {
88        t.require_when = v.clone();
89    }
90    if let Some(v) = &o.sections {
91        t.sections = v.clone();
92    }
93    if let Some(v) = &o.dir {
94        t.dir = Some(v.clone());
95    }
96    if let Some(v) = &o.current {
97        t.current = v.clone();
98    }
99    if let Some(v) = &o.ignore {
100        t.ignore = v.clone();
101    }
102}
103
104/// `[types.<name>]` tables that look like typos: a name that is not built in, close to one that
105/// is, and without an `about` (which a deliberate new type would have); or a table disabling a
106/// type that does not exist.
107pub fn suspect_overrides(overrides: &BTreeMap<String, TypeOverride>) -> Vec<String> {
108    let builtin: Vec<String> = doctype::builtin().into_iter().map(|t| t.name).collect();
109    let mut out = vec![];
110    for (name, o) in overrides {
111        if builtin.contains(name) {
112            continue;
113        }
114        let near = crate::suggest::nearest(name, builtin.iter().map(String::as_str))
115            .or_else(|| builtin.iter().map(String::as_str).find(|b| name.strip_suffix('s') == Some(*b)));
116        if o.enabled == Some(false) {
117            let hint = near.map(|n| format!("; did you mean [types.{n}]?")).unwrap_or_default();
118            out.push(format!("[types.{name}] disables a type that does not exist{hint}"));
119        } else if let Some(n) = near
120            && o.about.is_none()
121        {
122            out.push(format!(
123                "[types.{name}] is not a built-in type, so it creates a new one; did you mean [types.{n}]? (give it an `about` to keep it as a new type)"
124            ));
125        }
126    }
127    // C110: a status `require_when` names that the type does not have never applies.
128    for t in Registry::new(overrides).types {
129        for s in t.require_when.keys().filter(|s| !t.statuses.contains(s)) {
130            out.push(format!(
131                "[types.{}] require_when names status '{s}', which {} documents never have, so it never applies; statuses: {}",
132                t.name,
133                t.name,
134                t.statuses.join(", ")
135            ));
136        }
137        for s in t.current.iter().filter(|s| !t.statuses.contains(s)) {
138            out.push(format!(
139                "[types.{}] current names status '{s}', which {} documents never have; statuses: {}",
140                t.name,
141                t.name,
142                t.statuses.join(", ")
143            ));
144        }
145    }
146    out
147}
148
149/// `[audit] coverage_types` names that are no enabled type: coverage never looks at them.
150pub fn suspect_coverage(overrides: &BTreeMap<String, TypeOverride>, coverage: &[String]) -> Vec<String> {
151    let r = Registry::new(overrides);
152    let names: Vec<&str> = r.types.iter().map(|t| t.name.as_str()).collect();
153    coverage
154        .iter()
155        .filter(|c| !names.contains(&c.as_str()))
156        .map(|c| {
157            let near = crate::suggest::nearest(c, names.iter().copied())
158                .map(|n| format!("; did you mean '{n}'?"))
159                .unwrap_or_default();
160            format!(
161                "[audit] coverage_types names type '{c}', which does not exist, so it is never checked{near} (types: {})",
162                names.join(", ")
163            )
164        })
165        .collect()
166}
167
168impl Registry {
169    pub fn new(overrides: &BTreeMap<String, TypeOverride>) -> Self {
170        let mut types = doctype::builtin();
171        for (name, o) in overrides {
172            let pos = types.iter().position(|t| &t.name == name);
173            if o.enabled == Some(false) {
174                if let Some(p) = pos {
175                    types.remove(p);
176                }
177                continue;
178            }
179            match pos {
180                Some(p) => apply(&mut types[p], o),
181                None => {
182                    let mut t = doctype::custom(name);
183                    apply(&mut t, o);
184                    types.push(t);
185                }
186            }
187        }
188        Registry { types }
189    }
190
191    pub fn get(&self, name: &str) -> Option<&TypeDef> {
192        self.types.iter().find(|t| t.name == name)
193    }
194
195    /// Whether a `ty` document in `status` is shown without `--all` ([`TypeDef::is_current`]).
196    pub fn is_current(&self, ty: &str, status: &str) -> bool {
197        match self.get(ty) {
198            Some(t) => t.is_current(status),
199            None => super::lifecycle::is_current(status),
200        }
201    }
202
203    /// The type a hint to write a governing document names: sot, else adr, else the first type
204    /// the project added; None when the project disabled all of them.
205    pub fn rule_type(&self) -> Option<&str> {
206        let builtin: Vec<String> = doctype::builtin().into_iter().map(|t| t.name).collect();
207        ["sot", "adr"]
208            .into_iter()
209            .find(|n| self.get(n).is_some())
210            .or_else(|| self.types.iter().map(|t| t.name.as_str()).find(|n| !builtin.iter().any(|b| b == n)))
211    }
212
213    pub fn names(&self) -> Vec<&str> {
214        self.types.iter().map(|t| t.name.as_str()).collect()
215    }
216}
217
218#[cfg(test)]
219mod suspect_tests {
220    use super::{TypeOverride, suspect_overrides};
221    use std::collections::BTreeMap;
222
223    #[test]
224    fn near_misses_are_named_and_deliberate_types_are_not() {
225        let mut m = BTreeMap::new();
226        m.insert("adrs".to_string(), TypeOverride { sections: Some(vec!["Decision".into()]), ..Default::default() });
227        m.insert("memo".to_string(), TypeOverride { about: Some("Short notes".into()), ..Default::default() });
228        m.insert("rfc".to_string(), TypeOverride::default());
229        let got = suspect_overrides(&m);
230        assert_eq!(got.len(), 1, "{got:?}");
231        assert!(got[0].contains("did you mean [types.adr]"), "{got:?}");
232        let mut m = BTreeMap::new();
233        let when = BTreeMap::from([("accepted".to_string(), vec!["approvers".to_string()])]);
234        m.insert("adr".to_string(), TypeOverride { require_when: Some(when), ..Default::default() });
235        let got = suspect_overrides(&m);
236        assert!(got.len() == 1 && got[0].contains("status 'accepted'") && got[0].contains("active"), "C110: {got:?}");
237    }
238}