Skip to main content

specfold_core/workspace/owners/
patterns.rs

1//! Directory patterns: `services/*`-style kinds and path matchers for public and retired lists.
2
3use globset::{GlobBuilder, GlobMatcher};
4use std::path::Path;
5
6/// A path or glob; a plain path also matches everything under it.
7#[derive(Debug, Clone)]
8pub enum PathMatch {
9    Prefix(String),
10    Glob(GlobMatcher),
11}
12
13impl PathMatch {
14    pub fn is_match(&self, rel: &str) -> bool {
15        match self {
16            PathMatch::Prefix(p) => rel == p || rel.starts_with(&format!("{p}/")),
17            PathMatch::Glob(g) => g.is_match(rel),
18        }
19    }
20}
21
22/// Globs follow gitignore conventions: `*` stays within one path segment, `**` crosses them, and a
23/// pattern without a slash matches a file name at any depth.
24pub fn matcher(pattern: &str) -> Option<PathMatch> {
25    let p = pattern.trim_end_matches('/');
26    if p.contains(['*', '?', '[', '{']) {
27        let full = if p.contains('/') { p.to_string() } else { format!("**/{p}") };
28        GlobBuilder::new(&full).literal_separator(true).build().ok().map(|g| PathMatch::Glob(g.compile_matcher()))
29    } else {
30        Some(PathMatch::Prefix(p.to_string()))
31    }
32}
33
34/// C185: a literal path as a glob that matches only it: each of `[ * ? {` becomes a one-character
35/// class (`[[]`, `[*]`, …), which every glob reader takes literally. Other paths come back as is.
36pub fn escape_glob(path: &str) -> String {
37    let mut out = String::with_capacity(path.len());
38    for ch in path.chars() {
39        if matches!(ch, '[' | '*' | '?' | '{') {
40            out.push('[');
41            out.push(ch);
42            out.push(']');
43        } else {
44            out.push(ch);
45        }
46    }
47    out
48}
49
50/// The literal text before the first wildcard, reading `[c]` escapes of `[ * ? {` as `c`; the
51/// bool says whether a wildcard was found.
52pub fn literal_prefix(glob: &str) -> (String, bool) {
53    let b: Vec<char> = glob.chars().collect();
54    let mut out = String::new();
55    let mut i = 0;
56    while i < b.len() {
57        match b[i] {
58            '[' if b.len() > i + 2 && matches!(b[i + 1], '[' | '*' | '?' | '{') && b[i + 2] == ']' => {
59                out.push(b[i + 1]);
60                i += 3;
61            }
62            '[' | '*' | '?' | '{' => return (out, true),
63            c => {
64                out.push(c);
65                i += 1;
66            }
67        }
68    }
69    (out, false)
70}
71
72/// Expands a pattern of literal segments and `*` into existing directories, returning each with
73/// the values its `*` segments took.
74/// C210: owner patterns take literal folder names and whole `*` segments only. The problem
75/// with `pattern`, if it has one.
76pub fn kind_pattern_problem(pattern: &str) -> Option<String> {
77    let bad = pattern.trim_matches('/').split('/').find(|seg| *seg != "*" && seg.contains(['*', '?', '[', '{']))?;
78    Some(format!(
79        "owner pattern '{pattern}' has the segment '{bad}'; owner patterns take literal folder names and whole '*' segments, e.g. services/*"
80    ))
81}
82
83/// The number of `*` segments in an owner pattern: the captures `{1}`..`{N}` can name.
84pub fn kind_stars(pattern: &str) -> usize {
85    pattern.trim_matches('/').split('/').filter(|s| *s == "*").count()
86}
87
88pub fn expand(root: &Path, pattern: &str) -> Vec<(String, Vec<String>)> {
89    let mut acc: Vec<(String, Vec<String>)> = vec![(String::new(), vec![])];
90    for seg in pattern.trim_matches('/').split('/') {
91        let mut next = vec![];
92        for (base, caps) in &acc {
93            let dir = if base.is_empty() { root.to_path_buf() } else { root.join(base) };
94            if seg == "*" {
95                for name in subdirs(&dir) {
96                    let mut c = caps.clone();
97                    c.push(name.clone());
98                    next.push((join(base, &name), c));
99                }
100            } else if dir.join(seg).is_dir() {
101                next.push((join(base, seg), caps.clone()));
102            }
103        }
104        acc = next;
105    }
106    acc
107}
108
109fn subdirs(dir: &Path) -> Vec<String> {
110    let Ok(rd) = std::fs::read_dir(dir) else { return vec![] };
111    let mut names: Vec<String> = rd
112        .flatten()
113        .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
114        .map(|e| e.file_name().to_string_lossy().into_owned())
115        .filter(|n| !n.starts_with('.') && n != "node_modules" && n != "target")
116        .collect();
117    names.sort();
118    names
119}
120
121fn join(base: &str, seg: &str) -> String {
122    if base.is_empty() { seg.to_string() } else { format!("{base}/{seg}") }
123}
124
125/// Fills `{1}`, `{2}` … in an owner id template.
126pub fn render_id(template: &str, caps: &[String]) -> String {
127    caps.iter().enumerate().fold(template.to_string(), |s, (i, c)| s.replace(&format!("{{{}}}", i + 1), c))
128}
129
130pub fn has_manifest(dir: &Path, manifests: &[String]) -> bool {
131    manifests.iter().any(|m| match m.strip_prefix("*.") {
132        Some(ext) => std::fs::read_dir(dir)
133            .map(|rd| rd.flatten().any(|e| e.path().extension().is_some_and(|x| x == ext)))
134            .unwrap_or(false),
135        None => dir.join(m).is_file(),
136    })
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn globs_follow_gitignore_conventions() {
145        let m = |p: &str, rel: &str| matcher(p).unwrap().is_match(rel);
146        assert!(m("docs/plans/*.md", "docs/plans/a.md"));
147        assert!(!m("docs/plans/*.md", "docs/plans/a/10-steps.md"));
148        assert!(m("docs/**/*.md", "docs/plans/a/10-steps.md"));
149        assert!(m("*.md", "docs/plans/a.md"));
150        assert!(m("services/shop", "services/shop/src/main.rs"));
151    }
152}