fallow-cli 2.40.1

CLI for the fallow TypeScript/JavaScript codebase analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! CODEOWNERS file parser and ownership lookup.
//!
//! Parses GitHub/GitLab-style CODEOWNERS files and matches file paths
//! to their owners. Used by `--group-by owner` to group analysis output
//! by team ownership.
//!
//! # Pattern semantics
//!
//! CODEOWNERS patterns follow gitignore-like rules:
//! - `*.js` matches any `.js` file in any directory
//! - `/docs/*` matches files directly in `docs/` (root-anchored)
//! - `docs/` matches everything under `docs/`
//! - Last matching rule wins
//! - First owner on a multi-owner line is the primary owner
//!
//! # GitLab extensions
//!
//! GitLab's CODEOWNERS format is a superset of GitHub's. The following
//! GitLab-only syntax is accepted (though it doesn't affect ownership
//! lookup beyond propagating the default owners within a section):
//!
//! - Section headers: `[Section name]`, `^[Section name]` (optional section),
//!   `[Section name][N]` (N required approvals)
//! - Section default owners: `[Section] @owner1 @owner2`. Pattern lines
//!   inside the section that omit inline owners inherit the section's defaults
//! - Exclusion patterns: `!path` clears ownership for matching files
//!   (GitLab 17.10+). A negation that is the last matching rule for a
//!   file makes it unowned.

use std::path::Path;

use globset::{Glob, GlobSet, GlobSetBuilder};

/// Parsed CODEOWNERS file for ownership lookup.
#[derive(Debug)]
pub struct CodeOwners {
    /// Primary owner per rule, indexed by glob position in the `GlobSet`.
    /// Empty string for negation rules (see `is_negation`).
    owners: Vec<String>,
    /// Original CODEOWNERS pattern per rule (e.g. `/src/` or `*.ts`).
    /// For negations, the raw pattern is prefixed with `!`.
    patterns: Vec<String>,
    /// Whether each rule is a GitLab-style negation (`!path`). A matching
    /// negation as the last-matching rule clears ownership for that file.
    is_negation: Vec<bool>,
    /// Compiled glob patterns for matching.
    globs: GlobSet,
}

/// Standard locations to probe for a CODEOWNERS file, in priority order.
///
/// Order: root catch-all → GitHub → GitLab → GitHub legacy (`docs/`).
const PROBE_PATHS: &[&str] = &[
    "CODEOWNERS",
    ".github/CODEOWNERS",
    ".gitlab/CODEOWNERS",
    "docs/CODEOWNERS",
];

/// Label for files that match no CODEOWNERS rule.
pub const UNOWNED_LABEL: &str = "(unowned)";

