Skip to main content

tramlines_core/grammar/
id_template.rs

1//! Id templates (`TL_58`): the `id` key's template, whose holes are
2//! the ones a new document is filled with, `${:seq}`, `${:slug}` and a
3//! lifecycle key's state, `${<key>}`.
4
5use std::fmt::Write as _;
6
7use regex::Regex;
8
9use super::{SLUG, template};
10use crate::{
11    Problem,
12    grammar::{LifecycleDimension, LineTemplate, Segment, States},
13    text::{self, is_slug},
14};
15
16/// The pieces of an id template.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Token {
19    /// Literal text.
20    Literal(String),
21    /// A `seq` hole: the number, `seq-width` digits.
22    Seq(usize),
23    /// A `slug` hole: one or more slug words.
24    Slug,
25    /// A hole named for a lifecycle key: the document's state of that key.
26    Key {
27        /// The lifecycle key.
28        name: String,
29        /// Its states, each a slug.
30        states: Vec<String>,
31    },
32}
33
34/// An id template a new document can be filled with.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct IdTemplate {
37    /// The template as written.
38    pub source: String,
39    /// The tokens, in order.
40    pub tokens: Vec<Token>,
41}
42
43impl IdTemplate {
44    /// The id template of `template`, its sequence `width` digits wide, a
45    /// hole named with no type standing for the state of the `lifecycle`
46    /// key of its name. Refuses a hole a new document cannot be filled with,
47    /// more than one `seq`, a zero width, a lifecycle key with a state that is
48    /// not a slug, and a template that admits a non-slug.
49    // sokf-implements: TL_58
50    // sokf-implements: TL_102
51    // sokf-implements: TL_114
52    // sokf-implements: TL_122
53    pub fn from_template(
54        template: &LineTemplate,
55        width: usize,
56        lifecycle: &[LifecycleDimension],
57    ) -> Result<Self, Problem> {
58        let source = &template.source;
59        let mut tokens = Vec::new();
60        let mut seqs = 0;
61        for segment in &template.segments {
62            match segment {
63                Segment::Literal(l) => tokens.push(Token::Literal(l.clone())),
64                Segment::Hole { ty, .. } if ty == "seq" => {
65                    seqs += 1;
66                    if seqs > 1 {
67                        return Err(Problem::new(
68                            "TL_114",
69                            format!(
70                                "template {source} has more than one `seq` hole",
71                                source = text::code(source)
72                            ),
73                        ));
74                    }
75                    if width == 0 {
76                        return Err(Problem::new(
77                            "TL_102",
78                            format!(
79                                "template {source}: `seq-width` must be positive",
80                                source = text::code(source)
81                            ),
82                        ));
83                    }
84                    tokens.push(Token::Seq(width));
85                }
86                Segment::Hole { ty, .. } if ty == "slug" => tokens.push(Token::Slug),
87                Segment::Hole {
88                    name: Some(name),
89                    ty,
90                    ..
91                } if ty == "text" => {
92                    let Some(dim) = lifecycle.iter().find(|d| &d.key == name) else {
93                        return Err(Problem::new(
94                            "TL_58",
95                            format!(
96                                "template {source}: the hole `${{{name}}}` names no lifecycle key",
97                                source = text::code(source)
98                            ),
99                        ));
100                    };
101                    if let Some(bad) = dim.states.iter().find(|s| !is_slug(s)) {
102                        return Err(Problem::new(
103                            "TL_122",
104                            format!(
105                                "template {source}: the state `{bad}` of `{name}` is not a slug, so no id can hold it",
106                                source = text::code(source)
107                            ),
108                        ));
109                    }
110                    tokens.push(Token::Key {
111                        name: name.clone(),
112                        states: dim.states.clone(),
113                    });
114                }
115                Segment::Hole { ty, .. } => {
116                    return Err(Problem::new(
117                        "TL_58",
118                        format!(
119                            "template {source}: an id holds only the holes a new document is filled with, `${{:seq}}`, `${{:slug}}` and `${{<lifecycle key>}}`, not {} `{ty}`",
120                            text::article(ty),
121                            source = text::code(source)
122                        ),
123                    ));
124                }
125            }
126        }
127        let sample: String = tokens
128            .iter()
129            .map(|t| match t {
130                Token::Literal(s) => s.as_str(),
131                _ => "x",
132            })
133            .collect();
134        if !is_slug(&sample) {
135            return Err(Problem::new(
136                "TL_122",
137                format!(
138                    "template {source} admits a non-slug: `{sample}` is not a slug",
139                    source = text::code(source)
140                ),
141            ));
142        }
143        Ok(IdTemplate {
144            source: source.clone(),
145            tokens,
146        })
147    }
148
149    /// The id template of a fixed id, the `const` of `id`: one literal, a
150    /// slug.
151    // sokf-implements: TL_122
152    pub fn fixed(id: &str) -> Result<Self, Problem> {
153        if !is_slug(id) {
154            return Err(Problem::new(
155                "TL_122",
156                format!("the id {} is not a slug", text::code(id)),
157            ));
158        }
159        Ok(IdTemplate {
160            source: id.to_string(),
161            tokens: vec![Token::Literal(id.to_string())],
162        })
163    }
164
165    /// Whether the template carries a `seq` hole, and its width.
166    pub fn seq_width(&self) -> Option<usize> {
167        self.tokens.iter().find_map(|t| match t {
168            Token::Seq(n) => Some(*n),
169            _ => None,
170        })
171    }
172
173    /// Whether the template carries a `slug` hole.
174    pub fn has_slug(&self) -> bool {
175        self.tokens.contains(&Token::Slug)
176    }
177
178    /// Whether the template carries a hole for a lifecycle key.
179    pub fn has_keys(&self) -> bool {
180        self.tokens.iter().any(|t| matches!(t, Token::Key { .. }))
181    }
182
183    /// An anchored regex matching the ids the template admits; the `seq`
184    /// hole is the group `seq`, and a lifecycle key's hole the group
185    /// `key_<name>`.
186    pub fn regex(&self) -> String {
187        let mut s = String::from("^");
188        for t in &self.tokens {
189            match t {
190                Token::Literal(l) => s.push_str(&regex::escape(l)),
191                Token::Seq(n) => {
192                    let _ = write!(s, "(?P<seq>[0-9]{{{n}}})");
193                }
194                Token::Slug => s.push_str(SLUG),
195                Token::Key { name, states } => {
196                    let alts: Vec<String> = states.iter().map(|s| regex::escape(s)).collect();
197                    let _ = write!(s, "(?P<key_{name}>{})", alts.join("|"));
198                }
199            }
200        }
201        s.push('$');
202        s
203    }
204
205    fn compiled(&self) -> Regex {
206        template::compiled(&self.regex()).expect("template regex is built from escaped parts")
207    }
208
209    /// Whether `id` matches the template.
210    pub fn matches(&self, id: &str) -> bool {
211        self.compiled().is_match(id)
212    }
213
214    /// The sequence number of `id`, when it matches and the template has a
215    /// sequence.
216    pub fn seq_of(&self, id: &str) -> Option<u64> {
217        let caps = self.compiled().captures(id)?;
218        caps.name("seq")?.as_str().parse().ok()
219    }
220
221    /// The lifecycle keys whose state `id` holds, each with that state, when
222    /// `id` matches the template.
223    pub fn keys_of(&self, id: &str) -> Vec<(String, String)> {
224        let Some(caps) = self.compiled().captures(id) else {
225            return vec![];
226        };
227        self.tokens
228            .iter()
229            .filter_map(|t| match t {
230                Token::Key { name, .. } => caps
231                    .name(&format!("key_{name}"))
232                    .map(|m| (name.clone(), m.as_str().to_string())),
233                _ => None,
234            })
235            .collect()
236    }
237
238    /// Render the id for `seq` and `slug`, each lifecycle key's hole taking
239    /// its first state. Refuses what [`IdTemplate::render_with`] refuses.
240    pub fn render(&self, seq: u64, slug: Option<&str>) -> Result<String, String> {
241        self.render_with(seq, slug, &States::default())
242    }
243
244    /// Render the id for `seq`, `slug` and `states`, a lifecycle key's hole
245    /// taking the state `states` gives it, else its first. Refuses a sequence
246    /// that needs more digits than the width, a missing slug, a slug that is
247    /// not slug words, and a state that is not one of the key's.
248    pub fn render_with(
249        &self,
250        seq: u64,
251        slug: Option<&str>,
252        states: &States,
253    ) -> Result<String, String> {
254        let mut s = String::new();
255        for t in &self.tokens {
256            match t {
257                Token::Literal(l) => s.push_str(l),
258                Token::Seq(n) => {
259                    let digits = format!("{seq:0n$}");
260                    if digits.len() > *n {
261                        return Err(format!("the next number {seq} needs more than {n} digits"));
262                    }
263                    s.push_str(&digits);
264                }
265                Token::Slug => match slug {
266                    Some(slug) if is_slug(slug) => s.push_str(slug),
267                    Some(slug) => return Err(format!("`{slug}` is not slug words")),
268                    None => return Err("the template has a `slug` hole; pass --slug".into()),
269                },
270                Token::Key { name, states: all } => {
271                    let state = states
272                        .0
273                        .get(name)
274                        .and_then(|s| s.first())
275                        .or_else(|| all.first())
276                        .cloned()
277                        .unwrap_or_default();
278                    if !all.contains(&state) {
279                        return Err(format!("`{state}` is not a state of `{name}`"));
280                    }
281                    s.push_str(&state);
282                }
283            }
284        }
285        Ok(s)
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use std::collections::BTreeMap;
292
293    use proptest::prelude::*;
294
295    use super::*;
296    use crate::grammar::TypeRegistry;
297
298    fn parse(src: &str, width: usize) -> Result<IdTemplate, String> {
299        parse_in(src, width, &[])
300    }
301
302    fn parse_in(
303        src: &str,
304        width: usize,
305        lifecycle: &[LifecycleDimension],
306    ) -> Result<IdTemplate, String> {
307        let t = LineTemplate::parse(src, &TypeRegistry::built_ins()).map_err(|e| e.message)?;
308        IdTemplate::from_template(&t, width, lifecycle).map_err(|e| e.message)
309    }
310
311    fn kind(states: &[&str]) -> LifecycleDimension {
312        LifecycleDimension {
313            key: "kind".into(),
314            states: states.iter().map(ToString::to_string).collect(),
315            guidance: None,
316            line: 1,
317            extensions: BTreeMap::default(),
318        }
319    }
320
321    // sokf-tests: TL_58
322    #[test]
323    fn a_lifecycle_key_fills_its_hole() {
324        let kinds = [kind(&["feature", "bug", "chore"])];
325        let t = parse_in("issue-${:seq}-${kind}-${:slug}", 3, &kinds).unwrap();
326        assert!(t.has_keys());
327        assert!(t.matches("issue-004-bug-retry-logic"));
328        assert!(!t.matches("issue-004-task-retry-logic"));
329        assert_eq!(t.seq_of("issue-004-bug-retry-logic"), Some(4));
330        assert_eq!(
331            t.keys_of("issue-004-bug-retry-logic"),
332            vec![("kind".to_string(), "bug".to_string())]
333        );
334        let mut states = States::default();
335        states.0.insert("kind".into(), vec!["chore".into()]);
336        assert_eq!(
337            t.render_with(7, Some("tidy"), &states).unwrap(),
338            "issue-007-chore-tidy"
339        );
340        assert_eq!(t.render(7, Some("tidy")).unwrap(), "issue-007-feature-tidy");
341        states.0.insert("kind".into(), vec!["task".into()]);
342        assert!(t.render_with(7, Some("tidy"), &states).is_err());
343        // A hole of another name, or a key whose states are not slugs, is refused.
344        assert!(parse_in("issue-${:seq}-${state}-${:slug}", 3, &kinds).is_err());
345        assert!(parse_in("issue-${:seq}-${kind}", 3, &[kind(&["Bug"])]).is_err());
346    }
347
348    #[test]
349    fn parses_templates() {
350        let t = parse("issue-${:seq}-${:slug}", 3).unwrap();
351        assert_eq!(
352            t.tokens,
353            vec![
354                Token::Literal("issue-".into()),
355                Token::Seq(3),
356                Token::Literal("-".into()),
357                Token::Slug
358            ]
359        );
360        assert_eq!(t.seq_width(), Some(3));
361        assert!(t.has_slug());
362        assert_eq!(
363            t.regex(),
364            "^issue\\-(?P<seq>[0-9]{3})\\-[a-z0-9]+(?:-[a-z0-9]+)*$"
365        );
366        assert!(t.matches("issue-004-retry-logic"));
367        assert!(!t.matches("issue-4-retry"));
368        assert!(!t.matches("issue-004-Retry"));
369        assert_eq!(t.seq_of("issue-004-retry-logic"), Some(4));
370        assert_eq!(t.seq_of("nope"), None);
371        assert_eq!(
372            t.render(4, Some("retry-logic")).unwrap(),
373            "issue-004-retry-logic"
374        );
375        assert!(t.render(1000, Some("x")).is_err());
376        assert!(t.render(1, None).is_err());
377        assert!(t.render(1, Some("Bad Slug")).is_err());
378        let plain = parse("adr-${:seq}", 4).unwrap();
379        assert!(!plain.has_slug());
380        assert_eq!(plain.render(12, None).unwrap(), "adr-0012");
381        assert_eq!(parse("${:slug}", 3).unwrap().seq_width(), None);
382        // A named hole is still the hole of its type.
383        assert!(parse("x-${n:seq}", 2).unwrap().matches("x-07"));
384    }
385
386    #[test]
387    fn refuses_bad_templates() {
388        for (bad, width) in [
389            ("issue-${:seq}-${:seq}", 3),
390            ("issue-${:seq}", 0),
391            ("issue-${:int}", 3),
392            ("issue-${slug}", 3),
393            ("Issue-${:seq}", 3),
394            ("issue_${:slug}", 3),
395            ("issue--${:slug}", 3),
396            ("-${:slug}", 3),
397        ] {
398            assert!(parse(bad, width).is_err(), "{bad}");
399        }
400    }
401
402    fn arb_template() -> impl Strategy<Value = (String, usize)> {
403        (
404            "[a-z][a-z0-9]{0,4}",
405            1usize..5,
406            any::<bool>(),
407            any::<bool>(),
408        )
409            .prop_map(|(prefix, width, with_slug, with_kind)| {
410                let kind = if with_kind { "-${kind}" } else { "" };
411                let t = if with_slug {
412                    format!("{prefix}-${{:seq}}{kind}-${{:slug}}")
413                } else {
414                    format!("{prefix}-${{:seq}}{kind}")
415                };
416                (t, width)
417            })
418    }
419
420    // sokf-tests: TL_58
421    proptest! {
422        #![proptest_config(ProptestConfig::with_cases(256))]
423
424        #[test]
425        fn render_then_seq_of_round_trips((template, width) in arb_template(), seq in 0u64..10_000, slug in "[a-z0-9]+(-[a-z0-9]+){0,2}", state in prop::sample::select(vec!["feature", "bug", "chore"])) {
426            let t = parse_in(&template, width, &[kind(&["feature", "bug", "chore"])]).unwrap();
427            let mut states = States::default();
428            states.0.insert("kind".into(), vec![state.to_string()]);
429            let rendered = t.render_with(seq, Some(&slug), &states);
430            let fits = seq.to_string().len() <= width;
431            prop_assert_eq!(rendered.is_ok(), fits);
432            if let Ok(id) = rendered {
433                prop_assert!(is_slug(&id), "{id}");
434                prop_assert!(t.matches(&id));
435                prop_assert_eq!(t.seq_of(&id), Some(seq));
436                if t.has_keys() {
437                    prop_assert_eq!(t.keys_of(&id), vec![("kind".to_string(), state.to_string())]);
438                }
439            }
440        }
441    }
442}