Skip to main content

fallow_engine/
codeowners.rs

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