Skip to main content

fallow_engine/
codeowners.rs

1//! CODEOWNERS file parser and ownership lookup.
2//!
3//! Parses GitHub/GitLab-style CODEOWNERS files and matches file paths
4//! to their owners. Used by `--group-by owner` to group analysis output
5//! by team ownership.
6//!
7//! # Pattern semantics
8//!
9//! CODEOWNERS patterns follow gitignore-like rules:
10//! - `*.js` matches any `.js` file in any directory
11//! - `/docs/*` matches files directly in `docs/` (root-anchored)
12//! - `/*` matches root-level files only; `*` is the catch-all
13//! - `docs/` matches everything under a `docs/` directory at any depth
14//! - `/docs` matches a file `docs` or everything under the `docs/` directory
15//! - `*` does not match `/`
16//! - Last matching rule wins
17//! - First owner on a multi-owner line is the primary owner
18//!
19//! # GitLab extensions
20//!
21//! GitLab's CODEOWNERS format is a superset of GitHub's. The following
22//! GitLab-only syntax is accepted (though it doesn't affect ownership
23//! lookup beyond propagating the default owners within a section):
24//!
25//! - Section headers: `[Section name]`, `^[Section name]` (optional section),
26//!   `[Section name][N]` (N required approvals)
27//! - Section default owners: `[Section] @owner1 @owner2`. Pattern lines
28//!   inside the section that omit inline owners inherit the section's defaults
29//! - Exclusion patterns: `!path` clears ownership for matching files
30//!   (GitLab 17.10+). A negation that is the last matching rule for a
31//!   file makes it unowned.
32//! - Repeated section names: headers with the same name, compared without
33//!   case, form one section. The section keeps the name of its first header.
34//!   Its default owners are the default owners of all its headers, in file
35//!   order, each one time. A pattern line without inline owners inherits the
36//!   default owners of the header directly above it.
37
38use std::path::Path;
39
40use globset::{Candidate, Glob, GlobBuilder, GlobSet, GlobSetBuilder};
41use rustc_hash::{FxHashMap, FxHashSet};
42
43/// Wildcards (`*`, `?`, `[`, `{`) allowed in one CODEOWNERS pattern.
44///
45/// Real CODEOWNERS patterns use a few wildcards. A pattern with thousands
46/// of them makes each lookup build a large lazy DFA.
47const MAX_RULE_WILDCARDS: usize = 32;
48
49/// Wildcards allowed across all patterns of one CODEOWNERS file.
50///
51/// Bound the total work required to compile patterns. Large public CODEOWNERS
52/// files stay below 400 wildcards.
53const MAX_FILE_WILDCARDS: usize = 4096;
54
55/// Bytes allowed in one CODEOWNERS pattern.
56///
57/// The `GlobSet` matches literal prefixes with an Aho-Corasick DFA, and its
58/// build time grows with the square of the pattern length. Real CODEOWNERS
59/// patterns are far shorter.
60const MAX_RULE_BYTES: usize = 512;
61
62/// Target regex-source bytes times glob count in one matcher batch.
63///
64/// Regex fallback caches multiply automaton states by capture slots for every
65/// pattern. Batch this product, rather than only counting wildcards, so long
66/// literals cannot multiply the cache cost of every other ownership rule.
67/// A larger single glob remains valid and compiles in its own batch.
68const MAX_MATCHER_COST: usize = 8 * 1024 * 1024;
69
70/// One CODEOWNERS rule line.
71#[derive(Debug)]
72struct Rule {
73    /// Pattern text from the file. An exclusion keeps its `!` prefix.
74    pattern: String,
75    /// Primary owner. `None` for a GitLab exclusion (`!path`).
76    owner: Option<String>,
77    /// Number of owners on the rule. Zero for an exclusion.
78    owner_count: u32,
79    /// Index into `CodeOwners::sections`. `None` before the first header.
80    section: Option<usize>,
81}
82
83/// One GitLab section.
84#[derive(Debug)]
85struct Section {
86    name: String,
87    default_owners: Vec<String>,
88}
89
90/// The last CODEOWNERS rule that matches a path.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct RuleMatch<'a> {
93    /// Primary owner. `None` when the rule is a GitLab exclusion (`!path`).
94    pub owner: Option<&'a str>,
95    /// Number of owners on the rule. Zero for an exclusion.
96    pub owner_count: u32,
97    /// Pattern text from the file. An exclusion keeps its `!` prefix.
98    pub pattern: &'a str,
99    /// Section of the rule. `None` for a rule before the first header.
100    pub section: Option<&'a str>,
101    /// Default owners of the section. Empty outside a section.
102    pub section_owners: &'a [String],
103}
104
105/// Parsed CODEOWNERS file for ownership lookup.
106#[derive(Debug)]
107pub struct CodeOwners {
108    /// Rules in file order.
109    rules: Vec<Rule>,
110    /// GitLab sections in the order of their first header.
111    sections: Vec<Section>,
112    /// Ordered batches keep regex fallback caches independent of other batches.
113    globs: Vec<CodeOwnersMatcher>,
114    /// Index into `rules` per translated glob, across all matcher batches.
115    glob_rules: Vec<usize>,
116}
117
118#[derive(Debug)]
119struct CodeOwnersMatcher {
120    globs: GlobSet,
121    /// Position of the batch's first glob in `CodeOwners::glob_rules`.
122    glob_offset: usize,
123}
124
125/// Standard locations to probe for a CODEOWNERS file, in priority order.
126///
127/// Order: root catch-all → GitHub → GitLab → GitHub legacy (`docs/`).
128const PROBE_PATHS: &[&str] = &[
129    "CODEOWNERS",
130    ".github/CODEOWNERS",
131    ".gitlab/CODEOWNERS",
132    "docs/CODEOWNERS",
133];
134
135/// Label for files that match no CODEOWNERS rule.
136pub const UNOWNED_LABEL: &str = "(unowned)";
137
138/// Label for files owned by a rule declared before any GitLab section header.
139///
140/// Used as the group key for `--group-by section` when the last matching rule
141/// isn't inside any `[Section]` block.
142pub const NO_SECTION_LABEL: &str = "(no section)";
143
144/// The text of the CODEOWNERS file at `path` below `root`, read with the
145/// bounded read helper.
146fn read_project_file(
147    root: &Path,
148    path: &Path,
149) -> Result<String, fallow_types::read_guard::ReadRefusal> {
150    fallow_types::read_guard::read_to_string_inside(
151        root,
152        path,
153        fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
154    )
155}
156
157impl CodeOwners {
158    /// Load and parse a CODEOWNERS file from the given path.
159    pub fn from_file(path: &Path) -> Result<Self, String> {
160        let content = std::fs::read_to_string(path)
161            .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
162        Self::parse(&content)
163    }
164
165    /// Auto-probe standard CODEOWNERS locations relative to the project root.
166    ///
167    /// Tries `CODEOWNERS`, `.github/CODEOWNERS`, `.gitlab/CODEOWNERS`, `docs/CODEOWNERS`.
168    /// A probe that is a link must resolve to a file inside `root`. A probe
169    /// link that does not resolve there gets a warning, and the search goes
170    /// on with the next location. A dangling link and a link to a file
171    /// outside `root` get the same warning.
172    pub fn discover(root: &Path) -> Result<Self, String> {
173        for probe in PROBE_PATHS {
174            let present = root
175                .join(probe)
176                .symlink_metadata()
177                .is_ok_and(|meta| meta.is_file() || meta.file_type().is_symlink());
178            let parent_is_link = Path::new(probe).parent().is_some_and(|parent| {
179                !parent.as_os_str().is_empty()
180                    && root
181                        .join(parent)
182                        .symlink_metadata()
183                        .is_ok_and(|meta| meta.file_type().is_symlink())
184            });
185            if !present && !parent_is_link {
186                continue;
187            }
188            match read_project_file(root, Path::new(probe)) {
189                Ok(content) => return Self::parse(&content),
190                Err(fallow_types::read_guard::ReadRefusal::OutsideRoot { .. }) => {
191                    tracing::warn!(
192                        "skipping {probe}: it is a link that does not resolve to a file inside the project root"
193                    );
194                }
195                Err(refusal) if refusal.is_not_found() => {}
196                Err(refusal) => return Err(refusal.to_string()),
197            }
198        }
199        Err(format!(
200            "no CODEOWNERS file found (looked for: {}). \
201             Create one of these files or use --group-by directory instead",
202            PROBE_PATHS.join(", ")
203        ))
204    }
205
206    /// Load from a config-specified path, or auto-discover. A discovered
207    /// file must resolve inside `root`. A config-specified path is taken
208    /// relative to `root` and must resolve inside the project scope base of
209    /// `root` (see [`fallow_config::project_scope_base`]), so the config of a
210    /// monorepo package can name the `CODEOWNERS` file of the repository.
211    pub fn load(root: &Path, config_path: Option<&str>) -> Result<Self, String> {
212        if let Some(p) = config_path {
213            let base = fallow_config::project_scope_base(root);
214            Self::from_project_file(&base, &root.join(p)).map_err(|error| {
215                fallow_config::outside_value_error(root, "codeowners", Path::new(p))
216                    .unwrap_or(error)
217            })
218        } else {
219            Self::discover(root)
220        }
221    }
222
223    /// Load and parse the CODEOWNERS file at `path` below `root`. The read
224    /// refuses a path that resolves outside `root`, a file that is not a
225    /// regular file, and a very large file.
226    fn from_project_file(root: &Path, path: &Path) -> Result<Self, String> {
227        let content = read_project_file(root, path).map_err(|e| e.to_string())?;
228        Self::parse(&content)
229    }
230
231    /// Parse CODEOWNERS content into a lookup structure.
232    ///
233    /// The parser ignores a UTF-8 byte order mark at the start of the content.
234    pub fn parse(content: &str) -> Result<Self, String> {
235        let content = content.strip_prefix('\u{FEFF}').unwrap_or(content);
236        let mut parser = CodeOwnersParser::new();
237        for line in content.lines() {
238            parser.parse_line(line)?;
239        }
240        parser.finish()
241    }
242
243    /// Index of the last CODEOWNERS rule that matches the path, if any.
244    ///
245    /// CODEOWNERS resolves ownership with last-match-wins, so the highest
246    /// rule index wins. Batches retain glob order, so the first matching batch
247    /// in reverse order contains the winning rule.
248    fn last_matching_rule(&self, relative_path: &Path) -> Option<usize> {
249        let candidate = Candidate::new(relative_path);
250        self.globs.iter().rev().find_map(|batch| {
251            batch
252                .globs
253                .matches_candidate(&candidate)
254                .into_iter()
255                .map(|idx| self.glob_rules[batch.glob_offset + idx])
256                .max()
257        })
258    }
259
260    /// Look up the last CODEOWNERS rule that matches a path (relative to the
261    /// project root).
262    ///
263    /// Returns `None` when no rule matches. For a GitLab exclusion (`!path`)
264    /// the result has `owner: None` and `owner_count: 0`. For a rule before the
265    /// first section header the result has `section: None` and no section
266    /// owners.
267    pub fn match_path(&self, relative_path: &Path) -> Option<RuleMatch<'_>> {
268        let rule = &self.rules[self.last_matching_rule(relative_path)?];
269        let section = rule.section.map(|idx| &self.sections[idx]);
270        Some(RuleMatch {
271            owner: rule.owner.as_deref(),
272            owner_count: rule.owner_count,
273            pattern: &rule.pattern,
274            section: section.map(|s| s.name.as_str()),
275            section_owners: section.map_or(&[][..], |s| s.default_owners.as_slice()),
276        })
277    }
278
279    /// Look up the primary owner of a file path (relative to project root).
280    ///
281    /// Returns the first owner from the last matching CODEOWNERS rule,
282    /// or `None` if no rule matches or the last matching rule is a
283    /// GitLab-style exclusion (`!path`).
284    pub fn owner_of(&self, relative_path: &Path) -> Option<&str> {
285        self.match_path(relative_path)?.owner
286    }
287
288    /// Look up the number of owners matched by the last matching CODEOWNERS rule.
289    ///
290    /// Returns `Some(0)` when the path is explicitly unowned by a GitLab
291    /// negation, and `None` when no CODEOWNERS rule matches.
292    pub fn owner_count_of(&self, relative_path: &Path) -> Option<u32> {
293        self.match_path(relative_path).map(|m| m.owner_count)
294    }
295
296    /// Whether the parsed file contains at least one GitLab section header.
297    ///
298    /// `--group-by section` errors out when this is false, since every file
299    /// would collapse into the `(no section)` bucket.
300    pub fn has_sections(&self) -> bool {
301        !self.sections.is_empty()
302    }
303}
304
305struct CodeOwnersParser {
306    globs: Vec<Glob>,
307    glob_rules: Vec<usize>,
308    rules: Vec<Rule>,
309    sections: Vec<Section>,
310    /// Index into `sections` by lowercase section name.
311    section_index: FxHashMap<String, usize>,
312    /// `(section index, owner)` pairs in the default owners of a section.
313    /// A hash set keeps the merge of a header linear in its owner count.
314    section_owners_seen: FxHashSet<(usize, String)>,
315    current_section: Option<usize>,
316    /// Default owners of the header directly above the current line.
317    current_section_owners: Vec<String>,
318    wildcards: usize,
319}
320
321impl CodeOwnersParser {
322    fn new() -> Self {
323        Self {
324            globs: Vec::new(),
325            glob_rules: Vec::new(),
326            rules: Vec::new(),
327            sections: Vec::new(),
328            section_index: FxHashMap::default(),
329            section_owners_seen: FxHashSet::default(),
330            current_section: None,
331            current_section_owners: Vec::new(),
332            wildcards: 0,
333        }
334    }
335
336    fn parse_line(&mut self, line: &str) -> Result<(), String> {
337        match parse_codeowners_line(line, &self.current_section_owners) {
338            ParsedCodeOwnersLine::Skip => Ok(()),
339            ParsedCodeOwnersLine::Section { name, defaults } => {
340                self.enter_section(name, defaults);
341                Ok(())
342            }
343            ParsedCodeOwnersLine::Rule {
344                pattern,
345                owner,
346                owner_count,
347                negate,
348            } => self.add_rule(pattern, owner, owner_count, negate),
349        }
350    }
351
352    /// Make the section of a header the current section.
353    ///
354    /// GitLab combines sections with the same name and compares the names
355    /// without case. The section keeps the name of its first header.
356    fn enter_section(&mut self, name: String, defaults: Vec<String>) {
357        let key = name.to_lowercase();
358        let idx = if let Some(&idx) = self.section_index.get(&key) {
359            idx
360        } else {
361            let idx = self.sections.len();
362            self.sections.push(Section {
363                name,
364                default_owners: Vec::new(),
365            });
366            self.section_index.insert(key, idx);
367            idx
368        };
369        for owner in &defaults {
370            if self.section_owners_seen.insert((idx, owner.clone())) {
371                self.sections[idx].default_owners.push(owner.clone());
372            }
373        }
374        self.current_section = Some(idx);
375        self.current_section_owners = defaults;
376    }
377
378    fn add_rule(
379        &mut self,
380        pattern: String,
381        owner: String,
382        owner_count: u32,
383        negate: bool,
384    ) -> Result<(), String> {
385        if pattern.len() > MAX_RULE_BYTES {
386            let start: String = pattern.chars().take(40).collect();
387            return Err(format!(
388                "CODEOWNERS pattern '{start}...' is longer than {MAX_RULE_BYTES} bytes"
389            ));
390        }
391        let wildcards = pattern
392            .bytes()
393            .filter(|b| matches!(b, b'*' | b'?' | b'[' | b'{'))
394            .count();
395        if wildcards > MAX_RULE_WILDCARDS {
396            return Err(format!(
397                "CODEOWNERS pattern '{pattern}' has more than {MAX_RULE_WILDCARDS} wildcards"
398            ));
399        }
400        self.wildcards += wildcards;
401        if self.wildcards > MAX_FILE_WILDCARDS {
402            return Err(format!(
403                "CODEOWNERS file has more than {MAX_FILE_WILDCARDS} wildcards in its patterns"
404            ));
405        }
406
407        let rule_idx = self.rules.len();
408        for glob_pattern in translate_pattern(&pattern) {
409            // A backslash escapes the next character on every platform, as in
410            // gitignore. The globset default turns escapes off on Windows.
411            let glob = GlobBuilder::new(&glob_pattern)
412                .literal_separator(true)
413                .backslash_escape(true)
414                .build()
415                .map_err(|e| format!("invalid CODEOWNERS pattern '{pattern}': {e}"))?;
416            self.globs.push(glob);
417            self.glob_rules.push(rule_idx);
418        }
419
420        self.rules.push(Rule {
421            pattern: if negate {
422                format!("!{pattern}")
423            } else {
424                pattern
425            },
426            owner: (!negate).then_some(owner),
427            owner_count,
428            section: self.current_section,
429        });
430        Ok(())
431    }
432
433    fn finish(self) -> Result<CodeOwners, String> {
434        let mut globs = Vec::new();
435        let mut offset = 0;
436        let mut remaining = self.globs.into_iter().peekable();
437        while remaining.peek().is_some() {
438            let mut builder = GlobSetBuilder::new();
439            let mut regex_bytes: usize = 0;
440            let mut count = 0;
441            while let Some(glob) = remaining.next_if(|glob| {
442                let next_bytes = regex_bytes.saturating_add(glob.regex().len());
443                if count > 0 && next_bytes.saturating_mul(count + 1) > MAX_MATCHER_COST {
444                    return false;
445                }
446                regex_bytes = next_bytes;
447                true
448            }) {
449                builder.add(glob);
450                count += 1;
451            }
452            globs.push(CodeOwnersMatcher {
453                globs: builder
454                    .build()
455                    .map_err(|e| format!("failed to compile CODEOWNERS patterns: {e}"))?,
456                glob_offset: offset,
457            });
458            offset += count;
459        }
460
461        Ok(CodeOwners {
462            rules: self.rules,
463            sections: self.sections,
464            globs,
465            glob_rules: self.glob_rules,
466        })
467    }
468}
469
470enum ParsedCodeOwnersLine {
471    Skip,
472    Section {
473        name: String,
474        defaults: Vec<String>,
475    },
476    Rule {
477        pattern: String,
478        owner: String,
479        owner_count: u32,
480        negate: bool,
481    },
482}
483
484fn parse_codeowners_line(line: &str, current_section_owners: &[String]) -> ParsedCodeOwnersLine {
485    let line = line.trim();
486    if line.is_empty() || line.starts_with('#') {
487        return ParsedCodeOwnersLine::Skip;
488    }
489
490    if let Some((name, defaults)) = parse_section_header(line) {
491        return ParsedCodeOwnersLine::Section { name, defaults };
492    }
493
494    let (negate, rest) = if let Some(after) = line.strip_prefix('!') {
495        (true, after.trim_start())
496    } else {
497        (false, line)
498    };
499
500    let (pattern, owners_text) = split_pattern(rest);
501    if pattern.is_empty() {
502        return ParsedCodeOwnersLine::Skip;
503    }
504    let inline_owners = owners_text.split_whitespace().collect::<Vec<_>>();
505
506    let (owner, owner_count) = if negate {
507        (String::new(), 0)
508    } else if let Some(owner) = inline_owners.first() {
509        (
510            (*owner).to_string(),
511            u32::try_from(inline_owners.len()).unwrap_or(u32::MAX),
512        )
513    } else if let Some(owner) = current_section_owners.first() {
514        (
515            owner.clone(),
516            u32::try_from(current_section_owners.len()).unwrap_or(u32::MAX),
517        )
518    } else {
519        return ParsedCodeOwnersLine::Skip;
520    };
521
522    ParsedCodeOwnersLine::Rule {
523        pattern: pattern.to_string(),
524        owner,
525        owner_count,
526        negate,
527    }
528}
529
530/// Split a rule line at the first whitespace that a backslash does not escape.
531///
532/// GitLab writes a space in a path as `\ `, for example
533/// `/docs/Security\ Release.md @owner`.
534fn split_pattern(line: &str) -> (&str, &str) {
535    let mut escaped = false;
536    for (idx, ch) in line.char_indices() {
537        if escaped {
538            escaped = false;
539        } else if ch == '\\' {
540            escaped = true;
541        } else if ch.is_whitespace() {
542            return (&line[..idx], &line[idx..]);
543        }
544    }
545    (line, "")
546}
547
548/// Parse a GitLab CODEOWNERS section header.
549///
550/// Recognized forms (all optionally prefixed with `^` for optional sections):
551/// - `[Section name]`
552/// - `[Section name][N]` (N required approvals)
553/// - `[Section name] @owner1 @owner2` (section default owners)
554/// - `^[Section name][N] @owner` (any combination of the above)
555///
556/// Returns `Some((name, default_owners))` if the line is a well-formed section
557/// header. The returned owner vec is empty when the header declares no default
558/// owners. Returns `None` when the line is not a section header and should be
559/// parsed as a rule instead. Detection is strict: a line like `[abc]def @owner`
560/// that has non-whitespace content directly after the closing `]` is not
561/// treated as a section header, so legacy GitHub CODEOWNERS patterns continue
562/// to parse.
563fn parse_section_header(line: &str) -> Option<(String, Vec<String>)> {
564    let rest = line.strip_prefix('^').unwrap_or(line);
565    let rest = rest.strip_prefix('[')?;
566    let close = rest.find(']')?;
567    let name = &rest[..close];
568    if name.is_empty() {
569        return None;
570    }
571    let mut after = &rest[close + 1..];
572
573    if let Some(inner) = after.strip_prefix('[') {
574        let n_close = inner.find(']')?;
575        let count = &inner[..n_close];
576        if count.is_empty() || !count.chars().all(|c| c.is_ascii_digit()) {
577            return None;
578        }
579        after = &inner[n_close + 1..];
580    }
581
582    if !after.is_empty() && !after.starts_with(char::is_whitespace) {
583        return None;
584    }
585
586    Some((
587        name.to_string(),
588        after.split_whitespace().map(String::from).collect(),
589    ))
590}
591
592/// Translate a CODEOWNERS pattern to one or more `globset` glob patterns.
593///
594/// CODEOWNERS uses gitignore semantics. The caller compiles each glob with
595/// `literal_separator`, so `*` and `?` do not match `/`.
596/// - A leading `/` anchors the pattern to the root (stripped for globset).
597/// - A trailing `/` matches the directory contents only (`dir/` → `dir/**`).
598/// - A pattern without a trailing `/` matches a file or a directory. A
599///   directory match covers all paths below it (`/docs` → `docs` and
600///   `docs/**`).
601/// - A last segment of only `*` or `**` gets no extra glob. Thus `docs/*`
602///   matches the direct children of `docs` only, as GitHub documents.
603/// - A pattern without an inner `/` matches at any depth (`*.js` →
604///   `**/*.js`, `apps/` → `**/apps/**`).
605fn translate_pattern(pattern: &str) -> Vec<String> {
606    let (anchored, rest) = match pattern.strip_prefix('/') {
607        Some(p) => (true, p),
608        None => (false, pattern),
609    };
610    let (directory_only, body) = match rest.strip_suffix('/') {
611        Some(p) => (true, p),
612        None => (false, rest),
613    };
614    if body.is_empty() {
615        return vec!["**".to_string()];
616    }
617
618    let base = if !anchored && !body.contains('/') {
619        format!("**/{body}")
620    } else {
621        body.to_string()
622    };
623    let contents = format!("{base}/**");
624    if directory_only {
625        return vec![contents];
626    }
627
628    let last_segment = base.rsplit('/').next().unwrap_or(&base);
629    if matches!(last_segment, "*" | "**") {
630        vec![base]
631    } else {
632        vec![base, contents]
633    }
634}
635
636/// Extract the first path component for `--group-by directory` grouping.
637///
638/// Returns the first directory segment of a relative path.
639/// For monorepo structures (`packages/auth/...`), returns `packages`.
640pub fn directory_group(relative_path: &Path) -> &str {
641    let s = relative_path.to_str().unwrap_or("");
642    let s = if s.contains('\\') {
643        return s.split(['/', '\\']).next().unwrap_or(s);
644    } else {
645        s
646    };
647
648    match s.find('/') {
649        Some(pos) => &s[..pos],
650        None => s, // Root-level file
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657
658    #[test]
659    fn translate_bare_glob() {
660        assert_eq!(translate_pattern("*.js"), ["**/*.js", "**/*.js/**"]);
661    }
662
663    #[test]
664    fn translate_rooted_pattern() {
665        assert_eq!(translate_pattern("/docs/*"), ["docs/*"]);
666    }
667
668    #[test]
669    fn translate_directory_pattern() {
670        assert_eq!(translate_pattern("docs/"), ["**/docs/**"]);
671    }
672
673    #[test]
674    fn translate_rooted_directory() {
675        assert_eq!(translate_pattern("/src/app/"), ["src/app/**"]);
676    }
677
678    #[test]
679    fn translate_rooted_path_without_trailing_slash() {
680        assert_eq!(translate_pattern("/docs"), ["docs", "docs/**"]);
681    }
682
683    #[test]
684    fn translate_path_with_slash() {
685        assert_eq!(
686            translate_pattern("src/utils/*.ts"),
687            ["src/utils/*.ts", "src/utils/*.ts/**"]
688        );
689    }
690
691    #[test]
692    fn translate_double_star() {
693        assert_eq!(
694            translate_pattern("**/test_*.py"),
695            ["**/test_*.py", "**/test_*.py/**"]
696        );
697        assert_eq!(translate_pattern("/build/**"), ["build/**"]);
698    }
699
700    #[test]
701    fn translate_single_file() {
702        assert_eq!(
703            translate_pattern("Makefile"),
704            ["**/Makefile", "**/Makefile/**"]
705        );
706    }
707
708    #[test]
709    fn translate_catch_all() {
710        assert_eq!(translate_pattern("*"), ["**/*"]);
711    }
712
713    #[test]
714    fn parse_simple_codeowners() {
715        let content = "* @global-owner\n/src/ @frontend\n*.rs @rust-team\n";
716        let co = CodeOwners::parse(content).unwrap();
717        assert_eq!(co.rules.len(), 3);
718    }
719
720    #[test]
721    fn parse_skips_comments_and_blanks() {
722        let content = "# Comment\n\n* @owner\n  # Indented comment\n";
723        let co = CodeOwners::parse(content).unwrap();
724        assert_eq!(co.rules.len(), 1);
725    }
726
727    #[test]
728    fn parse_multi_owner_takes_first() {
729        let content = "*.ts @team-a @team-b @team-c\n";
730        let co = CodeOwners::parse(content).unwrap();
731        assert_eq!(co.rules[0].owner.as_deref(), Some("@team-a"));
732    }
733
734    #[test]
735    fn parse_skips_pattern_without_owner() {
736        let content = "*.ts\n*.js @owner\n";
737        let co = CodeOwners::parse(content).unwrap();
738        assert_eq!(co.rules.len(), 1);
739        assert_eq!(co.rules[0].owner.as_deref(), Some("@owner"));
740    }
741
742    #[test]
743    fn long_patterns_do_not_multiply_lookup_resources_by_rule_count() {
744        use std::fmt::Write as _;
745
746        let mut content = String::from("[Files] @files\n/docs/escaped\\ file.md @escaped\n");
747        for index in 0..256 {
748            writeln!(content, "file{index}?").expect("writing to a String cannot fail");
749        }
750        let literal = "a".repeat(MAX_RULE_BYTES - 2);
751        writeln!(
752            content,
753            "[Long] @long\n{literal}*\"\n[Overrides] @override\n!file0x\nfile1x"
754        )
755        .expect("writing to a String cannot fail");
756        let owners = CodeOwners::parse(&content).unwrap();
757        let start = std::time::Instant::now();
758        for _ in 0..5 {
759            for index in 2..256 {
760                assert_eq!(
761                    owners.owner_of(Path::new(&format!("file{index}x"))),
762                    Some("@files")
763                );
764            }
765            assert_eq!(
766                owners.owner_of(Path::new(&format!("{literal}suffix\""))),
767                Some("@long")
768            );
769            assert_eq!(owners.owner_of(Path::new("file0x")), None);
770            assert_eq!(owners.owner_of(Path::new("file1x")), Some("@override"));
771            assert_eq!(
772                owners.owner_of(Path::new("docs/escaped file.md")),
773                Some("@escaped")
774            );
775            assert_eq!(
776                owners.match_path(Path::new("file1x")).map(|m| m.section),
777                Some(Some("Overrides"))
778            );
779        }
780        assert!(
781            start.elapsed() < std::time::Duration::from_secs(25),
782            "ownership lookup exceeded its resource regression budget"
783        );
784    }
785
786    /// The matcher build time grows with the square of the pattern length.
787    /// OSS-Fuzz issue 579300911 had a 96 KB pattern.
788    #[test]
789    fn parse_rejects_rule_that_is_too_long() {
790        let content = format!(
791            "/{}/ @owner\n/x/{}/ @owner\n",
792            "0".repeat(512),
793            "0".repeat(4_096)
794        );
795        let err = CodeOwners::parse(&content).err().unwrap_or_default();
796        assert!(err.contains("longer than 512 bytes"), "{err}");
797
798        let content = format!("/{}/ @owner\n", "0".repeat(509));
799        assert!(CodeOwners::parse(&content).is_ok());
800    }
801
802    #[test]
803    fn parse_rejects_rule_with_too_many_wildcards() {
804        let content = format!("{} @owner\n", "*a".repeat(33));
805        let err = CodeOwners::parse(&content).unwrap_err();
806        assert!(err.contains("more than 32 wildcards"), "{err}");
807    }
808
809    #[test]
810    fn parse_rejects_file_with_too_many_wildcards() {
811        let rule = format!("{} @owner\n", "*a".repeat(16));
812        let err = CodeOwners::parse(&rule.repeat(257)).unwrap_err();
813        assert!(err.contains("more than 4096 wildcards"), "{err}");
814    }
815
816    #[test]
817    fn parse_counts_every_wildcard_kind() {
818        let content = format!("!{} @owner\n", "{a,b}?[x]".repeat(11));
819        let err = CodeOwners::parse(&content).unwrap_err();
820        assert!(err.contains("more than 32 wildcards"), "{err}");
821    }
822
823    #[test]
824    fn parse_accepts_wildcards_at_the_limits() {
825        let rule = format!("{} @owner\n", "*a".repeat(32));
826        let co = CodeOwners::parse(&rule.repeat(128)).unwrap();
827        assert_eq!(co.rules.len(), 128);
828    }
829
830    #[test]
831    fn parse_empty_content() {
832        let co = CodeOwners::parse("").unwrap();
833        assert_eq!(co.owner_of(Path::new("anything.ts")), None);
834    }
835
836    #[test]
837    fn owner_of_last_match_wins() {
838        let content = "* @default\n/src/ @frontend\n";
839        let co = CodeOwners::parse(content).unwrap();
840        assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
841    }
842
843    #[test]
844    fn owner_of_falls_back_to_catch_all() {
845        let content = "* @default\n/src/ @frontend\n";
846        let co = CodeOwners::parse(content).unwrap();
847        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
848    }
849
850    #[test]
851    fn owner_of_no_match_returns_none() {
852        let content = "/src/ @frontend\n";
853        let co = CodeOwners::parse(content).unwrap();
854        assert_eq!(co.owner_of(Path::new("README.md")), None);
855    }
856
857    #[test]
858    fn owner_of_extension_glob() {
859        let content = "*.rs @rust-team\n*.ts @ts-team\n";
860        let co = CodeOwners::parse(content).unwrap();
861        assert_eq!(co.owner_of(Path::new("src/lib.rs")), Some("@rust-team"));
862        assert_eq!(
863            co.owner_of(Path::new("packages/ui/Button.ts")),
864            Some("@ts-team")
865        );
866    }
867
868    #[test]
869    fn owner_of_nested_directory() {
870        let content = "* @default\n/packages/auth/ @auth-team\n";
871        let co = CodeOwners::parse(content).unwrap();
872        assert_eq!(
873            co.owner_of(Path::new("packages/auth/src/login.ts")),
874            Some("@auth-team")
875        );
876        assert_eq!(
877            co.owner_of(Path::new("packages/ui/Button.ts")),
878            Some("@default")
879        );
880    }
881
882    #[test]
883    fn owner_of_specific_overrides_general() {
884        let content = "\
885            * @default\n\
886            /src/ @frontend\n\
887            /src/api/ @backend\n\
888        ";
889        let co = CodeOwners::parse(content).unwrap();
890        assert_eq!(
891            co.owner_of(Path::new("src/api/routes.ts")),
892            Some("@backend")
893        );
894        assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
895    }
896
897    #[test]
898    fn match_path_returns_owner_and_pattern() {
899        let content = "* @default\n/src/ @frontend\n*.rs @rust-team\n";
900        let co = CodeOwners::parse(content).unwrap();
901        assert_eq!(
902            co.match_path(Path::new("src/app.ts"))
903                .map(|m| (m.owner, m.pattern)),
904            Some((Some("@frontend"), "/src/"))
905        );
906        assert_eq!(
907            co.match_path(Path::new("src/lib.rs"))
908                .map(|m| (m.owner, m.pattern)),
909            Some((Some("@rust-team"), "*.rs"))
910        );
911        assert_eq!(
912            co.match_path(Path::new("README.md"))
913                .map(|m| (m.owner, m.pattern)),
914            Some((Some("@default"), "*"))
915        );
916    }
917
918    #[test]
919    fn match_path_no_match() {
920        let content = "/src/ @frontend\n";
921        let co = CodeOwners::parse(content).unwrap();
922        assert_eq!(co.match_path(Path::new("README.md")), None);
923    }
924
925    #[test]
926    fn directory_group_simple() {
927        assert_eq!(directory_group(Path::new("src/utils/index.ts")), "src");
928    }
929
930    #[test]
931    fn directory_group_root_file() {
932        assert_eq!(directory_group(Path::new("index.ts")), "index.ts");
933    }
934
935    #[test]
936    fn directory_group_monorepo() {
937        assert_eq!(
938            directory_group(Path::new("packages/auth/src/login.ts")),
939            "packages"
940        );
941    }
942
943    #[test]
944    fn discover_nonexistent_root() {
945        let result = CodeOwners::discover(Path::new("/nonexistent/path"));
946        assert!(result.is_err());
947        let err = result.unwrap_err();
948        assert!(err.contains("no CODEOWNERS file found"));
949        assert!(err.contains("--group-by directory"));
950    }
951
952    #[cfg(unix)]
953    #[test]
954    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
955    fn codeowners_link_out_of_the_root_is_refused() {
956        let dir = tempfile::tempdir().unwrap();
957        let root = dir.path().join("project");
958        std::fs::create_dir(&root).unwrap();
959        std::fs::write(dir.path().join("OWNERS"), "* @outside-owner\n").unwrap();
960        std::os::unix::fs::symlink(dir.path().join("OWNERS"), root.join("CODEOWNERS")).unwrap();
961
962        let err = CodeOwners::discover(&root).unwrap_err();
963        assert!(err.contains("no CODEOWNERS file found"), "{err}");
964        let err = CodeOwners::load(&root, Some("CODEOWNERS")).unwrap_err();
965        assert!(err.contains("outside"), "{err}");
966    }
967
968    #[test]
969    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
970    fn a_package_config_can_name_the_codeowners_file_of_the_repository() {
971        let dir = tempfile::tempdir().unwrap();
972        let top = dir.path().join("repo");
973        let package = top.join("packages/app");
974        std::fs::create_dir_all(&package).unwrap();
975        std::fs::create_dir_all(top.join(".git")).unwrap();
976        std::fs::create_dir_all(top.join(".github")).unwrap();
977        std::fs::write(top.join(".github/CODEOWNERS"), "* @repo-owner\n").unwrap();
978        std::fs::write(dir.path().join("CODEOWNERS"), "* @outside-owner\n").unwrap();
979
980        let owners = CodeOwners::load(&package, Some("../../.github/CODEOWNERS")).unwrap();
981        assert_eq!(owners.owner_of(Path::new("a.ts")), Some("@repo-owner"));
982        let err = CodeOwners::load(&package, Some("../../../CODEOWNERS")).unwrap_err();
983        assert!(err.contains("outside"), "{err}");
984    }
985
986    #[test]
987    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
988    fn a_codeowners_read_error_omits_a_value_from_an_outside_config_file() {
989        let dir = tempfile::tempdir().unwrap();
990        let root = dir.path().join("project");
991        std::fs::create_dir_all(root.join(".git")).unwrap();
992        std::fs::write(
993            dir.path().join("outside.json"),
994            r#"{"codeowners": "owners-7531/CODEOWNERS"}"#,
995        )
996        .unwrap();
997        std::fs::write(
998            root.join(".fallowrc.json"),
999            r#"{"extends": "../outside.json"}"#,
1000        )
1001        .unwrap();
1002        let file = crate::project_config::load_config_file(
1003            &root,
1004            None,
1005            crate::project_config::ConfigFileOptions::default(),
1006        )
1007        .unwrap();
1008        let value = file.config.codeowners.unwrap();
1009
1010        let err = CodeOwners::load(&root, Some(&value)).unwrap_err();
1011        assert!(!err.contains("owners-7531"), "{err}");
1012        assert!(err.contains("codeowners"), "{err}");
1013        assert!(err.contains("outside.json"), "{err}");
1014
1015        // A value that the project sets keeps its text.
1016        std::fs::write(
1017            root.join(".fallowrc.json"),
1018            r#"{"codeowners": "owners-7531/CODEOWNERS"}"#,
1019        )
1020        .unwrap();
1021        crate::project_config::load_config_file(
1022            &root,
1023            None,
1024            crate::project_config::ConfigFileOptions::default(),
1025        )
1026        .unwrap();
1027        let err = CodeOwners::load(&root, Some(&value)).unwrap_err();
1028        assert!(err.contains("owners-7531"), "{err}");
1029    }
1030
1031    #[cfg(unix)]
1032    #[test]
1033    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1034    fn a_dangling_root_codeowners_link_falls_back_to_the_github_file() {
1035        let dir = tempfile::tempdir().unwrap();
1036        let root = dir.path();
1037        std::os::unix::fs::symlink("missing-owners", root.join("CODEOWNERS")).unwrap();
1038        std::fs::create_dir(root.join(".github")).unwrap();
1039        std::fs::write(root.join(".github/CODEOWNERS"), "* @github-owner\n").unwrap();
1040
1041        let owners = CodeOwners::discover(root).unwrap();
1042        assert_eq!(
1043            owners.owner_of(Path::new("src/a.ts")),
1044            Some("@github-owner")
1045        );
1046    }
1047
1048    #[test]
1049    fn from_file_nonexistent() {
1050        let result = CodeOwners::from_file(Path::new("/nonexistent/CODEOWNERS"));
1051        assert!(result.is_err());
1052    }
1053
1054    #[test]
1055    fn from_file_real_codeowners() {
1056        let root = std::path::PathBuf::from(
1057            std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
1058        )
1059        .parent()
1060        .unwrap()
1061        .parent()
1062        .unwrap()
1063        .to_path_buf();
1064        let path = root.join(".github/CODEOWNERS");
1065        if path.exists() {
1066            let co = CodeOwners::from_file(&path).unwrap();
1067            assert_eq!(
1068                co.owner_of(Path::new(".claude/rules/detection.md")),
1069                Some("@bartwaardenburg")
1070            );
1071        }
1072    }
1073
1074    #[test]
1075    fn email_owner() {
1076        let content = "*.js user@example.com\n";
1077        let co = CodeOwners::parse(content).unwrap();
1078        assert_eq!(co.owner_of(Path::new("index.js")), Some("user@example.com"));
1079    }
1080
1081    #[test]
1082    fn team_owner() {
1083        let content = "*.ts @org/frontend-team\n";
1084        let co = CodeOwners::parse(content).unwrap();
1085        assert_eq!(co.owner_of(Path::new("app.ts")), Some("@org/frontend-team"));
1086    }
1087
1088    #[test]
1089    fn gitlab_section_header_skipped_as_rule() {
1090        let content = "[Section Name]\n*.ts @owner\n";
1091        let co = CodeOwners::parse(content).unwrap();
1092        assert_eq!(co.rules.len(), 1);
1093        assert_eq!(co.owner_of(Path::new("app.ts")), Some("@owner"));
1094    }
1095
1096    #[test]
1097    fn gitlab_optional_section_header_skipped() {
1098        let content = "^[Optional Section]\n*.ts @owner\n";
1099        let co = CodeOwners::parse(content).unwrap();
1100        assert_eq!(co.rules.len(), 1);
1101    }
1102
1103    #[test]
1104    fn gitlab_section_header_with_approval_count_skipped() {
1105        let content = "[Section Name][2]\n*.ts @owner\n";
1106        let co = CodeOwners::parse(content).unwrap();
1107        assert_eq!(co.rules.len(), 1);
1108    }
1109
1110    #[test]
1111    fn gitlab_optional_section_with_approval_count_skipped() {
1112        let content = "^[Section Name][3] @fallback-team\nfoo/\n";
1113        let co = CodeOwners::parse(content).unwrap();
1114        assert_eq!(co.rules.len(), 1);
1115        assert_eq!(co.owner_of(Path::new("foo/bar.ts")), Some("@fallback-team"));
1116    }
1117
1118    #[test]
1119    fn gitlab_section_default_owners_inherited() {
1120        let content = "\
1121            [Utilities] @utils-team\n\
1122            src/utils/\n\
1123            [UI Components] @ui-team\n\
1124            src/components/\n\
1125        ";
1126        let co = CodeOwners::parse(content).unwrap();
1127        assert_eq!(co.rules.len(), 2);
1128        assert_eq!(
1129            co.owner_of(Path::new("src/utils/greet.ts")),
1130            Some("@utils-team")
1131        );
1132        assert_eq!(
1133            co.owner_of(Path::new("src/components/button.ts")),
1134            Some("@ui-team")
1135        );
1136    }
1137
1138    #[test]
1139    fn gitlab_inline_owner_overrides_section_default() {
1140        let content = "\
1141            [Section] @section-owner\n\
1142            src/generic/\n\
1143            src/special/ @special-owner\n\
1144        ";
1145        let co = CodeOwners::parse(content).unwrap();
1146        assert_eq!(
1147            co.owner_of(Path::new("src/generic/a.ts")),
1148            Some("@section-owner")
1149        );
1150        assert_eq!(
1151            co.owner_of(Path::new("src/special/a.ts")),
1152            Some("@special-owner")
1153        );
1154    }
1155
1156    #[test]
1157    fn gitlab_section_defaults_reset_between_sections() {
1158        let content = "\
1159            [Section1] @team-a\n\
1160            foo/\n\
1161            [Section2]\n\
1162            bar/\n\
1163        ";
1164        let co = CodeOwners::parse(content).unwrap();
1165        assert_eq!(co.rules.len(), 1);
1166        assert_eq!(co.owner_of(Path::new("foo/x.ts")), Some("@team-a"));
1167        assert_eq!(co.owner_of(Path::new("bar/x.ts")), None);
1168    }
1169
1170    #[test]
1171    fn gitlab_section_header_multiple_default_owners_uses_first() {
1172        let content = "[Section] @first @second\nfoo/\n";
1173        let co = CodeOwners::parse(content).unwrap();
1174        assert_eq!(co.owner_of(Path::new("foo/a.ts")), Some("@first"));
1175    }
1176
1177    #[test]
1178    fn gitlab_rules_before_first_section_retain_inline_owners() {
1179        let content = "\
1180            * @default-owner\n\
1181            [Utilities] @utils-team\n\
1182            src/utils/\n\
1183        ";
1184        let co = CodeOwners::parse(content).unwrap();
1185        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
1186        assert_eq!(
1187            co.owner_of(Path::new("src/utils/greet.ts")),
1188            Some("@utils-team")
1189        );
1190    }
1191
1192    #[test]
1193    fn gitlab_issue_127_reproduction() {
1194        let content = "\
1195# Default section (no header, rules before first section)
1196* @default-owner
1197
1198[Utilities] @utils-team
1199src/utils/
1200
1201[UI Components] @ui-team
1202src/components/
1203";
1204        let co = CodeOwners::parse(content).unwrap();
1205        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
1206        assert_eq!(
1207            co.owner_of(Path::new("src/utils/greet.ts")),
1208            Some("@utils-team")
1209        );
1210        assert_eq!(
1211            co.owner_of(Path::new("src/components/button.ts")),
1212            Some("@ui-team")
1213        );
1214    }
1215
1216    #[test]
1217    fn gitlab_negation_last_match_clears_ownership() {
1218        let content = "\
1219            * @default\n\
1220            !src/generated/\n\
1221        ";
1222        let co = CodeOwners::parse(content).unwrap();
1223        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
1224        assert_eq!(co.owner_of(Path::new("src/generated/bundle.js")), None);
1225    }
1226
1227    #[test]
1228    fn gitlab_negation_only_clears_when_last_match() {
1229        let content = "\
1230            * @default\n\
1231            !src/\n\
1232            /src/special/ @special\n\
1233        ";
1234        let co = CodeOwners::parse(content).unwrap();
1235        assert_eq!(co.owner_of(Path::new("src/foo.ts")), None);
1236        assert_eq!(co.owner_of(Path::new("src/special/a.ts")), Some("@special"));
1237    }
1238
1239    #[test]
1240    fn gitlab_negation_owner_and_rule_returns_none() {
1241        let content = "* @default\n!src/vendor/\n";
1242        let co = CodeOwners::parse(content).unwrap();
1243        assert_eq!(
1244            co.match_path(Path::new("README.md"))
1245                .map(|m| (m.owner, m.pattern)),
1246            Some((Some("@default"), "*"))
1247        );
1248        let excluded = co.match_path(Path::new("src/vendor/lib.js"));
1249        assert!(excluded.is_some());
1250        assert_eq!(excluded.and_then(|m| m.owner), None);
1251    }
1252
1253    #[test]
1254    fn escaped_space_stays_in_pattern() {
1255        let content = "* @default\n/docs/Security\\ Release.md @security @release\n";
1256        let co = CodeOwners::parse(content).unwrap();
1257        assert_eq!(
1258            co.match_path(Path::new("docs/Security Release.md"))
1259                .map(|m| (m.owner, m.pattern)),
1260            Some((Some("@security"), "/docs/Security\\ Release.md"))
1261        );
1262        assert_eq!(
1263            co.owner_count_of(Path::new("docs/Security Release.md")),
1264            Some(2)
1265        );
1266        assert_eq!(co.owner_of(Path::new("docs/Security")), Some("@default"));
1267    }
1268
1269    #[test]
1270    fn split_pattern_edge_cases() {
1271        assert_eq!(split_pattern("foo\\\\ @o"), ("foo\\\\", " @o"));
1272        assert_eq!(split_pattern("foo\\\tbar @o"), ("foo\\\tbar", " @o"));
1273        assert_eq!(
1274            split_pattern("caf\u{e9}\\ menu @o"),
1275            ("caf\u{e9}\\ menu", " @o")
1276        );
1277        assert_eq!(split_pattern("foo\\"), ("foo\\", ""));
1278        assert_eq!(split_pattern("foo\t@o"), ("foo", "\t@o"));
1279    }
1280
1281    #[test]
1282    fn negated_rule_with_escaped_space() {
1283        let content = "* @default\n!docs/Security\\ Release.md\n";
1284        let co = CodeOwners::parse(content).unwrap();
1285        assert_eq!(co.owner_of(Path::new("docs/Security Release.md")), None);
1286        assert_eq!(co.owner_of(Path::new("docs/other.md")), Some("@default"));
1287    }
1288
1289    // GitHub documents that `\#` does not escape a comment. Gitignore
1290    // accepts it, so Fallow reads it as a pattern.
1291    #[test]
1292    fn escaped_hash_is_a_pattern() {
1293        let content = "\\#notes.md @owner\n";
1294        let co = CodeOwners::parse(content).unwrap();
1295        assert_eq!(co.owner_of(Path::new("#notes.md")), Some("@owner"));
1296    }
1297
1298    #[test]
1299    fn parse_section_header_variants() {
1300        assert_eq!(
1301            parse_section_header("[Section]"),
1302            Some(("Section".into(), vec![]))
1303        );
1304        assert_eq!(
1305            parse_section_header("^[Section]"),
1306            Some(("Section".into(), vec![]))
1307        );
1308        assert_eq!(
1309            parse_section_header("[Section][2]"),
1310            Some(("Section".into(), vec![]))
1311        );
1312        assert_eq!(
1313            parse_section_header("^[Section][2]"),
1314            Some(("Section".into(), vec![]))
1315        );
1316        assert_eq!(
1317            parse_section_header("[Section] @a @b"),
1318            Some(("Section".into(), vec!["@a".into(), "@b".into()]))
1319        );
1320        assert_eq!(
1321            parse_section_header("[Section][2] @a"),
1322            Some(("Section".into(), vec!["@a".into()]))
1323        );
1324    }
1325
1326    #[test]
1327    fn parse_section_header_rejects_malformed() {
1328        assert_eq!(parse_section_header("[unclosed"), None);
1329        assert_eq!(parse_section_header("[]"), None);
1330        assert_eq!(parse_section_header("[abc]def @owner"), None);
1331        assert_eq!(parse_section_header("[Section][] @owner"), None);
1332        assert_eq!(parse_section_header("[Section][abc] @owner"), None);
1333    }
1334
1335    #[test]
1336    fn has_sections_false_without_headers() {
1337        let co = CodeOwners::parse("* @default\n/src/ @frontend\n").unwrap();
1338        assert!(!co.has_sections());
1339    }
1340
1341    #[test]
1342    fn has_sections_true_with_headers() {
1343        let co = CodeOwners::parse("[Utilities] @utils\nsrc/utils/\n").unwrap();
1344        assert!(co.has_sections());
1345    }
1346
1347    #[test]
1348    fn match_path_returns_named_section() {
1349        let content = "\
1350            [Billing] @billing-team\n\
1351            src/billing/\n\
1352            [Search] @search-team\n\
1353            src/search/\n\
1354        ";
1355        let co = CodeOwners::parse(content).unwrap();
1356        assert_eq!(
1357            co.match_path(Path::new("src/billing/invoice.ts"))
1358                .map(|m| m.section),
1359            Some(Some("Billing"))
1360        );
1361        assert_eq!(
1362            co.match_path(Path::new("src/search/indexer.ts"))
1363                .map(|m| m.section),
1364            Some(Some("Search"))
1365        );
1366    }
1367
1368    #[test]
1369    fn match_path_returns_no_section_for_pre_section_rule() {
1370        let content = "\
1371            * @default\n\
1372            [Billing] @billing-team\n\
1373            src/billing/\n\
1374        ";
1375        let co = CodeOwners::parse(content).unwrap();
1376        assert_eq!(
1377            co.match_path(Path::new("README.md")).map(|m| m.section),
1378            Some(None)
1379        );
1380        assert_eq!(
1381            co.match_path(Path::new("src/billing/invoice.ts"))
1382                .map(|m| m.section),
1383            Some(Some("Billing"))
1384        );
1385    }
1386
1387    #[test]
1388    fn match_path_returns_none_for_unmatched_path() {
1389        let content = "[Billing] @billing-team\nsrc/billing/\n";
1390        let co = CodeOwners::parse(content).unwrap();
1391        assert_eq!(co.match_path(Path::new("src/other/x.ts")), None);
1392    }
1393
1394    #[test]
1395    fn match_path_returns_no_owner_for_negation_last_match() {
1396        let content = "\
1397            [Billing] @billing-team\n\
1398            src/billing/\n\
1399            !src/billing/vendor/\n\
1400        ";
1401        let co = CodeOwners::parse(content).unwrap();
1402        assert_eq!(
1403            co.match_path(Path::new("src/billing/invoice.ts"))
1404                .map(|m| m.section),
1405            Some(Some("Billing"))
1406        );
1407        let excluded = co.match_path(Path::new("src/billing/vendor/lib.js"));
1408        assert!(excluded.is_some());
1409        assert_eq!(excluded.and_then(|m| m.owner), None);
1410    }
1411
1412    #[test]
1413    fn match_path_returns_section_defaults() {
1414        let content = "\
1415            [Billing] @core-reviewers @alice\n\
1416            src/billing/\n\
1417        ";
1418        let co = CodeOwners::parse(content).unwrap();
1419        let (section, owners) = co
1420            .match_path(Path::new("src/billing/invoice.ts"))
1421            .map(|m| (m.section, m.section_owners))
1422            .unwrap();
1423        assert_eq!(section, Some("Billing"));
1424        assert_eq!(
1425            owners,
1426            &["@core-reviewers".to_string(), "@alice".to_string()]
1427        );
1428    }
1429
1430    #[test]
1431    fn match_path_same_owners_distinct_sections() {
1432        let content = "\
1433            [billing] @core-reviewers @alice @bob\n\
1434            src/billing/\n\
1435            [notifications] @core-reviewers @alice @bob\n\
1436            src/notifications/\n\
1437        ";
1438        let co = CodeOwners::parse(content).unwrap();
1439        let (billing_sec, _) = co
1440            .match_path(Path::new("src/billing/invoice.ts"))
1441            .map(|m| (m.section, m.section_owners))
1442            .unwrap();
1443        let (notifications_sec, _) = co
1444            .match_path(Path::new("src/notifications/email.ts"))
1445            .map(|m| (m.section, m.section_owners))
1446            .unwrap();
1447        assert_eq!(billing_sec, Some("billing"));
1448        assert_eq!(notifications_sec, Some("notifications"));
1449    }
1450
1451    #[test]
1452    fn match_path_empty_owners_for_pre_section_rule() {
1453        let content = "* @default\n[Billing]\nsrc/billing/ @billing\n";
1454        let co = CodeOwners::parse(content).unwrap();
1455        let (section, owners) = co
1456            .match_path(Path::new("README.md"))
1457            .map(|m| (m.section, m.section_owners))
1458            .unwrap();
1459        assert_eq!(section, None);
1460        assert!(owners.is_empty());
1461    }
1462
1463    #[test]
1464    fn owner_count_of_counts_all_matched_owners() {
1465        let content = "\
1466            * @default\n\
1467            src/api/ @backend @payments @security\n\
1468            [Frontend] @ui @design\n\
1469            src/ui/\n\
1470            !src/generated/\n\
1471        ";
1472        let co = CodeOwners::parse(content).unwrap();
1473        assert_eq!(co.owner_count_of(Path::new("src/api/payments.ts")), Some(3));
1474        assert_eq!(co.owner_count_of(Path::new("src/ui/button.tsx")), Some(2));
1475        assert_eq!(co.owner_count_of(Path::new("README.md")), Some(1));
1476        assert_eq!(
1477            co.owner_count_of(Path::new("src/generated/types.ts")),
1478            Some(0)
1479        );
1480        assert_eq!(
1481            co.owner_count_of(Path::new("other/generated/types.ts")),
1482            Some(1)
1483        );
1484    }
1485
1486    #[test]
1487    fn non_section_bracket_pattern_parses_as_rule() {
1488        let content = "[abc]def @owner\n";
1489        let co = CodeOwners::parse(content).unwrap();
1490        assert_eq!(co.rules.len(), 1);
1491        assert_eq!(co.owner_of(Path::new("adef")), Some("@owner"));
1492    }
1493
1494    #[test]
1495    fn pattern_without_trailing_slash_owns_directory_contents() {
1496        let content = "\
1497            src/platform/packages/shared/kbn-try-in-console @elastic/search\n\
1498            /docs @docs-team\n\
1499        ";
1500        let co = CodeOwners::parse(content).unwrap();
1501        assert_eq!(
1502            co.owner_of(Path::new(
1503                "src/platform/packages/shared/kbn-try-in-console/index.ts"
1504            )),
1505            Some("@elastic/search")
1506        );
1507        assert_eq!(
1508            co.owner_of(Path::new(
1509                "src/platform/packages/shared/kbn-try-in-console/src/components/a.tsx"
1510            )),
1511            Some("@elastic/search")
1512        );
1513        assert_eq!(
1514            co.owner_of(Path::new("docs/guide/intro.md")),
1515            Some("@docs-team")
1516        );
1517        assert_eq!(
1518            co.match_path(Path::new("docs/guide/intro.md"))
1519                .map(|m| (m.owner, m.pattern)),
1520            Some((Some("@docs-team"), "/docs"))
1521        );
1522        assert_eq!(co.owner_count_of(Path::new("docs/a.md")), Some(1));
1523    }
1524
1525    #[test]
1526    fn pattern_without_trailing_slash_still_matches_a_file() {
1527        let co = CodeOwners::parse("/package.json @root\nMakefile @build\n").unwrap();
1528        assert_eq!(co.owner_of(Path::new("package.json")), Some("@root"));
1529        assert_eq!(co.owner_of(Path::new("tools/Makefile")), Some("@build"));
1530    }
1531
1532    #[test]
1533    fn pattern_without_trailing_slash_does_not_match_sibling_prefix() {
1534        let co = CodeOwners::parse("/docs @docs-team\n").unwrap();
1535        assert_eq!(co.owner_of(Path::new("docs-old/a.md")), None);
1536        assert_eq!(co.owner_of(Path::new("docs.md")), None);
1537    }
1538
1539    #[test]
1540    fn directory_pattern_keeps_last_match_wins_order() {
1541        let content = "\
1542            /src @general\n\
1543            /src/lib @lib\n\
1544            /src/lib/legacy.ts @legacy\n\
1545        ";
1546        let co = CodeOwners::parse(content).unwrap();
1547        assert_eq!(co.owner_of(Path::new("src/main.ts")), Some("@general"));
1548        assert_eq!(co.owner_of(Path::new("src/lib/a/b.ts")), Some("@lib"));
1549        assert_eq!(co.owner_of(Path::new("src/lib/legacy.ts")), Some("@legacy"));
1550
1551        let reversed = "\
1552            /src/lib @lib\n\
1553            /src @general\n\
1554        ";
1555        let co = CodeOwners::parse(reversed).unwrap();
1556        assert_eq!(co.owner_of(Path::new("src/lib/a/b.ts")), Some("@general"));
1557    }
1558
1559    #[test]
1560    fn trailing_star_matches_direct_children_only() {
1561        let co = CodeOwners::parse("* @default\ndocs/* @docs-team\n").unwrap();
1562        assert_eq!(
1563            co.owner_of(Path::new("docs/getting-started.md")),
1564            Some("@docs-team")
1565        );
1566        assert_eq!(
1567            co.owner_of(Path::new("docs/build-app/troubleshooting.md")),
1568            Some("@default")
1569        );
1570    }
1571
1572    #[test]
1573    fn root_star_owns_root_level_files_only() {
1574        // GitHub matches `/*` like `docs/*`: direct children only. A
1575        // catch-all for the whole repository needs `*`.
1576        let co = CodeOwners::parse("/* @root\n").unwrap();
1577        assert_eq!(co.owner_of(Path::new("package.json")), Some("@root"));
1578        assert_eq!(co.owner_of(Path::new("src/index.ts")), None);
1579
1580        let co = CodeOwners::parse("* @all\n").unwrap();
1581        assert_eq!(co.owner_of(Path::new("src/deep/index.ts")), Some("@all"));
1582    }
1583
1584    #[test]
1585    fn single_star_does_not_cross_directories() {
1586        let co = CodeOwners::parse("* @default\n/src/*.ts @ts\n").unwrap();
1587        assert_eq!(co.owner_of(Path::new("src/index.ts")), Some("@ts"));
1588        assert_eq!(co.owner_of(Path::new("src/nested/a.ts")), Some("@default"));
1589    }
1590
1591    #[test]
1592    fn wildcard_name_owns_matching_directory_contents() {
1593        let co = CodeOwners::parse("/fixtures/date_* @data\n").unwrap();
1594        assert_eq!(
1595            co.owner_of(Path::new("fixtures/date_nanos/data.json")),
1596            Some("@data")
1597        );
1598    }
1599
1600    #[test]
1601    fn trailing_double_star_keeps_its_meaning() {
1602        let co = CodeOwners::parse("/build/logs/** @ops\n").unwrap();
1603        assert_eq!(co.owner_of(Path::new("build/logs/a/b.log")), Some("@ops"));
1604        assert_eq!(co.owner_of(Path::new("build/other.log")), None);
1605    }
1606
1607    #[test]
1608    fn unanchored_directory_pattern_matches_at_any_depth() {
1609        let co = CodeOwners::parse("apps/ @apps-team\n").unwrap();
1610        assert_eq!(co.owner_of(Path::new("apps/web/a.ts")), Some("@apps-team"));
1611        assert_eq!(
1612            co.owner_of(Path::new("packages/x/apps/web/a.ts")),
1613            Some("@apps-team")
1614        );
1615    }
1616
1617    #[test]
1618    fn negation_without_trailing_slash_clears_directory_contents() {
1619        let content = "\
1620            * @default\n\
1621            !/src/generated\n\
1622        ";
1623        let co = CodeOwners::parse(content).unwrap();
1624        assert_eq!(co.owner_of(Path::new("src/generated/types.ts")), None);
1625        assert_eq!(
1626            co.owner_count_of(Path::new("src/generated/a/b.ts")),
1627            Some(0)
1628        );
1629        assert_eq!(co.owner_of(Path::new("src/main.ts")), Some("@default"));
1630    }
1631
1632    #[test]
1633    fn gitlab_section_pattern_without_trailing_slash_owns_directory_contents() {
1634        let content = "\
1635            [Frontend] @ui\n\
1636            /src/ui\n\
1637            [Backend] @api\n\
1638            /src/api @api-lead\n\
1639        ";
1640        let co = CodeOwners::parse(content).unwrap();
1641        assert_eq!(
1642            co.match_path(Path::new("src/ui/button/a.tsx")).map(|m| (
1643                m.section,
1644                m.section_owners,
1645                m.pattern
1646            )),
1647            Some((Some("Frontend"), ["@ui".to_string()].as_slice(), "/src/ui"))
1648        );
1649        assert_eq!(
1650            co.match_path(Path::new("src/api/users.ts"))
1651                .map(|m| m.section),
1652            Some(Some("Backend"))
1653        );
1654        assert_eq!(
1655            co.owner_of(Path::new("src/api/users.ts")),
1656            Some("@api-lead")
1657        );
1658    }
1659
1660    #[test]
1661    fn parse_ignores_a_leading_bom() {
1662        for content in ["\u{FEFF}* @team\n", "* @team\n"] {
1663            let co = CodeOwners::parse(content).unwrap();
1664            assert_eq!(co.owner_of(Path::new("src/a.ts")), Some("@team"));
1665            assert_eq!(co.owner_count_of(Path::new("src/a.ts")), Some(1));
1666        }
1667        let co = CodeOwners::parse("\u{FEFF}[Docs] @docs\ndocs/\n").unwrap();
1668        assert!(co.has_sections());
1669        assert_eq!(co.owner_of(Path::new("docs/a.md")), Some("@docs"));
1670    }
1671
1672    fn section_and_owners<'a>(co: &'a CodeOwners, path: &str) -> (Option<&'a str>, Vec<String>) {
1673        let m = co.match_path(Path::new(path)).unwrap();
1674        (m.section, m.section_owners.to_vec())
1675    }
1676
1677    fn owner_list(items: &[&str]) -> Vec<String> {
1678        items.iter().map(|item| (*item).to_string()).collect()
1679    }
1680
1681    #[test]
1682    fn repeated_section_headers_merge_their_default_owners() {
1683        let co = CodeOwners::parse(
1684            "[Team] @alice\nsrc/a/\n!src/a/vendor/\n[Other] @carol\nsrc/c/\n[Team] @bob\nsrc/b/\n",
1685        )
1686        .unwrap();
1687        let team = (Some("Team"), owner_list(&["@alice", "@bob"]));
1688        assert_eq!(section_and_owners(&co, "src/a/x.ts"), team);
1689        assert_eq!(section_and_owners(&co, "src/b/x.ts"), team);
1690        assert_eq!(co.owner_of(Path::new("src/a/x.ts")), Some("@alice"));
1691        assert_eq!(co.owner_of(Path::new("src/b/x.ts")), Some("@bob"));
1692        assert_eq!(co.owner_count_of(Path::new("src/b/x.ts")), Some(1));
1693
1694        let excluded = co.match_path(Path::new("src/a/vendor/x.js")).unwrap();
1695        assert_eq!(excluded.owner, None);
1696        assert_eq!(excluded.owner_count, 0);
1697        assert_eq!(excluded.pattern, "!src/a/vendor/");
1698        assert_eq!(co.owner_count_of(Path::new("src/a/vendor/x.js")), Some(0));
1699        assert_eq!(co.owner_count_of(Path::new("other/x.ts")), None);
1700    }
1701
1702    #[test]
1703    fn repeated_section_headers_merge_without_case() {
1704        let co = CodeOwners::parse("[Docs] @a\ndocs/\n[DOCS] @b\nREADME.md\n").unwrap();
1705        let docs = (Some("Docs"), owner_list(&["@a", "@b"]));
1706        assert_eq!(section_and_owners(&co, "docs/guide.md"), docs);
1707        assert_eq!(section_and_owners(&co, "README.md"), docs);
1708    }
1709
1710    #[test]
1711    fn repeated_section_headers_keep_each_owner_one_time() {
1712        let co = CodeOwners::parse(
1713            "[Team] @alice @bob\nsrc/a/\n[Team]\nsrc/b/ @x\n[Team] @bob @carol\nsrc/c/\n",
1714        )
1715        .unwrap();
1716        let team = (Some("Team"), owner_list(&["@alice", "@bob", "@carol"]));
1717        for path in ["src/a/x.ts", "src/b/x.ts", "src/c/x.ts"] {
1718            assert_eq!(section_and_owners(&co, path), team, "{path}");
1719        }
1720    }
1721
1722    #[test]
1723    fn a_section_header_keeps_each_default_owner_one_time() {
1724        let co = CodeOwners::parse("[Team] @a @b @a\nsrc/\n").unwrap();
1725        assert_eq!(
1726            section_and_owners(&co, "src/x.ts"),
1727            (Some("Team"), owner_list(&["@a", "@b"]))
1728        );
1729        assert_eq!(co.owner_count_of(Path::new("src/x.ts")), Some(3));
1730    }
1731}