impl CodeOwners {
    /// Load and parse a CODEOWNERS file from the given path.
    pub fn from_file(path: &Path) -> Result<Self, String> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
        Self::parse(&content)
    }

    /// Auto-probe standard CODEOWNERS locations relative to the project root.
    ///
    /// Tries `CODEOWNERS`, `.github/CODEOWNERS`, `.gitlab/CODEOWNERS`, `docs/CODEOWNERS`.
    pub fn discover(root: &Path) -> Result<Self, String> {
        for probe in PROBE_PATHS {
            let path = root.join(probe);
            if path.is_file() {
                return Self::from_file(&path);
            }
        }
        Err(format!(
            "no CODEOWNERS file found (looked for: {}). \
             Create one of these files or use --group-by directory instead",
            PROBE_PATHS.join(", ")
        ))
    }

    /// Load from a config-specified path, or auto-discover.
    pub fn load(root: &Path, config_path: Option<&str>) -> Result<Self, String> {
        if let Some(p) = config_path {
            let path = root.join(p);
            Self::from_file(&path)
        } else {
            Self::discover(root)
        }
    }

    /// Parse CODEOWNERS content into a lookup structure.
    pub(crate) fn parse(content: &str) -> Result<Self, String> {
        let mut builder = GlobSetBuilder::new();
        let mut owners = Vec::new();
        let mut patterns = Vec::new();
        let mut is_negation = Vec::new();
        let mut section_default_owners: Vec<String> = Vec::new();

        for line in content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // GitLab section header: `[Name]`, `^[Name]`, `[Name][N]`, optionally
            // followed by section default owners. Update the running defaults
            // and move on; section headers never produce a rule.
            if let Some(defaults) = parse_section_header(line) {
                section_default_owners = defaults;
                continue;
            }

            // GitLab exclusion pattern: `!path` clears ownership for matching files.
            let (negate, rest) = if let Some(after) = line.strip_prefix('!') {
                (true, after.trim_start())
            } else {
                (false, line)
            };

            let mut parts = rest.split_whitespace();
            let Some(pattern) = parts.next() else {
                continue;
            };
            let first_inline_owner = parts.next();

            let effective_owner: &str = if negate {
                // Negations clear ownership on match, so an owner token is
                // irrelevant. GitLab doesn't require one anyway.
                ""
            } else if let Some(o) = first_inline_owner {
                o
            } else if let Some(o) = section_default_owners.first() {
                o.as_str()
            } else {
                // Pattern without owners and no section default, skip.
                continue;
            };

            let glob_pattern = translate_pattern(pattern);
            let glob = Glob::new(&glob_pattern)
                .map_err(|e| format!("invalid CODEOWNERS pattern '{pattern}': {e}"))?;

            builder.add(glob);
            owners.push(effective_owner.to_string());
            patterns.push(if negate {
                format!("!{pattern}")
            } else {
                pattern.to_string()
            });
            is_negation.push(negate);
        }

        let globs = builder
            .build()
            .map_err(|e| format!("failed to compile CODEOWNERS patterns: {e}"))?;

        Ok(Self {
            owners,
            patterns,
            is_negation,
            globs,
        })
    }

    /// Look up the primary owner of a file path (relative to project root).
    ///
    /// Returns the first owner from the last matching CODEOWNERS rule,
    /// or `None` if no rule matches or the last matching rule is a
    /// GitLab-style exclusion (`!path`).
    pub fn owner_of(&self, relative_path: &Path) -> Option<&str> {
        let matches = self.globs.matches(relative_path);
        // Last match wins: highest index = last rule in file order
        matches.iter().max().and_then(|&idx| {
            if self.is_negation[idx] {
                None
            } else {
                Some(self.owners[idx].as_str())
            }
        })
    }

    /// Look up the primary owner and the original CODEOWNERS pattern for a path.
    ///
    /// Returns `(owner, pattern)` from the last matching rule, or `None` if
    /// no rule matches or the last matching rule is a GitLab-style exclusion.
    /// The pattern is the raw string from the CODEOWNERS file (e.g. `/src/`
    /// or `*.ts`).
    pub fn owner_and_rule_of(&self, relative_path: &Path) -> Option<(&str, &str)> {
        let matches = self.globs.matches(relative_path);
        matches.iter().max().and_then(|&idx| {
            if self.is_negation[idx] {
                None
            } else {
                Some((self.owners[idx].as_str(), self.patterns[idx].as_str()))
            }
        })
    }
}

/// Parse a GitLab CODEOWNERS section header.
///
/// Recognized forms (all optionally prefixed with `^` for optional sections):
/// - `[Section name]`
/// - `[Section name][N]` (N required approvals)
/// - `[Section name] @owner1 @owner2` (section default owners)
/// - `^[Section name][N] @owner` (any combination of the above)
///
/// Returns `Some(default_owners)` if the line is a well-formed section header
/// (the returned vec is empty when the header declares no default owners),
/// or `None` when the line is not a section header and should be parsed as a
/// rule instead. Detection is strict: a line like `[abc]def @owner` that has
/// non-whitespace content directly after the closing `]` is not treated as a
/// section header, so legacy GitHub CODEOWNERS patterns continue to parse.
fn parse_section_header(line: &str) -> Option<Vec<String>> {
    let rest = line.strip_prefix('^').unwrap_or(line);
    let rest = rest.strip_prefix('[')?;
    let close = rest.find(']')?;
    let name = &rest[..close];
    if name.is_empty() {
        return None;
    }
    let mut after = &rest[close + 1..];

    // Optional `[N]` approval count.
    if let Some(inner) = after.strip_prefix('[') {
        let n_close = inner.find(']')?;
        let count = &inner[..n_close];
        if count.is_empty() || !count.chars().all(|c| c.is_ascii_digit()) {
            return None;
        }
        after = &inner[n_close + 1..];
    }

    // The remainder must be empty or start with whitespace. Otherwise this
    // line isn't a section header, e.g. `[abc]def @owner` stays a rule.
    if !after.is_empty() && !after.starts_with(char::is_whitespace) {
        return None;
    }

    Some(after.split_whitespace().map(String::from).collect())
}

