codeowners-parser 0.1.0

Parser, matcher, and validator for GitHub CODEOWNERS files. Position-aware parsing for editor tooling, fast glob matching, and rule-subsumption analysis for dead-code detection.
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Parse CODEOWNERS files into structured lines, with or without positions.
//!
//! Two parse entry points:
//! - [`parse_codeowners_file_with_positions`] — retains character offsets
//!   for every pattern, owner span, and inline comment. Use this for
//!   editor tooling.
//! - [`parse_codeowners_file`] — drops positions, returns only the
//!   logical content. Use this for CLI-style tools that only need to
//!   inspect or rewrite rules.

/// A parsed CODEOWNERS line with character offsets for editor tooling.
#[derive(Debug, Clone)]
pub struct ParsedLine {
    /// 0-indexed line number in the source file.
    pub line_number: u32,
    /// The logical content of the line (rule, comment, or empty).
    pub content: CodeownersLine,
    /// Character offset where the pattern starts (0 for non-rule lines).
    pub pattern_start: u32,
    /// Character offset one past the end of the pattern.
    pub pattern_end: u32,
    /// Character offset where owners start (equals `pattern_end` if no owners).
    pub owners_start: u32,
    /// Character offset of the inline comment's `#`, if any.
    pub comment_start: Option<u32>,
}

/// The logical content of a CODEOWNERS line.
#[derive(Debug, Clone, PartialEq)]
pub enum CodeownersLine {
    /// A comment line (starts with `#`). The stored string includes the `#`.
    Comment(String),
    /// A blank or whitespace-only line.
    Empty,
    /// A rule line: a glob pattern followed by zero or more owners.
    Rule {
        /// The glob pattern, exactly as written (no normalization).
        pattern: String,
        /// Owners assigned to this rule. May be empty.
        owners: Vec<String>,
    },
}

impl std::fmt::Display for CodeownersLine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CodeownersLine::Comment(c) => write!(f, "{}", c),
            CodeownersLine::Empty => Ok(()),
            CodeownersLine::Rule { pattern, owners } => {
                write!(f, "{} {}", pattern, owners.join(" "))
            }
        }
    }
}

/// Parse a CODEOWNERS file into structured lines with position info
pub fn parse_codeowners_file_with_positions(content: &str) -> Vec<ParsedLine> {
    content
        .lines()
        .enumerate()
        .map(|(line_num, line)| {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                ParsedLine {
                    line_number: line_num as u32,
                    content: CodeownersLine::Empty,
                    pattern_start: 0,
                    pattern_end: 0,
                    owners_start: 0,
                    comment_start: None,
                }
            } else if trimmed.starts_with('#') {
                ParsedLine {
                    line_number: line_num as u32,
                    content: CodeownersLine::Comment(line.to_string()),
                    pattern_start: 0,
                    pattern_end: 0,
                    owners_start: 0,
                    comment_start: None,
                }
            } else {
                // Split by whitespace, stopping at # (end-of-line comment)
                let parts: Vec<&str> = line
                    .split_whitespace()
                    .take_while(|part| !part.starts_with('#'))
                    .collect();

                // Find the inline comment position (first # that's a separate whitespace-delimited token)
                let comment_start = find_inline_comment_start(line).map(|pos| pos as u32);

                if parts.is_empty() {
                    ParsedLine {
                        line_number: line_num as u32,
                        content: CodeownersLine::Empty,
                        pattern_start: 0,
                        pattern_end: 0,
                        owners_start: 0,
                        comment_start: None,
                    }
                } else {
                    // Find pattern position
                    let pattern_start = line.find(parts[0]).unwrap_or(0) as u32;
                    let pattern_end = pattern_start + parts[0].len() as u32;
                    // Search after the pattern, not from the start of the line —
                    // an owner that also appears inside its own pattern (say
                    // `api/src api`) would otherwise report the pattern's offset.
                    let owners_start = if parts.len() > 1 {
                        line[pattern_end as usize..]
                            .find(parts[1])
                            .map(|offset| pattern_end + offset as u32)
                            .unwrap_or(pattern_end)
                    } else {
                        pattern_end
                    };

                    ParsedLine {
                        line_number: line_num as u32,
                        content: CodeownersLine::Rule {
                            pattern: parts[0].to_string(),
                            owners: parts[1..].iter().map(|s| s.to_string()).collect(),
                        },
                        pattern_start,
                        pattern_end,
                        owners_start,
                        comment_start,
                    }
                }
            }
        })
        .collect()
}

