Skip to main content

ostrya_core/
refpattern.rs

1//! Ref patterns and ref selectors.
2//!
3//! A [`RefPattern`] is a path of parts that a ref name can match. A
4//! [`RefSelector`] is a list of patterns that selects ref names.
5//!
6//! # Grammar
7//!
8//! A pattern is split at `/`. Each part is one of these:
9//!
10//! - A literal. It passes [`is_ref_name_component`], and it matches a part of
11//!   a name that is equal to it.
12//! - `*`. It matches exactly one part of a name.
13//! - `**`. It matches one or more parts of a name.
14//!
15//! `*` and `**` are valid only as a whole part, so `b*c`, `x**`, and `***`
16//! are refused. A pattern is not empty and has no empty part. A pattern has
17//! no `!`: the ref-name rule refuses `!` in a name, so a literal never holds
18//! one. A name matches a pattern when the parts of the pattern, in order,
19//! cover all parts of the name.
20//!
21//! For example, `a/*` matches `a/b` and does not match `a` or `a/b/c`. `a/**`
22//! matches `a/b` and `a/c/d`, and does not match `a`. `a/**/c` matches
23//! `a/b/c` and `a/b/d/c`, and does not match `a/c`.
24//!
25//! # Selectors
26//!
27//! An entry of a selector is a pattern with an optional first character `!`.
28//! The entry with the `!` is a negative pattern, and each other entry is a
29//! positive pattern. A name is selected when both of these conditions are
30//! true:
31//!
32//! - The selector has no positive pattern, or a positive pattern matches the
33//!   name.
34//! - No negative pattern matches the name.
35//!
36//! The order of the entries has no effect. So `["!a/**", "a/b"]` does not
37//! select `a/b`. An empty list is valid and selects each name. An entry
38//! with a second `!`, such as `!!a`, is refused.
39//!
40//! # Cost
41//!
42//! The matcher is a dynamic program over the parts of the pattern and the
43//! parts of the name. It does not recurse and does not backtrack. Its cost
44//! is at most the number of pattern parts times the number of name parts, so
45//! a pattern such as `**/**/**/x` cannot make a match slow. A caller that
46//! takes patterns from the network must cap the number and the length of
47//! the patterns, because the cost of all matches grows with both.
48//!
49//! # Names
50//!
51//! Matching compares parts and does not check that the name is a valid ref
52//! name. A walk of the ref tree can yield a name that the ref-name rule
53//! refuses, and a wildcard selects such a name.
54//!
55//! # Examples
56//!
57//! ```
58//! use ostrya_core::{RefPattern, RefSelector};
59//!
60//! let pattern = RefPattern::parse("apps/*/stable")?;
61//! assert!(pattern.matches("apps/web/stable"));
62//! assert!(!pattern.matches("apps/web/db/stable"));
63//!
64//! let selector = RefSelector::parse(["apps/**", "!apps/web/**"])?;
65//! assert!(selector.matches("apps/db/stable"));
66//! assert!(!selector.matches("apps/web/stable"));
67//! assert!(!selector.matches("os/main"));
68//! # Ok::<(), ostrya_core::Error>(())
69//! ```
70
71use crate::error::{Error, Result};
72use crate::refname::is_ref_name_component;
73
74/// One part of a [`RefPattern`].
75#[derive(Debug, Clone, PartialEq, Eq)]
76enum Part {
77    /// A part that a name part must equal.
78    Literal(String),
79    /// `*`: exactly one name part.
80    One,
81    /// `**`: one or more name parts.
82    Many,
83}
84
85/// One ref pattern, with no `!`.
86///
87/// A pattern is split at `/`. Each part is a literal that passes
88/// [`is_ref_name_component`], `*`, or `**`. `*` matches exactly one part of a
89/// name, and `**` matches one or more parts. `*` and `**` are valid only as a
90/// whole part. The matcher costs at most the number of pattern parts times
91/// the number of name parts, so a caller that takes patterns from the
92/// network must cap the number and the length of the patterns. It does not
93/// check that a name is a valid ref name.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct RefPattern {
96    text: String,
97    parts: Vec<Part>,
98}
99
100impl RefPattern {
101    /// Parses one pattern.
102    ///
103    /// # Errors
104    ///
105    /// - [`Error::InvalidRefPattern`] if the pattern is empty, has an empty
106    ///   part, holds `!`, has a part with `*` that is not `*` or `**`, or has
107    ///   a literal part that fails [`is_ref_name_component`]. The text names
108    ///   the pattern.
109    pub fn parse(pattern: &str) -> Result<RefPattern> {
110        parse_pattern(pattern, pattern)
111    }
112
113    /// Returns the text of the pattern as parsed.
114    pub fn as_str(&self) -> &str {
115        &self.text
116    }
117
118    /// Returns `true` if the pattern matches `name`.
119    ///
120    /// The name is not checked against the ref-name rule.
121    pub fn matches(&self, name: &str) -> bool {
122        let head = match self.parts.split_last() {
123            Some((Part::Many, head)) => head,
124            _ => &self.parts,
125        };
126        if head.contains(&Part::Many) {
127            let name: Vec<&str> = name.split('/').collect();
128            match_parts(&self.parts, &name, &mut 0)
129        } else {
130            match_flat(&self.parts, name)
131        }
132    }
133}
134
135/// Parses `pattern`. `entry` is the text that an error names.
136fn parse_pattern(pattern: &str, entry: &str) -> Result<RefPattern> {
137    let refuse = |why: &str| Error::InvalidRefPattern(format!("{entry:?}: {why}"));
138    if pattern.is_empty() {
139        return Err(refuse("the pattern is empty"));
140    }
141    if pattern.contains('!') {
142        return Err(refuse(
143            "a `!` is valid only as the first character of a selector entry",
144        ));
145    }
146    let mut parts = Vec::new();
147    for part in pattern.split('/') {
148        parts.push(match part {
149            "" => return Err(refuse("the pattern has an empty part")),
150            "*" => Part::One,
151            "**" => Part::Many,
152            _ if part.contains('*') => {
153                return Err(refuse("`*` is valid only as a whole part"));
154            }
155            _ if is_ref_name_component(part) => Part::Literal(part.to_owned()),
156            _ => return Err(refuse("a part is not a valid ref-name component")),
157        });
158    }
159    Ok(RefPattern {
160        text: pattern.to_owned(),
161        parts,
162    })
163}
164
165/// Matches `name` against `parts` and adds one to `steps` for each cell of
166/// the table. Row `i` of the table tells which prefixes of the name the first
167/// `i` parts cover.
168fn match_parts(parts: &[Part], name: &[&str], steps: &mut usize) -> bool {
169    let (m, n) = (parts.len(), name.len());
170    if n < m {
171        return false;
172    }
173    let mut prev = vec![false; n + 1];
174    prev[0] = true;
175    let mut cur = vec![false; n + 1];
176    for part in parts {
177        // No part covers zero name parts.
178        cur[0] = false;
179        for j in 1..=n {
180            *steps += 1;
181            cur[j] = match part {
182                Part::Literal(literal) => prev[j - 1] && name[j - 1] == literal,
183                Part::One => prev[j - 1],
184                Part::Many => prev[j - 1] || cur[j - 1],
185            };
186        }
187        std::mem::swap(&mut prev, &mut cur);
188    }
189    prev[n]
190}
191
192/// Matches `name` against `parts`, which hold no `**` before the last part.
193/// Each other part covers exactly one name part, and a last `**` covers the
194/// one or more name parts that remain. So the match compares the parts in
195/// order and needs no table.
196fn match_flat(parts: &[Part], name: &str) -> bool {
197    let (parts, last_many) = match parts.split_last() {
198        Some((Part::Many, head)) => (head, true),
199        _ => (parts, false),
200    };
201    let mut name = name.split('/');
202    for part in parts {
203        let Some(piece) = name.next() else {
204            return false;
205        };
206        let ok = match part {
207            Part::Literal(literal) => piece == literal,
208            Part::One => true,
209            // The caller passes no `**` before the last part. The part would
210            // need more than one name part.
211            Part::Many => return false,
212        };
213        if !ok {
214            return false;
215        }
216    }
217    // A last `**` needs one or more name parts. Each other pattern needs no
218    // more name parts.
219    name.next().is_some() == last_many
220}
221
222/// A list of positive and negative [`RefPattern`]s.
223///
224/// An entry is a pattern with an optional first `!`, which makes it negative.
225/// A name is selected when the list has no positive pattern or a positive
226/// pattern matches it, and no negative pattern matches it. The order of the
227/// entries has no effect, and an empty list selects each name.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct RefSelector {
230    positive: Vec<RefPattern>,
231    negative: Vec<RefPattern>,
232}
233
234impl RefSelector {
235    /// Parses a list of entries. An entry is a pattern with an optional first
236    /// `!`. The selector keeps the entries in their order, with repeats.
237    ///
238    /// # Errors
239    ///
240    /// - [`Error::InvalidRefPattern`] if an entry is not valid. The text
241    ///   names the entry with its `!`.
242    pub fn parse<'a>(entries: impl IntoIterator<Item = &'a str>) -> Result<RefSelector> {
243        let mut positive = Vec::new();
244        let mut negative = Vec::new();
245        for entry in entries {
246            match entry.strip_prefix('!') {
247                Some(rest) => negative.push(parse_pattern(rest, entry)?),
248                None => positive.push(parse_pattern(entry, entry)?),
249            }
250        }
251        Ok(RefSelector { positive, negative })
252    }
253
254    /// Makes a selector of the positive patterns `positive` and the negative
255    /// patterns `negative`.
256    ///
257    /// The call cannot fail. The selector keeps the patterns in their order,
258    /// with repeats. It is the selector that [`parse`](RefSelector::parse)
259    /// gives for the same entries.
260    pub fn new(positive: Vec<RefPattern>, negative: Vec<RefPattern>) -> RefSelector {
261        RefSelector { positive, negative }
262    }
263
264    /// Returns `true` if the selector selects `name`.
265    ///
266    /// The name is not checked against the ref-name rule.
267    pub fn matches(&self, name: &str) -> bool {
268        (self.positive.is_empty() || self.positive.iter().any(|p| p.matches(name)))
269            && !self.negative.iter().any(|p| p.matches(name))
270    }
271
272    /// Returns the positive patterns in entry order.
273    pub fn positive(&self) -> &[RefPattern] {
274        &self.positive
275    }
276
277    /// Returns the negative patterns in entry order, with the `!` removed.
278    pub fn negative(&self) -> &[RefPattern] {
279        &self.negative
280    }
281}
282
283/// The pattern types move freely across tasks and threads.
284const _: fn() = || {
285    fn assert_send_sync<T: Send + Sync>() {}
286    assert_send_sync::<RefPattern>();
287    assert_send_sync::<RefSelector>();
288};
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    fn pat(p: &str) -> RefPattern {
295        RefPattern::parse(p).unwrap()
296    }
297
298    /// The match with no table agrees with the table on patterns with no
299    /// `**`, and on patterns whose one `**` is the last part.
300    #[test]
301    fn the_flat_match_agrees_with_the_table() {
302        let patterns = [
303            "a", "a/b", "*", "*/*", "a/*", "*/b", "a/*/c", "a/b/c", "**", "a/**", "*/**", "a/b/**",
304            "a/*/**", "*/*/**",
305        ];
306        let names = [
307            "",
308            "/",
309            "a/",
310            "/a",
311            "a//b",
312            "a",
313            "b",
314            "a/b",
315            "a/c",
316            "b/b",
317            "a/b/c",
318            "a/x/c",
319            "a/b/c/d",
320            "x/a/b",
321            "a/b/d",
322            "a/b/c/d/e/f",
323        ];
324        for p in patterns {
325            let pattern = pat(p);
326            let parts: Vec<Part> = pattern.parts.clone();
327            for n in names {
328                let split: Vec<&str> = n.split('/').collect();
329                assert_eq!(
330                    match_flat(&parts, n),
331                    match_parts(&parts, &split, &mut 0),
332                    "{p} {n}"
333                );
334                assert_eq!(pattern.matches(n), match_flat(&parts, n), "{p} {n}");
335            }
336        }
337    }
338
339    /// A last `**` covers one or more name parts, an empty part included.
340    #[test]
341    fn a_last_double_star_needs_one_part() {
342        let cases = [
343            ("**", "", true),
344            ("**", "a", true),
345            ("a/**", "a", false),
346            ("a/**", "a/", true),
347            ("a/**", "a/b/c/d", true),
348            ("a/**", "b/c", false),
349            ("*/**", "a", false),
350            ("*/**", "a/b", true),
351        ];
352        for (p, n, want) in cases {
353            assert_eq!(pat(p).matches(n), want, "{p:?} {n:?}");
354        }
355    }
356
357    #[test]
358    fn examples_match() {
359        let cases: [(&str, &[&str], &[&str]); 6] = [
360            ("a", &["a"], &["a/b"]),
361            ("a/b", &["a/b"], &["a/b/c"]),
362            ("a/*", &["a/b"], &["a/b/c"]),
363            ("a/**", &["a/b", "a/c/d"], &["a"]),
364            ("a/*/c", &["a/b/c"], &["a/b/d/c", "a/c"]),
365            ("a/**/c", &["a/b/c", "a/b/d/c"], &["a/c"]),
366        ];
367        for (p, yes, no) in cases {
368            let p = pat(p);
369            for n in yes {
370                assert!(p.matches(n), "{p:?} should match {n:?}");
371            }
372            for n in no {
373                assert!(!p.matches(n), "{p:?} should not match {n:?}");
374            }
375        }
376    }
377
378    #[test]
379    fn parse_refusals() {
380        let cases = [
381            "", "a//b", "/a", "a/", "b*c", "x**", "***", "*a", "a/*b", "!a", "a!", "!", ".", "..",
382            "a/.", "-a", "a b", "a:b", "a\0b",
383        ];
384        for p in cases {
385            let err = RefPattern::parse(p).unwrap_err();
386            assert!(matches!(err, Error::InvalidRefPattern(_)), "{p:?}: {err:?}");
387        }
388    }
389
390    #[test]
391    fn as_str_returns_text() {
392        assert_eq!(pat("a/*/**").as_str(), "a/*/**");
393    }
394
395    #[test]
396    fn single_star_and_double_star() {
397        let star = pat("*");
398        let many = pat("**");
399        for n in ["a", "main", "x.y"] {
400            assert!(star.matches(n), "{n:?}");
401        }
402        for n in ["a/b", "a/b/c"] {
403            assert!(!star.matches(n), "{n:?}");
404        }
405        for n in ["a", "a/b", "a/b/c/d"] {
406            assert!(many.matches(n), "{n:?}");
407        }
408    }
409
410    #[test]
411    fn double_star_minimums() {
412        let two = pat("**/**");
413        assert!(!two.matches("a"));
414        assert!(two.matches("a/b"));
415        assert!(two.matches("a/b/c"));
416        let lead = pat("**/c");
417        assert!(!lead.matches("c"));
418        assert!(lead.matches("a/c"));
419        assert!(lead.matches("a/b/c"));
420        assert!(!pat("a/**/c").matches("a/c"));
421    }
422
423    #[test]
424    fn names_the_rule_refuses_still_match() {
425        for n in ["a^b", "-x/.y", "a b/c"] {
426            assert!(pat("**").matches(n), "{n:?}");
427        }
428        assert!(pat("*").matches("a^b"));
429        assert!(pat("*/*").matches("-x/.y"));
430    }
431
432    fn sel(entries: &[&str]) -> RefSelector {
433        RefSelector::parse(entries.iter().copied()).unwrap()
434    }
435
436    #[test]
437    fn selector_positive_only() {
438        let s = sel(&["a/*", "b"]);
439        for (n, want) in [("a/x", true), ("b", true), ("c", false), ("a/x/y", false)] {
440            assert_eq!(s.matches(n), want, "{n:?}");
441        }
442    }
443
444    #[test]
445    fn selector_negative_only() {
446        let s = sel(&["!a/**"]);
447        for (n, want) in [("a/x", false), ("b", true), ("b/c", true)] {
448            assert_eq!(s.matches(n), want, "{n:?}");
449        }
450    }
451
452    #[test]
453    fn selector_mixed() {
454        let s = sel(&["a/**", "!a/x/**"]);
455        for (n, want) in [("a/y", true), ("a/x/z", false), ("b", false)] {
456            assert_eq!(s.matches(n), want, "{n:?}");
457        }
458    }
459
460    #[test]
461    fn selector_empty_selects_all() {
462        let s = RefSelector::parse(std::iter::empty()).unwrap();
463        for n in ["a", "a/b", "x^y"] {
464            assert!(s.matches(n), "{n:?}");
465        }
466        assert!(s.positive().is_empty() && s.negative().is_empty());
467    }
468
469    #[test]
470    fn selector_order_has_no_effect() {
471        for entries in [["!a/**", "a/b"], ["a/b", "!a/**"]] {
472            assert!(!sel(&entries).matches("a/b"), "{entries:?}");
473        }
474    }
475
476    #[test]
477    fn selector_repeats_and_order() {
478        let s = sel(&["b", "!x", "a", "b", "!y/*", "!x"]);
479        let pos: Vec<&str> = s.positive().iter().map(RefPattern::as_str).collect();
480        let neg: Vec<&str> = s.negative().iter().map(RefPattern::as_str).collect();
481        assert_eq!(pos, ["b", "a", "b"]);
482        assert_eq!(neg, ["x", "y/*", "x"]);
483        assert!(s.matches("a") && !s.matches("x"));
484    }
485
486    #[test]
487    fn selector_new_equals_parse() {
488        let s = RefSelector::new(
489            vec![pat("b"), pat("a"), pat("b")],
490            vec![pat("x"), pat("y/*"), pat("x")],
491        );
492        assert_eq!(s, sel(&["b", "!x", "a", "b", "!y/*", "!x"]));
493        assert_eq!(
494            RefSelector::new(Vec::new(), Vec::new()),
495            RefSelector::parse(std::iter::empty()).unwrap()
496        );
497    }
498
499    #[test]
500    fn selector_refusals_name_the_entry() {
501        for entry in [
502            "!!a", "!", "!a!", "", "a//b", "!b*c", "a!", "! ", "!\0", "!-a",
503        ] {
504            let err = RefSelector::parse(["ok", entry]).unwrap_err();
505            let Error::InvalidRefPattern(text) = &err else {
506                panic!("{entry:?}: {err:?}");
507            };
508            assert!(text.contains(&format!("{entry:?}")), "{entry:?}: {text}");
509            assert!(
510                err.to_string().starts_with("invalid ref pattern: "),
511                "{err}"
512            );
513        }
514    }
515
516    fn count(p: &str, n: usize) -> (bool, usize, usize) {
517        let pattern = pat(p);
518        let name = vec!["a"; n];
519        let mut steps = 0;
520        let hit = match_parts(&pattern.parts, &name, &mut steps);
521        (hit, steps, pattern.parts.len() * n)
522    }
523
524    #[test]
525    fn cost_is_bounded_by_the_product() {
526        let cases = [
527            ("**/**/**/**/x", false),
528            ("**/a/**/a/**/a/**/b", false),
529            ("*/*/*/*/*/x", false),
530            ("**/**/**/**/a", true),
531            ("**/a/**/a/**/a/**/a", true),
532        ];
533        for (p, want) in cases {
534            for n in [10, 100, 1000] {
535                let (hit, steps, bound) = count(p, n);
536                assert_eq!(hit, want, "{p:?} {n}");
537                assert!(steps <= bound, "{p:?} {n}: {steps} > {bound}");
538                let (_, double, _) = count(p, 2 * n);
539                assert!(double <= 2 * steps + 8, "{p:?} {n}: {steps} -> {double}");
540            }
541        }
542    }
543
544    /// A recursive reference matcher, for the cross-check.
545    fn naive(parts: &[&str], name: &[&str]) -> bool {
546        match parts.split_first() {
547            None => name.is_empty(),
548            Some((&"**", rest)) => (1..=name.len()).any(|k| naive(rest, &name[k..])),
549            Some((&"*", rest)) => !name.is_empty() && naive(rest, &name[1..]),
550            Some((lit, rest)) => name.first() == Some(lit) && naive(rest, &name[1..]),
551        }
552    }
553
554    /// Returns each sequence of 1 to `max` items from `alphabet`.
555    fn sequences<'a>(alphabet: &[&'a str], max: usize) -> Vec<Vec<&'a str>> {
556        let mut all: Vec<Vec<&str>> = Vec::new();
557        let mut layer: Vec<Vec<&str>> = vec![Vec::new()];
558        for _ in 0..max {
559            layer = layer
560                .iter()
561                .flat_map(|s| {
562                    alphabet.iter().map(move |a| {
563                        let mut t = s.clone();
564                        t.push(a);
565                        t
566                    })
567                })
568                .collect();
569            all.extend(layer.iter().cloned());
570        }
571        all
572    }
573
574    #[test]
575    fn agrees_with_the_naive_matcher() {
576        let patterns = sequences(&["a", "b", "*", "**"], 4);
577        let names = sequences(&["a", "b"], 5);
578        for p in &patterns {
579            let text = p.join("/");
580            let pattern = pat(&text);
581            for n in &names {
582                let name = n.join("/");
583                assert_eq!(pattern.matches(&name), naive(p, n), "{text:?} vs {name:?}");
584            }
585        }
586    }
587}