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