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        if self.parts.contains(&Part::Many) {
123            let name: Vec<&str> = name.split('/').collect();
124            match_parts(&self.parts, &name, &mut 0)
125        } else {
126            match_flat(&self.parts, name)
127        }
128    }
129}
130
131/// Parses `pattern`. `entry` is the text that an error names.
132fn parse_pattern(pattern: &str, entry: &str) -> Result<RefPattern> {
133    let refuse = |why: &str| Error::InvalidRefPattern(format!("{entry:?}: {why}"));
134    if pattern.is_empty() {
135        return Err(refuse("the pattern is empty"));
136    }
137    if pattern.contains('!') {
138        return Err(refuse(
139            "a `!` is valid only as the first character of a selector entry",
140        ));
141    }
142    let mut parts = Vec::new();
143    for part in pattern.split('/') {
144        parts.push(match part {
145            "" => return Err(refuse("the pattern has an empty part")),
146            "*" => Part::One,
147            "**" => Part::Many,
148            _ if part.contains('*') => {
149                return Err(refuse("`*` is valid only as a whole part"));
150            }
151            _ if is_ref_name_component(part) => Part::Literal(part.to_owned()),
152            _ => return Err(refuse("a part is not a valid ref-name component")),
153        });
154    }
155    Ok(RefPattern {
156        text: pattern.to_owned(),
157        parts,
158    })
159}
160
161/// Matches `name` against `parts` and adds one to `steps` for each cell of
162/// the table. Row `i` of the table tells which prefixes of the name the first
163/// `i` parts cover.
164fn match_parts(parts: &[Part], name: &[&str], steps: &mut usize) -> bool {
165    let (m, n) = (parts.len(), name.len());
166    if n < m {
167        return false;
168    }
169    let mut prev = vec![false; n + 1];
170    prev[0] = true;
171    let mut cur = vec![false; n + 1];
172    for part in parts {
173        // No part covers zero name parts.
174        cur[0] = false;
175        for j in 1..=n {
176            *steps += 1;
177            cur[j] = match part {
178                Part::Literal(literal) => prev[j - 1] && name[j - 1] == literal,
179                Part::One => prev[j - 1],
180                Part::Many => prev[j - 1] || cur[j - 1],
181            };
182        }
183        std::mem::swap(&mut prev, &mut cur);
184    }
185    prev[n]
186}
187
188/// Matches `name` against `parts`, which hold no `**`. Each part covers
189/// exactly one name part, so the match compares the parts in order and needs
190/// no table.
191fn match_flat(parts: &[Part], name: &str) -> bool {
192    let mut name = name.split('/');
193    for part in parts {
194        let Some(piece) = name.next() else {
195            return false;
196        };
197        let ok = match part {
198            Part::Literal(literal) => piece == literal,
199            Part::One => true,
200            // The caller passes no `**`. The part would need more than one
201            // name part.
202            Part::Many => return false,
203        };
204        if !ok {
205            return false;
206        }
207    }
208    name.next().is_none()
209}
210
211/// A list of positive and negative [`RefPattern`]s.
212///
213/// An entry is a pattern with an optional first `!`, which makes it negative.
214/// A name is selected when the list has no positive pattern or a positive
215/// pattern matches it, and no negative pattern matches it. The order of the
216/// entries has no effect, and an empty list selects each name.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct RefSelector {
219    positive: Vec<RefPattern>,
220    negative: Vec<RefPattern>,
221}
222
223impl RefSelector {
224    /// Parses a list of entries. An entry is a pattern with an optional first
225    /// `!`. The selector keeps the entries in their order, with repeats.
226    ///
227    /// # Errors
228    ///
229    /// - [`Error::InvalidRefPattern`] if an entry is not valid. The text
230    ///   names the entry with its `!`.
231    pub fn parse<'a>(entries: impl IntoIterator<Item = &'a str>) -> Result<RefSelector> {
232        let mut positive = Vec::new();
233        let mut negative = Vec::new();
234        for entry in entries {
235            match entry.strip_prefix('!') {
236                Some(rest) => negative.push(parse_pattern(rest, entry)?),
237                None => positive.push(parse_pattern(entry, entry)?),
238            }
239        }
240        Ok(RefSelector { positive, negative })
241    }
242
243    /// Returns `true` if the selector selects `name`.
244    ///
245    /// The name is not checked against the ref-name rule.
246    pub fn matches(&self, name: &str) -> bool {
247        (self.positive.is_empty() || self.positive.iter().any(|p| p.matches(name)))
248            && !self.negative.iter().any(|p| p.matches(name))
249    }
250
251    /// Returns the positive patterns in entry order.
252    pub fn positive(&self) -> &[RefPattern] {
253        &self.positive
254    }
255
256    /// Returns the negative patterns in entry order, with the `!` removed.
257    pub fn negative(&self) -> &[RefPattern] {
258        &self.negative
259    }
260}
261
262/// The pattern types move freely across tasks and threads.
263const _: fn() = || {
264    fn assert_send_sync<T: Send + Sync>() {}
265    assert_send_sync::<RefPattern>();
266    assert_send_sync::<RefSelector>();
267};
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    fn pat(p: &str) -> RefPattern {
274        RefPattern::parse(p).unwrap()
275    }
276
277    /// The match with no table agrees with the table on patterns with no
278    /// `**`.
279    #[test]
280    fn the_flat_match_agrees_with_the_table() {
281        let patterns = ["a", "a/b", "*", "*/*", "a/*", "*/b", "a/*/c", "a/b/c"];
282        let names = [
283            "a", "b", "a/b", "a/c", "b/b", "a/b/c", "a/x/c", "a/b/c/d", "x/a/b", "a/b/d",
284        ];
285        for p in patterns {
286            let pattern = pat(p);
287            let parts: Vec<Part> = pattern.parts.clone();
288            for n in names {
289                let split: Vec<&str> = n.split('/').collect();
290                assert_eq!(
291                    match_flat(&parts, n),
292                    match_parts(&parts, &split, &mut 0),
293                    "{p} {n}"
294                );
295                assert_eq!(pattern.matches(n), match_flat(&parts, n), "{p} {n}");
296            }
297        }
298    }
299
300    #[test]
301    fn examples_match() {
302        let cases: [(&str, &[&str], &[&str]); 6] = [
303            ("a", &["a"], &["a/b"]),
304            ("a/b", &["a/b"], &["a/b/c"]),
305            ("a/*", &["a/b"], &["a/b/c"]),
306            ("a/**", &["a/b", "a/c/d"], &["a"]),
307            ("a/*/c", &["a/b/c"], &["a/b/d/c", "a/c"]),
308            ("a/**/c", &["a/b/c", "a/b/d/c"], &["a/c"]),
309        ];
310        for (p, yes, no) in cases {
311            let p = pat(p);
312            for n in yes {
313                assert!(p.matches(n), "{p:?} should match {n:?}");
314            }
315            for n in no {
316                assert!(!p.matches(n), "{p:?} should not match {n:?}");
317            }
318        }
319    }
320
321    #[test]
322    fn parse_refusals() {
323        let cases = [
324            "", "a//b", "/a", "a/", "b*c", "x**", "***", "*a", "a/*b", "!a", "a!", "!", ".", "..",
325            "a/.", "-a", "a b", "a:b", "a\0b",
326        ];
327        for p in cases {
328            let err = RefPattern::parse(p).unwrap_err();
329            assert!(matches!(err, Error::InvalidRefPattern(_)), "{p:?}: {err:?}");
330        }
331    }
332
333    #[test]
334    fn as_str_returns_text() {
335        assert_eq!(pat("a/*/**").as_str(), "a/*/**");
336    }
337
338    #[test]
339    fn single_star_and_double_star() {
340        let star = pat("*");
341        let many = pat("**");
342        for n in ["a", "main", "x.y"] {
343            assert!(star.matches(n), "{n:?}");
344        }
345        for n in ["a/b", "a/b/c"] {
346            assert!(!star.matches(n), "{n:?}");
347        }
348        for n in ["a", "a/b", "a/b/c/d"] {
349            assert!(many.matches(n), "{n:?}");
350        }
351    }
352
353    #[test]
354    fn double_star_minimums() {
355        let two = pat("**/**");
356        assert!(!two.matches("a"));
357        assert!(two.matches("a/b"));
358        assert!(two.matches("a/b/c"));
359        let lead = pat("**/c");
360        assert!(!lead.matches("c"));
361        assert!(lead.matches("a/c"));
362        assert!(lead.matches("a/b/c"));
363        assert!(!pat("a/**/c").matches("a/c"));
364    }
365
366    #[test]
367    fn names_the_rule_refuses_still_match() {
368        for n in ["a^b", "-x/.y", "a b/c"] {
369            assert!(pat("**").matches(n), "{n:?}");
370        }
371        assert!(pat("*").matches("a^b"));
372        assert!(pat("*/*").matches("-x/.y"));
373    }
374
375    fn sel(entries: &[&str]) -> RefSelector {
376        RefSelector::parse(entries.iter().copied()).unwrap()
377    }
378
379    #[test]
380    fn selector_positive_only() {
381        let s = sel(&["a/*", "b"]);
382        for (n, want) in [("a/x", true), ("b", true), ("c", false), ("a/x/y", false)] {
383            assert_eq!(s.matches(n), want, "{n:?}");
384        }
385    }
386
387    #[test]
388    fn selector_negative_only() {
389        let s = sel(&["!a/**"]);
390        for (n, want) in [("a/x", false), ("b", true), ("b/c", true)] {
391            assert_eq!(s.matches(n), want, "{n:?}");
392        }
393    }
394
395    #[test]
396    fn selector_mixed() {
397        let s = sel(&["a/**", "!a/x/**"]);
398        for (n, want) in [("a/y", true), ("a/x/z", false), ("b", false)] {
399            assert_eq!(s.matches(n), want, "{n:?}");
400        }
401    }
402
403    #[test]
404    fn selector_empty_selects_all() {
405        let s = RefSelector::parse(std::iter::empty()).unwrap();
406        for n in ["a", "a/b", "x^y"] {
407            assert!(s.matches(n), "{n:?}");
408        }
409        assert!(s.positive().is_empty() && s.negative().is_empty());
410    }
411
412    #[test]
413    fn selector_order_has_no_effect() {
414        for entries in [["!a/**", "a/b"], ["a/b", "!a/**"]] {
415            assert!(!sel(&entries).matches("a/b"), "{entries:?}");
416        }
417    }
418
419    #[test]
420    fn selector_repeats_and_order() {
421        let s = sel(&["b", "!x", "a", "b", "!y/*", "!x"]);
422        let pos: Vec<&str> = s.positive().iter().map(RefPattern::as_str).collect();
423        let neg: Vec<&str> = s.negative().iter().map(RefPattern::as_str).collect();
424        assert_eq!(pos, ["b", "a", "b"]);
425        assert_eq!(neg, ["x", "y/*", "x"]);
426        assert!(s.matches("a") && !s.matches("x"));
427    }
428
429    #[test]
430    fn selector_refusals_name_the_entry() {
431        for entry in [
432            "!!a", "!", "!a!", "", "a//b", "!b*c", "a!", "! ", "!\0", "!-a",
433        ] {
434            let err = RefSelector::parse(["ok", entry]).unwrap_err();
435            let Error::InvalidRefPattern(text) = &err else {
436                panic!("{entry:?}: {err:?}");
437            };
438            assert!(text.contains(&format!("{entry:?}")), "{entry:?}: {text}");
439            assert!(
440                err.to_string().starts_with("invalid ref pattern: "),
441                "{err}"
442            );
443        }
444    }
445
446    fn count(p: &str, n: usize) -> (bool, usize, usize) {
447        let pattern = pat(p);
448        let name = vec!["a"; n];
449        let mut steps = 0;
450        let hit = match_parts(&pattern.parts, &name, &mut steps);
451        (hit, steps, pattern.parts.len() * n)
452    }
453
454    #[test]
455    fn cost_is_bounded_by_the_product() {
456        let cases = [
457            ("**/**/**/**/x", false),
458            ("**/a/**/a/**/a/**/b", false),
459            ("*/*/*/*/*/x", false),
460            ("**/**/**/**/a", true),
461            ("**/a/**/a/**/a/**/a", true),
462        ];
463        for (p, want) in cases {
464            for n in [10, 100, 1000] {
465                let (hit, steps, bound) = count(p, n);
466                assert_eq!(hit, want, "{p:?} {n}");
467                assert!(steps <= bound, "{p:?} {n}: {steps} > {bound}");
468                let (_, double, _) = count(p, 2 * n);
469                assert!(double <= 2 * steps + 8, "{p:?} {n}: {steps} -> {double}");
470            }
471        }
472    }
473
474    /// A recursive reference matcher, for the cross-check.
475    fn naive(parts: &[&str], name: &[&str]) -> bool {
476        match parts.split_first() {
477            None => name.is_empty(),
478            Some((&"**", rest)) => (1..=name.len()).any(|k| naive(rest, &name[k..])),
479            Some((&"*", rest)) => !name.is_empty() && naive(rest, &name[1..]),
480            Some((lit, rest)) => name.first() == Some(lit) && naive(rest, &name[1..]),
481        }
482    }
483
484    /// Returns each sequence of 1 to `max` items from `alphabet`.
485    fn sequences<'a>(alphabet: &[&'a str], max: usize) -> Vec<Vec<&'a str>> {
486        let mut all: Vec<Vec<&str>> = Vec::new();
487        let mut layer: Vec<Vec<&str>> = vec![Vec::new()];
488        for _ in 0..max {
489            layer = layer
490                .iter()
491                .flat_map(|s| {
492                    alphabet.iter().map(move |a| {
493                        let mut t = s.clone();
494                        t.push(a);
495                        t
496                    })
497                })
498                .collect();
499            all.extend(layer.iter().cloned());
500        }
501        all
502    }
503
504    #[test]
505    fn agrees_with_the_naive_matcher() {
506        let patterns = sequences(&["a", "b", "*", "**"], 4);
507        let names = sequences(&["a", "b"], 5);
508        for p in &patterns {
509            let text = p.join("/");
510            let pattern = pat(&text);
511            for n in &names {
512                let name = n.join("/");
513                assert_eq!(pattern.matches(&name), naive(p, n), "{text:?} vs {name:?}");
514            }
515        }
516    }
517}