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    /// Returns `true` if the selector selects `name`.
255    ///
256    /// The name is not checked against the ref-name rule.
257    pub fn matches(&self, name: &str) -> bool {
258        (self.positive.is_empty() || self.positive.iter().any(|p| p.matches(name)))
259            && !self.negative.iter().any(|p| p.matches(name))
260    }
261
262    /// Returns the positive patterns in entry order.
263    pub fn positive(&self) -> &[RefPattern] {
264        &self.positive
265    }
266
267    /// Returns the negative patterns in entry order, with the `!` removed.
268    pub fn negative(&self) -> &[RefPattern] {
269        &self.negative
270    }
271}
272
273/// The pattern types move freely across tasks and threads.
274const _: fn() = || {
275    fn assert_send_sync<T: Send + Sync>() {}
276    assert_send_sync::<RefPattern>();
277    assert_send_sync::<RefSelector>();
278};
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    fn pat(p: &str) -> RefPattern {
285        RefPattern::parse(p).unwrap()
286    }
287
288    /// The match with no table agrees with the table on patterns with no
289    /// `**`, and on patterns whose one `**` is the last part.
290    #[test]
291    fn the_flat_match_agrees_with_the_table() {
292        let patterns = [
293            "a", "a/b", "*", "*/*", "a/*", "*/b", "a/*/c", "a/b/c", "**", "a/**", "*/**", "a/b/**",
294            "a/*/**", "*/*/**",
295        ];
296        let names = [
297            "",
298            "/",
299            "a/",
300            "/a",
301            "a//b",
302            "a",
303            "b",
304            "a/b",
305            "a/c",
306            "b/b",
307            "a/b/c",
308            "a/x/c",
309            "a/b/c/d",
310            "x/a/b",
311            "a/b/d",
312            "a/b/c/d/e/f",
313        ];
314        for p in patterns {
315            let pattern = pat(p);
316            let parts: Vec<Part> = pattern.parts.clone();
317            for n in names {
318                let split: Vec<&str> = n.split('/').collect();
319                assert_eq!(
320                    match_flat(&parts, n),
321                    match_parts(&parts, &split, &mut 0),
322                    "{p} {n}"
323                );
324                assert_eq!(pattern.matches(n), match_flat(&parts, n), "{p} {n}");
325            }
326        }
327    }
328
329    /// A last `**` covers one or more name parts, an empty part included.
330    #[test]
331    fn a_last_double_star_needs_one_part() {
332        let cases = [
333            ("**", "", true),
334            ("**", "a", true),
335            ("a/**", "a", false),
336            ("a/**", "a/", true),
337            ("a/**", "a/b/c/d", true),
338            ("a/**", "b/c", false),
339            ("*/**", "a", false),
340            ("*/**", "a/b", true),
341        ];
342        for (p, n, want) in cases {
343            assert_eq!(pat(p).matches(n), want, "{p:?} {n:?}");
344        }
345    }
346
347    #[test]
348    fn examples_match() {
349        let cases: [(&str, &[&str], &[&str]); 6] = [
350            ("a", &["a"], &["a/b"]),
351            ("a/b", &["a/b"], &["a/b/c"]),
352            ("a/*", &["a/b"], &["a/b/c"]),
353            ("a/**", &["a/b", "a/c/d"], &["a"]),
354            ("a/*/c", &["a/b/c"], &["a/b/d/c", "a/c"]),
355            ("a/**/c", &["a/b/c", "a/b/d/c"], &["a/c"]),
356        ];
357        for (p, yes, no) in cases {
358            let p = pat(p);
359            for n in yes {
360                assert!(p.matches(n), "{p:?} should match {n:?}");
361            }
362            for n in no {
363                assert!(!p.matches(n), "{p:?} should not match {n:?}");
364            }
365        }
366    }
367
368    #[test]
369    fn parse_refusals() {
370        let cases = [
371            "", "a//b", "/a", "a/", "b*c", "x**", "***", "*a", "a/*b", "!a", "a!", "!", ".", "..",
372            "a/.", "-a", "a b", "a:b", "a\0b",
373        ];
374        for p in cases {
375            let err = RefPattern::parse(p).unwrap_err();
376            assert!(matches!(err, Error::InvalidRefPattern(_)), "{p:?}: {err:?}");
377        }
378    }
379
380    #[test]
381    fn as_str_returns_text() {
382        assert_eq!(pat("a/*/**").as_str(), "a/*/**");
383    }
384
385    #[test]
386    fn single_star_and_double_star() {
387        let star = pat("*");
388        let many = pat("**");
389        for n in ["a", "main", "x.y"] {
390            assert!(star.matches(n), "{n:?}");
391        }
392        for n in ["a/b", "a/b/c"] {
393            assert!(!star.matches(n), "{n:?}");
394        }
395        for n in ["a", "a/b", "a/b/c/d"] {
396            assert!(many.matches(n), "{n:?}");
397        }
398    }
399
400    #[test]
401    fn double_star_minimums() {
402        let two = pat("**/**");
403        assert!(!two.matches("a"));
404        assert!(two.matches("a/b"));
405        assert!(two.matches("a/b/c"));
406        let lead = pat("**/c");
407        assert!(!lead.matches("c"));
408        assert!(lead.matches("a/c"));
409        assert!(lead.matches("a/b/c"));
410        assert!(!pat("a/**/c").matches("a/c"));
411    }
412
413    #[test]
414    fn names_the_rule_refuses_still_match() {
415        for n in ["a^b", "-x/.y", "a b/c"] {
416            assert!(pat("**").matches(n), "{n:?}");
417        }
418        assert!(pat("*").matches("a^b"));
419        assert!(pat("*/*").matches("-x/.y"));
420    }
421
422    fn sel(entries: &[&str]) -> RefSelector {
423        RefSelector::parse(entries.iter().copied()).unwrap()
424    }
425
426    #[test]
427    fn selector_positive_only() {
428        let s = sel(&["a/*", "b"]);
429        for (n, want) in [("a/x", true), ("b", true), ("c", false), ("a/x/y", false)] {
430            assert_eq!(s.matches(n), want, "{n:?}");
431        }
432    }
433
434    #[test]
435    fn selector_negative_only() {
436        let s = sel(&["!a/**"]);
437        for (n, want) in [("a/x", false), ("b", true), ("b/c", true)] {
438            assert_eq!(s.matches(n), want, "{n:?}");
439        }
440    }
441
442    #[test]
443    fn selector_mixed() {
444        let s = sel(&["a/**", "!a/x/**"]);
445        for (n, want) in [("a/y", true), ("a/x/z", false), ("b", false)] {
446            assert_eq!(s.matches(n), want, "{n:?}");
447        }
448    }
449
450    #[test]
451    fn selector_empty_selects_all() {
452        let s = RefSelector::parse(std::iter::empty()).unwrap();
453        for n in ["a", "a/b", "x^y"] {
454            assert!(s.matches(n), "{n:?}");
455        }
456        assert!(s.positive().is_empty() && s.negative().is_empty());
457    }
458
459    #[test]
460    fn selector_order_has_no_effect() {
461        for entries in [["!a/**", "a/b"], ["a/b", "!a/**"]] {
462            assert!(!sel(&entries).matches("a/b"), "{entries:?}");
463        }
464    }
465
466    #[test]
467    fn selector_repeats_and_order() {
468        let s = sel(&["b", "!x", "a", "b", "!y/*", "!x"]);
469        let pos: Vec<&str> = s.positive().iter().map(RefPattern::as_str).collect();
470        let neg: Vec<&str> = s.negative().iter().map(RefPattern::as_str).collect();
471        assert_eq!(pos, ["b", "a", "b"]);
472        assert_eq!(neg, ["x", "y/*", "x"]);
473        assert!(s.matches("a") && !s.matches("x"));
474    }
475
476    #[test]
477    fn selector_refusals_name_the_entry() {
478        for entry in [
479            "!!a", "!", "!a!", "", "a//b", "!b*c", "a!", "! ", "!\0", "!-a",
480        ] {
481            let err = RefSelector::parse(["ok", entry]).unwrap_err();
482            let Error::InvalidRefPattern(text) = &err else {
483                panic!("{entry:?}: {err:?}");
484            };
485            assert!(text.contains(&format!("{entry:?}")), "{entry:?}: {text}");
486            assert!(
487                err.to_string().starts_with("invalid ref pattern: "),
488                "{err}"
489            );
490        }
491    }
492
493    fn count(p: &str, n: usize) -> (bool, usize, usize) {
494        let pattern = pat(p);
495        let name = vec!["a"; n];
496        let mut steps = 0;
497        let hit = match_parts(&pattern.parts, &name, &mut steps);
498        (hit, steps, pattern.parts.len() * n)
499    }
500
501    #[test]
502    fn cost_is_bounded_by_the_product() {
503        let cases = [
504            ("**/**/**/**/x", false),
505            ("**/a/**/a/**/a/**/b", false),
506            ("*/*/*/*/*/x", false),
507            ("**/**/**/**/a", true),
508            ("**/a/**/a/**/a/**/a", true),
509        ];
510        for (p, want) in cases {
511            for n in [10, 100, 1000] {
512                let (hit, steps, bound) = count(p, n);
513                assert_eq!(hit, want, "{p:?} {n}");
514                assert!(steps <= bound, "{p:?} {n}: {steps} > {bound}");
515                let (_, double, _) = count(p, 2 * n);
516                assert!(double <= 2 * steps + 8, "{p:?} {n}: {steps} -> {double}");
517            }
518        }
519    }
520
521    /// A recursive reference matcher, for the cross-check.
522    fn naive(parts: &[&str], name: &[&str]) -> bool {
523        match parts.split_first() {
524            None => name.is_empty(),
525            Some((&"**", rest)) => (1..=name.len()).any(|k| naive(rest, &name[k..])),
526            Some((&"*", rest)) => !name.is_empty() && naive(rest, &name[1..]),
527            Some((lit, rest)) => name.first() == Some(lit) && naive(rest, &name[1..]),
528        }
529    }
530
531    /// Returns each sequence of 1 to `max` items from `alphabet`.
532    fn sequences<'a>(alphabet: &[&'a str], max: usize) -> Vec<Vec<&'a str>> {
533        let mut all: Vec<Vec<&str>> = Vec::new();
534        let mut layer: Vec<Vec<&str>> = vec![Vec::new()];
535        for _ in 0..max {
536            layer = layer
537                .iter()
538                .flat_map(|s| {
539                    alphabet.iter().map(move |a| {
540                        let mut t = s.clone();
541                        t.push(a);
542                        t
543                    })
544                })
545                .collect();
546            all.extend(layer.iter().cloned());
547        }
548        all
549    }
550
551    #[test]
552    fn agrees_with_the_naive_matcher() {
553        let patterns = sequences(&["a", "b", "*", "**"], 4);
554        let names = sequences(&["a", "b"], 5);
555        for p in &patterns {
556            let text = p.join("/");
557            let pattern = pat(&text);
558            for n in &names {
559                let name = n.join("/");
560                assert_eq!(pattern.matches(&name), naive(p, n), "{text:?} vs {name:?}");
561            }
562        }
563    }
564}