/// Find the char offset of an inline comment on a rule line.
/// An inline comment starts with `#` that is preceded by whitespace.
pub fn find_inline_comment_start(line: &str) -> Option<usize> {
    let mut in_whitespace = true;
    for (i, c) in line.chars().enumerate() {
        if c == '#' && in_whitespace {
            return Some(i);
        }
        in_whitespace = c == ' ' || c == '\t';
    }
    None
}

/// Parse a CODEOWNERS file into structured lines (without positions)
#[allow(dead_code)]
pub fn parse_codeowners_file(content: &str) -> Vec<CodeownersLine> {
    parse_codeowners_file_with_positions(content)
        .into_iter()
        .map(|p| p.content)
        .collect()
}

/// Write parsed lines back to a string
#[allow(dead_code)]
pub fn serialize_codeowners(lines: &[CodeownersLine]) -> String {
    lines
        .iter()
        .map(|l| l.to_string())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Find the best insertion point for a new pattern
/// Uses heuristics to find a sensible location:
/// 1. Path similarity: near rules with similar directory prefixes
/// 2. Before catch-all rules (*, /**)
/// 3. End of file as fallback
#[allow(dead_code)]
pub fn find_insertion_point(lines: &[CodeownersLine], pattern: &str) -> usize {
    find_insertion_point_with_owner(lines, pattern, None)
}

/// Find the best insertion point considering both path and owner
#[allow(dead_code)]
pub fn find_insertion_point_with_owner(
    lines: &[CodeownersLine],
    pattern: &str,
    owner: Option<&str>,
) -> usize {
    if lines.is_empty() {
        return 0;
    }

    // Extract directory prefix from the pattern (e.g., "/src/foo/bar.rs" -> "/src/foo")
    let pattern_dir = get_directory_prefix(pattern);

    // Track best match by path similarity
    let mut best_path_match: Option<(usize, usize)> = None; // (index, depth)

    // Track owner clusters
    let mut owner_lines: Vec<usize> = Vec::new();

    // Track catch-all position
    let mut catch_all_idx: Option<usize> = None;

    for (idx, line) in lines.iter().enumerate() {
        if let CodeownersLine::Rule {
            pattern: rule_pattern,
            owners,
        } = line
        {
            // Check for catch-all patterns
            if rule_pattern == "*" || rule_pattern == "/*" || rule_pattern == "/**" {
                if catch_all_idx.is_none() {
                    catch_all_idx = Some(idx);
                }
                continue;
            }

            // Check path similarity
            let rule_dir = get_directory_prefix(rule_pattern);
            let common_depth = common_prefix_depth(&pattern_dir, &rule_dir);

            if common_depth > 0 {
                if let Some((_, best_depth)) = best_path_match {
                    if common_depth > best_depth {
                        best_path_match = Some((idx, common_depth));
                    }
                } else {
                    best_path_match = Some((idx, common_depth));
                }
            }

            // Track owner occurrences
            if let Some(target_owner) = owner {
                if owners.iter().any(|o| o == target_owner) {
                    owner_lines.push(idx);
                }
            }
        }
    }

    // Priority 1: Insert after the best path match (similar directory)
    if let Some((idx, _)) = best_path_match {
        // Insert after the matched rule
        return idx + 1;
    }

    // Priority 2: Insert near owner cluster (after last occurrence)
    if let Some(&last_owner_idx) = owner_lines.last() {
        return last_owner_idx + 1;
    }

    // Priority 3: Insert before catch-all rules
    if let Some(idx) = catch_all_idx {
        return idx;
    }

    // Fallback: end of file
    lines.len()
}

/// Extract directory prefix from a pattern
/// "/src/foo/bar.rs" -> "/src/foo"
/// "/src/**/*.rs" -> "/src"
/// "*.js" -> ""
fn get_directory_prefix(pattern: &str) -> String {
    // Remove leading / for comparison
    let p = pattern.strip_prefix('/').unwrap_or(pattern);

    // Find the last path separator before any wildcard
    let mut last_slash = None;
    for (i, c) in p.char_indices() {
        if c == '*' || c == '?' || c == '[' {
            break;
        }
        if c == '/' {
            last_slash = Some(i);
        }
    }

    match last_slash {
        Some(idx) => format!("/{}", &p[..idx]),
        None => {
            // Check if it's a full path to a file (contains /)
            if let Some(idx) = p.rfind('/') {
                format!("/{}", &p[..idx])
            } else {
                String::new()
            }
        }
    }
}

/// Count common directory depth between two paths
/// "/src/foo" and "/src/foo/bar" -> 2 (src, foo)
/// "/src/foo" and "/lib/bar" -> 0
fn common_prefix_depth(a: &str, b: &str) -> usize {
    if a.is_empty() || b.is_empty() {
        return 0;
    }

    let a_parts: Vec<&str> = a.split('/').filter(|s| !s.is_empty()).collect();
    let b_parts: Vec<&str> = b.split('/').filter(|s| !s.is_empty()).collect();

    let mut depth = 0;
    for (ap, bp) in a_parts.iter().zip(b_parts.iter()) {
        if ap == bp {
            depth += 1;
        } else {
            break;
        }
    }
    depth
}

/// Find the @owner at a given character position in a line
#[allow(dead_code)] // Used by LSP only
pub fn find_owner_at_position(line: &str, char_idx: usize) -> Option<String> {
    // Skip comments
    if line.trim_start().starts_with('#') {
        return None;
    }

    // Stop scanning at inline comment boundary
    let scan_end = find_inline_comment_start(line).unwrap_or(line.chars().count());

    // Find all potential owners in the non-comment portion
    let mut owners: Vec<(usize, usize, String)> = Vec::new();
    let mut i = 0;
    let chars: Vec<char> = line.chars().collect();

    while i < chars.len() && i < scan_end {
        if chars[i] == '@' {
            let start = i;
            i += 1;
            // Collect owner chars (alphanumeric, -, /)
            while i < chars.len()
                && (chars[i].is_alphanumeric() || chars[i] == '-' || chars[i] == '/')
            {
                i += 1;
            }
            if i > start + 1 {
                let owner: String = chars[start..i].iter().collect();
                owners.push((start, i, owner));
            }
        } else {
            i += 1;
        }
    }

    // Find which owner the cursor is on
    for (start, end, owner) in owners {
        if char_idx >= start && char_idx < end {
            return Some(owner);
        }
    }

    None
}

/// Format a CODEOWNERS file: normalize rule spacing, preserve comments exactly
pub fn format_codeowners(content: &str) -> String {
    let mut result = Vec::new();
    let mut prev_was_empty = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Preserve blank lines but collapse multiple
        if trimmed.is_empty() {
            if !prev_was_empty && !result.is_empty() {
                result.push(String::new());
            }
            prev_was_empty = true;
            continue;
        }
        prev_was_empty = false;

        // Comments: preserve exactly as-is (people use specific formatting)
        if trimmed.starts_with('#') {
            result.push(line.to_string());
            continue;
        }

        // Rules: normalize spacing between pattern and owners, preserve inline comments
        let parts: Vec<&str> = trimmed
            .split_whitespace()
            .take_while(|part| !part.starts_with('#'))
            .collect();
        if parts.is_empty() {
            continue;
        }

        let pattern = parts[0];
        let owners = &parts[1..];

        // Find inline comment in the original line
        let inline_comment = find_inline_comment_start(line).map(|char_off| {
            line.chars()
                .skip(char_off)
                .collect::<String>()
                .trim_end()
                .to_string()
        });

        let mut formatted = if owners.is_empty() {
            pattern.to_string()
        } else {
            format!("{} {}", pattern, owners.join(" "))
        };

        if let Some(comment) = inline_comment {
            formatted.push(' ');
            formatted.push_str(&comment);
        }

        result.push(formatted);
    }

    // Ensure trailing newline
    let mut output = result.join("\n");
    if !output.is_empty() && !output.ends_with('\n') {
        output.push('\n');
    }
    output
}

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

    #[test]
    fn test_parse_empty_file() {
        let lines = parse_codeowners_file("");
        assert!(lines.is_empty());
    }

    #[test]
    fn test_parse_comment() {
        let lines = parse_codeowners_file("# This is a comment");
        assert_eq!(lines.len(), 1);
        assert!(matches!(&lines[0], CodeownersLine::Comment(c) if c == "# This is a comment"));
    }

    #[test]
    fn test_parse_empty_line() {
        let lines = parse_codeowners_file("\n\n");
        assert_eq!(lines.len(), 2);
        assert!(matches!(lines[0], CodeownersLine::Empty));
        assert!(matches!(lines[1], CodeownersLine::Empty));
    }

    #[test]
    fn test_parse_rule_single_owner() {
        let lines = parse_codeowners_file("*.rs @rustacean");
        assert_eq!(lines.len(), 1);
        match &lines[0] {
            CodeownersLine::Rule { pattern, owners } => {
                assert_eq!(pattern, "*.rs");
                assert_eq!(owners, &vec!["@rustacean".to_string()]);
            }
            _ => panic!("Expected Rule"),
        }
    }

    #[test]
    fn test_parse_rule_single_owner_line_comment() {
        let lines = parse_codeowners_file("*.rs @rustacean # only rust people should touch rust");
        assert_eq!(lines.len(), 1);
        match &lines[0] {
            CodeownersLine::Rule { pattern, owners } => {
                assert_eq!(pattern, "*.rs");
                assert_eq!(owners, &vec!["@rustacean".to_string()]);
            }
            _ => panic!("Expected Rule"),
        }
    }

    #[test]
    fn test_parse_rule_multiple_owners() {
        let lines = parse_codeowners_file("/src/ @user1 @org/team email@test.com");
        assert_eq!(lines.len(), 1);
        match &lines[0] {
            CodeownersLine::Rule { pattern, owners } => {
                assert_eq!(pattern, "/src/");
                assert_eq!(
                    owners,
                    &vec![
                        "@user1".to_string(),
                        "@org/team".to_string(),
                        "email@test.com".to_string()
                    ]
                );
            }
            _ => panic!("Expected Rule"),
        }
    }

    #[test]
    fn test_parse_rule_no_owners() {
        let lines = parse_codeowners_file("/unowned/");
        assert_eq!(lines.len(), 1);
        match &lines[0] {
            CodeownersLine::Rule { pattern, owners } => {
                assert_eq!(pattern, "/unowned/");
                assert!(owners.is_empty());
            }
            _ => panic!("Expected Rule"),
        }
    }

    #[test]
    fn test_parse_with_positions() {
        let lines = parse_codeowners_file_with_positions("*.rs @owner");
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].line_number, 0);
        assert_eq!(lines[0].pattern_start, 0);
        assert_eq!(lines[0].pattern_end, 4);
        assert_eq!(lines[0].owners_start, 5);
    }

    #[test]
    fn test_serialize_roundtrip() {
        let original = "# Comment\n*.rs @owner\n/src/ @team";
        let lines = parse_codeowners_file(original);
        let serialized = serialize_codeowners(&lines);
        assert_eq!(serialized, original);
    }

    #[test]
    fn test_serialize_empty_rule() {
        let lines = vec![CodeownersLine::Rule {
            pattern: "/path/".to_string(),
            owners: vec![],
        }];
        let serialized = serialize_codeowners(&lines);
        assert_eq!(serialized, "/path/ ");
    }

    #[test]
    fn test_insertion_point_path_similarity() {
        let lines = parse_codeowners_file(
            "/src/api/ @api-team\n/src/api/auth/ @auth-team\n/lib/ @lib-team",
        );
        // New file in /src/api should go after first best path match (/src/api/)
        let idx = find_insertion_point_with_owner(&lines, "/src/api/users.rs", None);
        assert_eq!(idx, 1); // After /src/api/
    }

    #[test]
    fn test_insertion_point_before_catch_all() {
        let lines = parse_codeowners_file("/src/ @team\n* @default");
        // New pattern should go before catch-all
        let idx = find_insertion_point_with_owner(&lines, "/lib/foo.rs", None);
        assert_eq!(idx, 1); // Before *
    }

    #[test]
    fn test_insertion_point_owner_cluster() {
        let lines =
            parse_codeowners_file("/src/ @alice\n/lib/ @bob\n/tests/ @alice\n/docs/ @carol");
        // When owner is specified, prefer inserting near their other rules
        let idx = find_insertion_point_with_owner(&lines, "/bin/tool.rs", Some("@alice"));
        assert_eq!(idx, 3); // After /tests/ @alice
    }

    #[test]
    fn test_insertion_point_empty() {
        let lines: Vec<CodeownersLine> = vec![];
        let idx = find_insertion_point_with_owner(&lines, "/foo/bar.rs", None);
        assert_eq!(idx, 0);
    }

    #[test]
    fn test_get_directory_prefix() {
        assert_eq!(get_directory_prefix("/src/foo/bar.rs"), "/src/foo");
        assert_eq!(get_directory_prefix("/src/**/*.rs"), "/src");
        assert_eq!(get_directory_prefix("*.js"), "");
        assert_eq!(get_directory_prefix("/single.rs"), "");
        assert_eq!(get_directory_prefix("/a/b/c/d.txt"), "/a/b/c");
        // Directory patterns (trailing slash)
        assert_eq!(get_directory_prefix("/src/api/"), "/src/api");
        assert_eq!(get_directory_prefix("/src/api/auth/"), "/src/api/auth");
    }

    #[test]
    fn test_common_prefix_depth() {
        assert_eq!(common_prefix_depth("/src/foo", "/src/foo/bar"), 2);
        assert_eq!(common_prefix_depth("/src/foo", "/src/bar"), 1);
        assert_eq!(common_prefix_depth("/src/foo", "/lib/bar"), 0);
        assert_eq!(common_prefix_depth("", "/src"), 0);
    }

    #[test]
    fn test_find_owner_at_position_basic() {
        let line = "*.rs @owner1 @org/team";
        assert_eq!(find_owner_at_position(line, 5), Some("@owner1".to_string()));
        assert_eq!(find_owner_at_position(line, 6), Some("@owner1".to_string()));
        assert_eq!(
            find_owner_at_position(line, 11),
            Some("@owner1".to_string())
        );
        assert_eq!(
            find_owner_at_position(line, 13),
            Some("@org/team".to_string())
        );
    }

    #[test]
    fn test_find_owner_at_position_outside_owner() {
        let line = "*.rs @owner";
        // On pattern, not owner
        assert_eq!(find_owner_at_position(line, 0), None);
        assert_eq!(find_owner_at_position(line, 3), None);
        // Past end
        assert_eq!(find_owner_at_position(line, 100), None);
    }

    #[test]
    fn test_find_owner_at_position_comment() {
        let line = "# @mention in comment";
        assert_eq!(find_owner_at_position(line, 2), None);
    }

    #[test]
    fn test_find_owner_at_position_indented_comment() {
        let line = "   # @mention in comment";
        assert_eq!(find_owner_at_position(line, 5), None);
    }

    #[test]
    fn test_find_owner_at_position_no_owners() {
        let line = "/unowned/path/";
        assert_eq!(find_owner_at_position(line, 0), None);
        assert_eq!(find_owner_at_position(line, 5), None);
    }

    #[test]
    fn test_find_owner_at_position_just_at_symbol() {
        let line = "*.rs @ @";
        // @ alone (no following chars) shouldn't match
        assert_eq!(find_owner_at_position(line, 5), None);
        assert_eq!(find_owner_at_position(line, 7), None);
    }

    #[test]
    fn test_find_owner_at_position_special_chars() {
        let line = "*.rs @user-name @org/team";
        assert_eq!(
            find_owner_at_position(line, 5),
            Some("@user-name".to_string())
        );
        assert_eq!(
            find_owner_at_position(line, 16),
            Some("@org/team".to_string())
        );
    }

    #[test]
    fn test_format_codeowners_basic() {
        let input = "# Comment\n*.rs    @owner1   @owner2\n/src/   @team";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "# Comment\n*.rs @owner1 @owner2\n/src/ @team\n");
    }

    #[test]
    fn test_format_codeowners_collapse_empty_lines() {
        let input = "*.rs @owner\n\n\n\n/src/ @team";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "*.rs @owner\n\n/src/ @team\n");
    }

    #[test]
    fn test_format_codeowners_preserves_comments() {
        let input = "# This is a special comment    with    spacing\n*.rs @owner";
        let formatted = format_codeowners(input);
        assert!(formatted.contains("# This is a special comment    with    spacing"));
    }

    #[test]
    fn test_format_codeowners_no_owner() {
        let input = "/unowned/";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "/unowned/\n");
    }

    #[test]
    fn test_format_codeowners_empty() {
        let input = "";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "");
    }

    #[test]
    fn test_format_codeowners_leading_empty_lines() {
        let input = "\n\n# Header\n*.rs @owner";
        let formatted = format_codeowners(input);
        // Leading blank lines should not produce output before first content
        assert_eq!(formatted, "# Header\n*.rs @owner\n");
    }

    #[test]
    fn test_codeowners_line_display_comment() {
        let line = CodeownersLine::Comment("# test comment".to_string());
        assert_eq!(format!("{}", line), "# test comment");
    }

    #[test]
    fn test_codeowners_line_display_empty() {
        let line = CodeownersLine::Empty;
        assert_eq!(format!("{}", line), "");
    }

    #[test]
    fn test_codeowners_line_display_rule() {
        let line = CodeownersLine::Rule {
            pattern: "*.rs".to_string(),
            owners: vec!["@alice".to_string(), "@bob".to_string()],
        };
        assert_eq!(format!("{}", line), "*.rs @alice @bob");
    }

    #[test]
    fn test_parse_positions_with_leading_whitespace() {
        let lines = parse_codeowners_file_with_positions("  *.rs @owner");
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].pattern_start, 2);
        assert_eq!(lines[0].pattern_end, 6);
        assert_eq!(lines[0].owners_start, 7);
    }

    #[test]
    fn test_parse_whitespace_only_line() {
        let lines = parse_codeowners_file("   \t   ");
        assert_eq!(lines.len(), 1);
        assert!(matches!(lines[0], CodeownersLine::Empty));
    }

    #[test]
    fn test_insertion_point_only_comments() {
        let lines = parse_codeowners_file("# Header\n# Another comment");
        let idx = find_insertion_point(&lines, "/foo.rs");
        // Should insert at end when no rules
        assert_eq!(idx, 2);
    }

    #[test]
    fn test_insertion_point_prefers_deeper_path_match() {
        let lines = parse_codeowners_file("/src/ @team1\n/src/api/ @team2\n/src/api/v2/ @team3");
        // Should prefer /src/api/v2 for a file in /src/api/v2/
        let idx = find_insertion_point(&lines, "/src/api/v2/users.rs");
        assert_eq!(idx, 3); // After /src/api/v2/
    }

    #[test]
    fn test_insertion_point_catch_all_variants() {
        // Test with /* catch-all
        let lines = parse_codeowners_file("/src/ @team\n/* @default");
        let idx = find_insertion_point(&lines, "/lib/foo.rs");
        assert_eq!(idx, 1);

        // Test with /** catch-all
        let lines2 = parse_codeowners_file("/src/ @team\n/** @default");
        let idx2 = find_insertion_point(&lines2, "/lib/foo.rs");
        assert_eq!(idx2, 1);
    }

    #[test]
    fn test_directory_prefix_wildcard_variants() {
        assert_eq!(get_directory_prefix("/src/?oo/"), "/src");
        assert_eq!(get_directory_prefix("/src/[abc]/"), "/src");
        assert_eq!(get_directory_prefix("/a/b/*.txt"), "/a/b");
    }

    #[test]
    fn test_find_insertion_point_without_owner() {
        let lines = parse_codeowners_file("/src/ @team\n/lib/ @team");
        // Uses find_insertion_point_with_owner internally
        let idx = find_insertion_point(&lines, "/bin/tool.rs");
        // No path match, no catch-all, so end of file
        assert_eq!(idx, 2);
    }

    #[test]
    fn test_get_directory_prefix_file_with_slash_no_wildcard() {
        // File path with / but no wildcard before it (line 232)
        // This is like "src/foo/bar.txt" where there's no wildcard
        assert_eq!(get_directory_prefix("src/foo/bar.txt"), "/src/foo");
        assert_eq!(get_directory_prefix("a/b/c/file.rs"), "/a/b/c");
    }

    #[test]
    fn test_format_codeowners_whitespace_only_after_trim() {
        // Line that becomes empty after parts split (line 334)
        // This shouldn't really happen since trimmed empty is caught earlier
        // but the code handles it
        let input = "*.rs @owner\n\n/src/ @team";
        let formatted = format_codeowners(input);
        // Should handle gracefully
        assert!(formatted.contains("*.rs @owner"));
        assert!(formatted.contains("/src/ @team"));
    }

    // --- Inline comment tests ---

    #[test]
    fn test_find_inline_comment_start() {
        assert_eq!(find_inline_comment_start("*.rs @owner # comment"), Some(12));
        assert_eq!(find_inline_comment_start("*.rs @owner"), None);
        assert_eq!(find_inline_comment_start("# full line comment"), Some(0));
        assert_eq!(find_inline_comment_start("*.rs @owner #nospace"), Some(12));
    }

    #[test]
    fn test_find_inline_comment_start_hash_in_token() {
        // # attached to a token (no preceding whitespace) is NOT an inline comment
        assert_eq!(find_inline_comment_start("*.rs @owner#attached"), None);
    }

    #[test]
    fn test_parse_inline_comment_stripped_from_owners() {
        let lines = parse_codeowners_file("*.rs @owner # contact @admin for changes");
        assert_eq!(lines.len(), 1);
        match &lines[0] {
            CodeownersLine::Rule { owners, .. } => {
                assert_eq!(owners, &vec!["@owner".to_string()]);
            }
            _ => panic!("Expected Rule"),
        }
    }

    #[test]
    fn test_parse_inline_comment_position_stored() {
        let lines = parse_codeowners_file_with_positions("*.rs @owner # comment");
        assert_eq!(lines[0].comment_start, Some(12));
    }

    #[test]
    fn test_parse_no_inline_comment() {
        let lines = parse_codeowners_file_with_positions("*.rs @owner");
        assert_eq!(lines[0].comment_start, None);
    }

    #[test]
    fn test_find_owner_at_position_inline_comment_ignored() {
        let line = "*.rs @owner # contact @admin";
        // @owner should be found
        assert_eq!(find_owner_at_position(line, 5), Some("@owner".to_string()));
        // @admin is in the comment, should NOT be found
        assert_eq!(find_owner_at_position(line, 22), None);
    }

    #[test]
    fn test_find_owner_at_position_inline_comment_no_space() {
        let line = "*.rs @owner #comment @nope";
        assert_eq!(find_owner_at_position(line, 5), Some("@owner".to_string()));
        assert_eq!(find_owner_at_position(line, 21), None);
    }

    #[test]
    fn test_format_preserves_inline_comments() {
        let input = "*.rs    @owner1   @owner2   # important note";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "*.rs @owner1 @owner2 # important note\n");
    }

    #[test]
    fn test_format_preserves_inline_comment_no_owners() {
        let input = "/unowned/ # deliberately unowned";
        let formatted = format_codeowners(input);
        assert_eq!(formatted, "/unowned/ # deliberately unowned\n");
    }

    #[test]
    fn test_format_roundtrip_with_inline_comments() {
        let input = "# Header\n*.rs @owner # rust files\n/src/ @team # source dir\n";
        let formatted = format_codeowners(input);
        assert_eq!(
            formatted,
            "# Header\n*.rs @owner # rust files\n/src/ @team # source dir\n"
        );
    }
}

#[cfg(test)]
mod owner_offset_tests {
    use super::{parse_codeowners_file_with_positions, CodeownersLine};

    fn owners_start_of(line: &str) -> u32 {
        let parsed = parse_codeowners_file_with_positions(line);
        assert!(matches!(parsed[0].content, CodeownersLine::Rule { .. }));
        parsed[0].owners_start
    }

    #[test]
    fn owners_start_skips_matches_inside_the_pattern() {
        // "api" occurs inside the pattern before it occurs as the owner.
        assert_eq!(owners_start_of("api/src api"), 8);
        assert_eq!(owners_start_of("docs/ @docs"), 6);
        assert_eq!(owners_start_of("src src src"), 4);
    }

    #[test]
    fn owners_start_is_unchanged_for_ordinary_rules() {
        assert_eq!(owners_start_of("*.rs @owner"), 5);
        assert_eq!(owners_start_of("/src/  @org/team"), 7);
    }
}