Skip to main content

codeint_config/
codeowners.rs

1use std::path::{Path, PathBuf};
2
3use globset::{GlobBuilder, GlobMatcher};
4
5#[cfg(test)]
6mod tests;
7
8#[derive(Debug, thiserror::Error)]
9pub enum CodeownersError {
10    #[error("cannot read {}", path.display())]
11    Read {
12        path: PathBuf,
13        #[source]
14        source: std::io::Error,
15    },
16    #[error("invalid owner filter pattern {pattern:?}")]
17    InvalidOwnerPattern {
18        pattern: String,
19        #[source]
20        source: globset::Error,
21    },
22}
23
24#[derive(Debug, Clone, Default)]
25pub struct Codeowners {
26    rules: Vec<Rule>,
27}
28
29#[derive(Debug, Clone)]
30struct Rule {
31    matchers: Vec<GlobMatcher>,
32    owners: Vec<String>,
33}
34
35impl Codeowners {
36    pub const STANDARD_PATHS: [&'static str; 3] =
37        [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"];
38
39    pub fn load(repository_root: &Path) -> Result<Option<Codeowners>, CodeownersError> {
40        for relative in Self::STANDARD_PATHS {
41            let path = repository_root.join(relative);
42            if path.is_file() {
43                let text = std::fs::read_to_string(&path)
44                    .map_err(|source| CodeownersError::Read { path, source })?;
45                return Ok(Some(Codeowners::parse(&text)));
46            }
47        }
48        Ok(None)
49    }
50
51    pub fn parse(text: &str) -> Codeowners {
52        let text = text.strip_prefix('\u{feff}').unwrap_or(text);
53        let rules = text.lines().filter_map(parse_rule).collect();
54        Codeowners { rules }
55    }
56
57    pub fn owners_for(&self, path: &str) -> Vec<String> {
58        let normalized = path.trim_start_matches('/');
59        self.rules
60            .iter()
61            .rev()
62            .find(|rule| rule.matches(normalized))
63            .map(|rule| rule.owners.clone())
64            .unwrap_or_default()
65    }
66
67    pub fn owners_for_many<'a>(&self, paths: impl IntoIterator<Item = &'a str>) -> Vec<String> {
68        let mut combined = Vec::new();
69        for path in paths {
70            for owner in self.owners_for(path) {
71                if !combined.contains(&owner) {
72                    combined.push(owner);
73                }
74            }
75        }
76        combined
77    }
78}
79
80impl Rule {
81    fn matches(&self, path: &str) -> bool {
82        self.matchers.iter().any(|matcher| matcher.is_match(path))
83    }
84}
85
86#[derive(Debug, Clone)]
87pub struct OwnerFilter {
88    matcher: GlobMatcher,
89}
90
91impl OwnerFilter {
92    pub fn new(pattern: &str) -> Result<OwnerFilter, CodeownersError> {
93        let matcher = GlobBuilder::new(pattern)
94            .case_insensitive(true)
95            .build()
96            .map_err(|source| CodeownersError::InvalidOwnerPattern {
97                pattern: pattern.to_owned(),
98                source,
99            })?
100            .compile_matcher();
101        Ok(OwnerFilter { matcher })
102    }
103
104    pub fn matches(&self, owner: &str) -> bool {
105        self.matcher.is_match(owner)
106    }
107
108    pub fn matches_any(&self, owners: &[String]) -> bool {
109        owners.iter().any(|owner| self.matches(owner))
110    }
111}
112
113fn parse_rule(line: &str) -> Option<Rule> {
114    let trimmed = line.trim();
115    if trimmed.is_empty() || trimmed.starts_with('#') {
116        return None;
117    }
118    let (pattern, rest) = take_pattern(trimmed);
119    if pattern.is_empty() {
120        return None;
121    }
122    let matchers = compile_pattern(&pattern)?;
123    let owners = parse_owners(rest);
124    Some(Rule { matchers, owners })
125}
126
127fn take_pattern(line: &str) -> (String, &str) {
128    let mut pattern = String::new();
129    let mut chars = line.char_indices().peekable();
130    while let Some((index, ch)) = chars.next() {
131        if ch == '\\' {
132            if let Some(&(_, next)) = chars.peek() {
133                if matches!(next, '\\' | '*' | '?' | '[' | ']' | '{' | '}') {
134                    pattern.push('\\');
135                }
136                pattern.push(next);
137                chars.next();
138            }
139            continue;
140        }
141        if ch.is_whitespace() {
142            return (pattern, &line[index..]);
143        }
144        pattern.push(ch);
145    }
146    (pattern, "")
147}
148
149fn parse_owners(rest: &str) -> Vec<String> {
150    rest.split_whitespace()
151        .take_while(|token| !token.starts_with('#'))
152        .map(str::to_owned)
153        .collect()
154}
155
156fn compile_pattern(pattern: &str) -> Option<Vec<GlobMatcher>> {
157    let (has_leading_slash, without_leading) = match pattern.strip_prefix('/') {
158        Some(rest) => (true, rest),
159        None => (false, pattern),
160    };
161    let (has_trailing_slash, core) = match without_leading.strip_suffix('/') {
162        Some(rest) => (true, rest),
163        None => (false, without_leading),
164    };
165    if core.is_empty() {
166        return None;
167    }
168    let anchored = has_leading_slash || core.contains('/');
169    let prefix = if anchored { "" } else { "**/" };
170    let mut patterns = Vec::new();
171    if has_trailing_slash {
172        patterns.push(format!("{prefix}{core}/**"));
173    } else {
174        patterns.push(format!("{prefix}{core}"));
175        if !last_segment_has_wildcard(core) {
176            patterns.push(format!("{prefix}{core}/**"));
177        }
178    }
179    let mut matchers = Vec::with_capacity(patterns.len());
180    for glob in patterns {
181        let matcher = GlobBuilder::new(&glob)
182            .literal_separator(true)
183            .backslash_escape(true)
184            .build()
185            .ok()?
186            .compile_matcher();
187        matchers.push(matcher);
188    }
189    Some(matchers)
190}
191
192fn last_segment_has_wildcard(pattern: &str) -> bool {
193    let last = pattern.rsplit('/').next().unwrap_or(pattern);
194    let mut chars = last.chars();
195    while let Some(ch) = chars.next() {
196        if ch == '\\' {
197            chars.next();
198            continue;
199        }
200        if matches!(ch, '*' | '?' | '[') {
201            return true;
202        }
203    }
204    false
205}