/// Translate a CODEOWNERS pattern to a `globset`-compatible glob pattern.
///
/// CODEOWNERS uses gitignore-like semantics:
/// - Leading `/` anchors to root (stripped for globset)
/// - Trailing `/` means directory contents (`dir/` → `dir/**`)
/// - No `/` in pattern: matches in any directory (`*.js` → `**/*.js`)
/// - Contains `/` (non-trailing): root-relative as-is
fn translate_pattern(pattern: &str) -> String {
    // Strip leading `/` — globset matches from root by default
    let (anchored, rest) = if let Some(p) = pattern.strip_prefix('/') {
        (true, p)
    } else {
        (false, pattern)
    };

    // Trailing `/` means directory contents
    let expanded = if let Some(p) = rest.strip_suffix('/') {
        format!("{p}/**")
    } else {
        rest.to_string()
    };

    // If not anchored and no directory separator, match in any directory
    if !anchored && !expanded.contains('/') {
        format!("**/{expanded}")
    } else {
        expanded
    }
}

/// Extract the first path component for `--group-by directory` grouping.
///
/// Returns the first directory segment of a relative path.
/// For monorepo structures (`packages/auth/...`), returns `packages`.
pub fn directory_group(relative_path: &Path) -> &str {
    let s = relative_path.to_str().unwrap_or("");
    // Use forward-slash normalized path
    let s = if s.contains('\\') {
        // Windows paths: handled by caller normalizing, but be safe
        return s.split(['/', '\\']).next().unwrap_or(s);
    } else {
        s
    };

    match s.find('/') {
        Some(pos) => &s[..pos],
        None => s, // Root-level file
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    // ── translate_pattern ──────────────────────────────────────────

    #[test]
    fn translate_bare_glob() {
        assert_eq!(translate_pattern("*.js"), "**/*.js");
    }

    #[test]
    fn translate_rooted_pattern() {
        assert_eq!(translate_pattern("/docs/*"), "docs/*");
    }

    #[test]
    fn translate_directory_pattern() {
        assert_eq!(translate_pattern("docs/"), "docs/**");
    }

    #[test]
    fn translate_rooted_directory() {
        assert_eq!(translate_pattern("/src/app/"), "src/app/**");
    }

    #[test]
    fn translate_path_with_slash() {
        assert_eq!(translate_pattern("src/utils/*.ts"), "src/utils/*.ts");
    }

    #[test]
    fn translate_double_star() {
        // Pattern already contains `/`, so it's root-relative — no extra prefix
        assert_eq!(translate_pattern("**/test_*.py"), "**/test_*.py");
    }

    #[test]
    fn translate_single_file() {
        assert_eq!(translate_pattern("Makefile"), "**/Makefile");
    }

    // ── parse ──────────────────────────────────────────────────────

    #[test]
    fn parse_simple_codeowners() {
        let content = "* @global-owner\n/src/ @frontend\n*.rs @rust-team\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 3);
    }

    #[test]
    fn parse_skips_comments_and_blanks() {
        let content = "# Comment\n\n* @owner\n  # Indented comment\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
    }

    #[test]
    fn parse_multi_owner_takes_first() {
        let content = "*.ts @team-a @team-b @team-c\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners[0], "@team-a");
    }

    #[test]
    fn parse_skips_pattern_without_owner() {
        let content = "*.ts\n*.js @owner\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
        assert_eq!(co.owners[0], "@owner");
    }

    #[test]
    fn parse_empty_content() {
        let co = CodeOwners::parse("").unwrap();
        assert_eq!(co.owner_of(Path::new("anything.ts")), None);
    }

    // ── owner_of ───────────────────────────────────────────────────

    #[test]
    fn owner_of_last_match_wins() {
        let content = "* @default\n/src/ @frontend\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
    }

    #[test]
    fn owner_of_falls_back_to_catch_all() {
        let content = "* @default\n/src/ @frontend\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
    }

    #[test]
    fn owner_of_no_match_returns_none() {
        let content = "/src/ @frontend\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("README.md")), None);
    }

    #[test]
    fn owner_of_extension_glob() {
        let content = "*.rs @rust-team\n*.ts @ts-team\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("src/lib.rs")), Some("@rust-team"));
        assert_eq!(
            co.owner_of(Path::new("packages/ui/Button.ts")),
            Some("@ts-team")
        );
    }

    #[test]
    fn owner_of_nested_directory() {
        let content = "* @default\n/packages/auth/ @auth-team\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(
            co.owner_of(Path::new("packages/auth/src/login.ts")),
            Some("@auth-team")
        );
        assert_eq!(
            co.owner_of(Path::new("packages/ui/Button.ts")),
            Some("@default")
        );
    }

    #[test]
    fn owner_of_specific_overrides_general() {
        // Later, more specific rule wins
        let content = "\
            * @default\n\
            /src/ @frontend\n\
            /src/api/ @backend\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(
            co.owner_of(Path::new("src/api/routes.ts")),
            Some("@backend")
        );
        assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
    }

    // ── owner_and_rule_of ──────────────────────────────────────────

    #[test]
    fn owner_and_rule_of_returns_owner_and_pattern() {
        let content = "* @default\n/src/ @frontend\n*.rs @rust-team\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(
            co.owner_and_rule_of(Path::new("src/app.ts")),
            Some(("@frontend", "/src/"))
        );
        assert_eq!(
            co.owner_and_rule_of(Path::new("src/lib.rs")),
            Some(("@rust-team", "*.rs"))
        );
        assert_eq!(
            co.owner_and_rule_of(Path::new("README.md")),
            Some(("@default", "*"))
        );
    }

    #[test]
    fn owner_and_rule_of_no_match() {
        let content = "/src/ @frontend\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_and_rule_of(Path::new("README.md")), None);
    }

    // ── directory_group ────────────────────────────────────────────

    #[test]
    fn directory_group_simple() {
        assert_eq!(directory_group(Path::new("src/utils/index.ts")), "src");
    }

    #[test]
    fn directory_group_root_file() {
        assert_eq!(directory_group(Path::new("index.ts")), "index.ts");
    }

    #[test]
    fn directory_group_monorepo() {
        assert_eq!(
            directory_group(Path::new("packages/auth/src/login.ts")),
            "packages"
        );
    }

    // ── discover ───────────────────────────────────────────────────

    #[test]
    fn discover_nonexistent_root() {
        let result = CodeOwners::discover(Path::new("/nonexistent/path"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("no CODEOWNERS file found"));
        assert!(err.contains("--group-by directory"));
    }

    // ── from_file ──────────────────────────────────────────────────

    #[test]
    fn from_file_nonexistent() {
        let result = CodeOwners::from_file(Path::new("/nonexistent/CODEOWNERS"));
        assert!(result.is_err());
    }

    #[test]
    fn from_file_real_codeowners() {
        // Use the project's own CODEOWNERS file
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .unwrap()
            .parent()
            .unwrap()
            .to_path_buf();
        let path = root.join(".github/CODEOWNERS");
        if path.exists() {
            let co = CodeOwners::from_file(&path).unwrap();
            // Our CODEOWNERS has `* @bartwaardenburg`
            assert_eq!(
                co.owner_of(Path::new("src/anything.ts")),
                Some("@bartwaardenburg")
            );
        }
    }

    // ── edge cases ─────────────────────────────────────────────────

    #[test]
    fn email_owner() {
        let content = "*.js user@example.com\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("index.js")), Some("user@example.com"));
    }

    #[test]
    fn team_owner() {
        let content = "*.ts @org/frontend-team\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("app.ts")), Some("@org/frontend-team"));
    }

    // ── GitLab section headers ─────────────────────────────────────

    #[test]
    fn gitlab_section_header_skipped_as_rule() {
        // Previously produced: `invalid CODEOWNERS pattern '[Section'`.
        let content = "[Section Name]\n*.ts @owner\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
        assert_eq!(co.owner_of(Path::new("app.ts")), Some("@owner"));
    }

    #[test]
    fn gitlab_optional_section_header_skipped() {
        let content = "^[Optional Section]\n*.ts @owner\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
    }

    #[test]
    fn gitlab_section_header_with_approval_count_skipped() {
        let content = "[Section Name][2]\n*.ts @owner\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
    }

    #[test]
    fn gitlab_optional_section_with_approval_count_skipped() {
        let content = "^[Section Name][3] @fallback-team\nfoo/\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
        assert_eq!(co.owner_of(Path::new("foo/bar.ts")), Some("@fallback-team"));
    }

    #[test]
    fn gitlab_section_default_owners_inherited() {
        let content = "\
            [Utilities] @utils-team\n\
            src/utils/\n\
            [UI Components] @ui-team\n\
            src/components/\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 2);
        assert_eq!(
            co.owner_of(Path::new("src/utils/greet.ts")),
            Some("@utils-team")
        );
        assert_eq!(
            co.owner_of(Path::new("src/components/button.ts")),
            Some("@ui-team")
        );
    }

    #[test]
    fn gitlab_inline_owner_overrides_section_default() {
        let content = "\
            [Section] @section-owner\n\
            src/generic/\n\
            src/special/ @special-owner\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(
            co.owner_of(Path::new("src/generic/a.ts")),
            Some("@section-owner")
        );
        assert_eq!(
            co.owner_of(Path::new("src/special/a.ts")),
            Some("@special-owner")
        );
    }

    #[test]
    fn gitlab_section_defaults_reset_between_sections() {
        // Section1 declares @team-a. Section2 declares no defaults. A bare
        // pattern inside Section2 inherits nothing and is dropped.
        let content = "\
            [Section1] @team-a\n\
            foo/\n\
            [Section2]\n\
            bar/\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
        assert_eq!(co.owner_of(Path::new("foo/x.ts")), Some("@team-a"));
        assert_eq!(co.owner_of(Path::new("bar/x.ts")), None);
    }

    #[test]
    fn gitlab_section_header_multiple_default_owners_uses_first() {
        let content = "[Section] @first @second\nfoo/\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("foo/a.ts")), Some("@first"));
    }

    #[test]
    fn gitlab_rules_before_first_section_retain_inline_owners() {
        // Matches the reproduction in issue #127: rules before the first
        // section header use their own inline owners.
        let content = "\
            * @default-owner\n\
            [Utilities] @utils-team\n\
            src/utils/\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
        assert_eq!(
            co.owner_of(Path::new("src/utils/greet.ts")),
            Some("@utils-team")
        );
    }

    #[test]
    fn gitlab_issue_127_reproduction() {
        // Verbatim CODEOWNERS from issue #127.
        let content = "\
# Default section (no header, rules before first section)
* @default-owner

[Utilities] @utils-team
src/utils/

[UI Components] @ui-team
src/components/
";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
        assert_eq!(
            co.owner_of(Path::new("src/utils/greet.ts")),
            Some("@utils-team")
        );
        assert_eq!(
            co.owner_of(Path::new("src/components/button.ts")),
            Some("@ui-team")
        );
    }

    // ── GitLab exclusion patterns (negation) ───────────────────────

    #[test]
    fn gitlab_negation_last_match_clears_ownership() {
        let content = "\
            * @default\n\
            !src/generated/\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
        assert_eq!(co.owner_of(Path::new("src/generated/bundle.js")), None);
    }

    #[test]
    fn gitlab_negation_only_clears_when_last_match() {
        // A more specific positive rule after the negation wins again.
        let content = "\
            * @default\n\
            !src/\n\
            /src/special/ @special\n\
        ";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owner_of(Path::new("src/foo.ts")), None);
        assert_eq!(co.owner_of(Path::new("src/special/a.ts")), Some("@special"));
    }

    #[test]
    fn gitlab_negation_owner_and_rule_returns_none() {
        let content = "* @default\n!src/vendor/\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(
            co.owner_and_rule_of(Path::new("README.md")),
            Some(("@default", "*"))
        );
        assert_eq!(co.owner_and_rule_of(Path::new("src/vendor/lib.js")), None);
    }

    // ── section header parser ──────────────────────────────────────

    #[test]
    fn parse_section_header_variants() {
        assert_eq!(parse_section_header("[Section]"), Some(vec![]));
        assert_eq!(parse_section_header("^[Section]"), Some(vec![]));
        assert_eq!(parse_section_header("[Section][2]"), Some(vec![]));
        assert_eq!(parse_section_header("^[Section][2]"), Some(vec![]));
        assert_eq!(
            parse_section_header("[Section] @a @b"),
            Some(vec!["@a".into(), "@b".into()])
        );
        assert_eq!(
            parse_section_header("[Section][2] @a"),
            Some(vec!["@a".into()])
        );
    }

    #[test]
    fn parse_section_header_rejects_malformed() {
        // Not a section header; should parse as a rule elsewhere.
        assert_eq!(parse_section_header("[unclosed"), None);
        assert_eq!(parse_section_header("[]"), None);
        assert_eq!(parse_section_header("[abc]def @owner"), None);
        assert_eq!(parse_section_header("[Section][] @owner"), None);
        assert_eq!(parse_section_header("[Section][abc] @owner"), None);
    }

    #[test]
    fn non_section_bracket_pattern_parses_as_rule() {
        // `[abc]def` is not a section header (non-whitespace after `]`),
        // so it falls through to regular glob parsing as a character class.
        let content = "[abc]def @owner\n";
        let co = CodeOwners::parse(content).unwrap();
        assert_eq!(co.owners.len(), 1);
        assert_eq!(co.owner_of(Path::new("adef")), Some("@owner"));
    }
}