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