1use std::path::Path;
39
40use globset::{Candidate, Glob, GlobBuilder, GlobSet, GlobSetBuilder};
41use rustc_hash::{FxHashMap, FxHashSet};
42
43const MAX_RULE_WILDCARDS: usize = 32;
48
49const MAX_FILE_WILDCARDS: usize = 4096;
54
55const MAX_RULE_BYTES: usize = 512;
61
62const MAX_MATCHER_COST: usize = 8 * 1024 * 1024;
69
70#[derive(Debug)]
72struct Rule {
73 pattern: String,
75 owner: Option<String>,
77 owner_count: u32,
79 section: Option<usize>,
81}
82
83#[derive(Debug)]
85struct Section {
86 name: String,
87 default_owners: Vec<String>,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct RuleMatch<'a> {
93 pub owner: Option<&'a str>,
95 pub owner_count: u32,
97 pub pattern: &'a str,
99 pub section: Option<&'a str>,
101 pub section_owners: &'a [String],
103}
104
105#[derive(Debug)]
107pub struct CodeOwners {
108 rules: Vec<Rule>,
110 sections: Vec<Section>,
112 globs: Vec<CodeOwnersMatcher>,
114 glob_rules: Vec<usize>,
116}
117
118#[derive(Debug)]
119struct CodeOwnersMatcher {
120 globs: GlobSet,
121 glob_offset: usize,
123}
124
125const PROBE_PATHS: &[&str] = &[
129 "CODEOWNERS",
130 ".github/CODEOWNERS",
131 ".gitlab/CODEOWNERS",
132 "docs/CODEOWNERS",
133];
134
135pub const UNOWNED_LABEL: &str = "(unowned)";
137
138pub const NO_SECTION_LABEL: &str = "(no section)";
143
144fn read_project_file(
147 root: &Path,
148 path: &Path,
149) -> Result<String, fallow_types::read_guard::ReadRefusal> {
150 fallow_types::read_guard::read_to_string_inside(
151 root,
152 path,
153 fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
154 )
155}
156
157impl CodeOwners {
158 pub fn from_file(path: &Path) -> Result<Self, String> {
160 let content = std::fs::read_to_string(path)
161 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
162 Self::parse(&content)
163 }
164
165 pub fn discover(root: &Path) -> Result<Self, String> {
173 for probe in PROBE_PATHS {
174 let present = root
175 .join(probe)
176 .symlink_metadata()
177 .is_ok_and(|meta| meta.is_file() || meta.file_type().is_symlink());
178 let parent_is_link = Path::new(probe).parent().is_some_and(|parent| {
179 !parent.as_os_str().is_empty()
180 && root
181 .join(parent)
182 .symlink_metadata()
183 .is_ok_and(|meta| meta.file_type().is_symlink())
184 });
185 if !present && !parent_is_link {
186 continue;
187 }
188 match read_project_file(root, Path::new(probe)) {
189 Ok(content) => return Self::parse(&content),
190 Err(fallow_types::read_guard::ReadRefusal::OutsideRoot { .. }) => {
191 tracing::warn!(
192 "skipping {probe}: it is a link that does not resolve to a file inside the project root"
193 );
194 }
195 Err(refusal) if refusal.is_not_found() => {}
196 Err(refusal) => return Err(refusal.to_string()),
197 }
198 }
199 Err(format!(
200 "no CODEOWNERS file found (looked for: {}). \
201 Create one of these files or use --group-by directory instead",
202 PROBE_PATHS.join(", ")
203 ))
204 }
205
206 pub fn load(root: &Path, config_path: Option<&str>) -> Result<Self, String> {
212 if let Some(p) = config_path {
213 let base = fallow_config::project_scope_base(root);
214 Self::from_project_file(&base, &root.join(p)).map_err(|error| {
215 fallow_config::outside_value_error(root, "codeowners", Path::new(p))
216 .unwrap_or(error)
217 })
218 } else {
219 Self::discover(root)
220 }
221 }
222
223 fn from_project_file(root: &Path, path: &Path) -> Result<Self, String> {
227 let content = read_project_file(root, path).map_err(|e| e.to_string())?;
228 Self::parse(&content)
229 }
230
231 pub fn parse(content: &str) -> Result<Self, String> {
235 let content = content.strip_prefix('\u{FEFF}').unwrap_or(content);
236 let mut parser = CodeOwnersParser::new();
237 for line in content.lines() {
238 parser.parse_line(line)?;
239 }
240 parser.finish()
241 }
242
243 fn last_matching_rule(&self, relative_path: &Path) -> Option<usize> {
249 let candidate = Candidate::new(relative_path);
250 self.globs.iter().rev().find_map(|batch| {
251 batch
252 .globs
253 .matches_candidate(&candidate)
254 .into_iter()
255 .map(|idx| self.glob_rules[batch.glob_offset + idx])
256 .max()
257 })
258 }
259
260 pub fn match_path(&self, relative_path: &Path) -> Option<RuleMatch<'_>> {
268 let rule = &self.rules[self.last_matching_rule(relative_path)?];
269 let section = rule.section.map(|idx| &self.sections[idx]);
270 Some(RuleMatch {
271 owner: rule.owner.as_deref(),
272 owner_count: rule.owner_count,
273 pattern: &rule.pattern,
274 section: section.map(|s| s.name.as_str()),
275 section_owners: section.map_or(&[][..], |s| s.default_owners.as_slice()),
276 })
277 }
278
279 pub fn owner_of(&self, relative_path: &Path) -> Option<&str> {
285 self.match_path(relative_path)?.owner
286 }
287
288 pub fn owner_count_of(&self, relative_path: &Path) -> Option<u32> {
293 self.match_path(relative_path).map(|m| m.owner_count)
294 }
295
296 pub fn has_sections(&self) -> bool {
301 !self.sections.is_empty()
302 }
303}
304
305struct CodeOwnersParser {
306 globs: Vec<Glob>,
307 glob_rules: Vec<usize>,
308 rules: Vec<Rule>,
309 sections: Vec<Section>,
310 section_index: FxHashMap<String, usize>,
312 section_owners_seen: FxHashSet<(usize, String)>,
315 current_section: Option<usize>,
316 current_section_owners: Vec<String>,
318 wildcards: usize,
319}
320
321impl CodeOwnersParser {
322 fn new() -> Self {
323 Self {
324 globs: Vec::new(),
325 glob_rules: Vec::new(),
326 rules: Vec::new(),
327 sections: Vec::new(),
328 section_index: FxHashMap::default(),
329 section_owners_seen: FxHashSet::default(),
330 current_section: None,
331 current_section_owners: Vec::new(),
332 wildcards: 0,
333 }
334 }
335
336 fn parse_line(&mut self, line: &str) -> Result<(), String> {
337 match parse_codeowners_line(line, &self.current_section_owners) {
338 ParsedCodeOwnersLine::Skip => Ok(()),
339 ParsedCodeOwnersLine::Section { name, defaults } => {
340 self.enter_section(name, defaults);
341 Ok(())
342 }
343 ParsedCodeOwnersLine::Rule {
344 pattern,
345 owner,
346 owner_count,
347 negate,
348 } => self.add_rule(pattern, owner, owner_count, negate),
349 }
350 }
351
352 fn enter_section(&mut self, name: String, defaults: Vec<String>) {
357 let key = name.to_lowercase();
358 let idx = if let Some(&idx) = self.section_index.get(&key) {
359 idx
360 } else {
361 let idx = self.sections.len();
362 self.sections.push(Section {
363 name,
364 default_owners: Vec::new(),
365 });
366 self.section_index.insert(key, idx);
367 idx
368 };
369 for owner in &defaults {
370 if self.section_owners_seen.insert((idx, owner.clone())) {
371 self.sections[idx].default_owners.push(owner.clone());
372 }
373 }
374 self.current_section = Some(idx);
375 self.current_section_owners = defaults;
376 }
377
378 fn add_rule(
379 &mut self,
380 pattern: String,
381 owner: String,
382 owner_count: u32,
383 negate: bool,
384 ) -> Result<(), String> {
385 if pattern.len() > MAX_RULE_BYTES {
386 let start: String = pattern.chars().take(40).collect();
387 return Err(format!(
388 "CODEOWNERS pattern '{start}...' is longer than {MAX_RULE_BYTES} bytes"
389 ));
390 }
391 let wildcards = pattern
392 .bytes()
393 .filter(|b| matches!(b, b'*' | b'?' | b'[' | b'{'))
394 .count();
395 if wildcards > MAX_RULE_WILDCARDS {
396 return Err(format!(
397 "CODEOWNERS pattern '{pattern}' has more than {MAX_RULE_WILDCARDS} wildcards"
398 ));
399 }
400 self.wildcards += wildcards;
401 if self.wildcards > MAX_FILE_WILDCARDS {
402 return Err(format!(
403 "CODEOWNERS file has more than {MAX_FILE_WILDCARDS} wildcards in its patterns"
404 ));
405 }
406
407 let rule_idx = self.rules.len();
408 for glob_pattern in translate_pattern(&pattern) {
409 let glob = GlobBuilder::new(&glob_pattern)
412 .literal_separator(true)
413 .backslash_escape(true)
414 .build()
415 .map_err(|e| format!("invalid CODEOWNERS pattern '{pattern}': {e}"))?;
416 self.globs.push(glob);
417 self.glob_rules.push(rule_idx);
418 }
419
420 self.rules.push(Rule {
421 pattern: if negate {
422 format!("!{pattern}")
423 } else {
424 pattern
425 },
426 owner: (!negate).then_some(owner),
427 owner_count,
428 section: self.current_section,
429 });
430 Ok(())
431 }
432
433 fn finish(self) -> Result<CodeOwners, String> {
434 let mut globs = Vec::new();
435 let mut offset = 0;
436 let mut remaining = self.globs.into_iter().peekable();
437 while remaining.peek().is_some() {
438 let mut builder = GlobSetBuilder::new();
439 let mut regex_bytes: usize = 0;
440 let mut count = 0;
441 while let Some(glob) = remaining.next_if(|glob| {
442 let next_bytes = regex_bytes.saturating_add(glob.regex().len());
443 if count > 0 && next_bytes.saturating_mul(count + 1) > MAX_MATCHER_COST {
444 return false;
445 }
446 regex_bytes = next_bytes;
447 true
448 }) {
449 builder.add(glob);
450 count += 1;
451 }
452 globs.push(CodeOwnersMatcher {
453 globs: builder
454 .build()
455 .map_err(|e| format!("failed to compile CODEOWNERS patterns: {e}"))?,
456 glob_offset: offset,
457 });
458 offset += count;
459 }
460
461 Ok(CodeOwners {
462 rules: self.rules,
463 sections: self.sections,
464 globs,
465 glob_rules: self.glob_rules,
466 })
467 }
468}
469
470enum ParsedCodeOwnersLine {
471 Skip,
472 Section {
473 name: String,
474 defaults: Vec<String>,
475 },
476 Rule {
477 pattern: String,
478 owner: String,
479 owner_count: u32,
480 negate: bool,
481 },
482}
483
484fn parse_codeowners_line(line: &str, current_section_owners: &[String]) -> ParsedCodeOwnersLine {
485 let line = line.trim();
486 if line.is_empty() || line.starts_with('#') {
487 return ParsedCodeOwnersLine::Skip;
488 }
489
490 if let Some((name, defaults)) = parse_section_header(line) {
491 return ParsedCodeOwnersLine::Section { name, defaults };
492 }
493
494 let (negate, rest) = if let Some(after) = line.strip_prefix('!') {
495 (true, after.trim_start())
496 } else {
497 (false, line)
498 };
499
500 let (pattern, owners_text) = split_pattern(rest);
501 if pattern.is_empty() {
502 return ParsedCodeOwnersLine::Skip;
503 }
504 let inline_owners = owners_text.split_whitespace().collect::<Vec<_>>();
505
506 let (owner, owner_count) = if negate {
507 (String::new(), 0)
508 } else if let Some(owner) = inline_owners.first() {
509 (
510 (*owner).to_string(),
511 u32::try_from(inline_owners.len()).unwrap_or(u32::MAX),
512 )
513 } else if let Some(owner) = current_section_owners.first() {
514 (
515 owner.clone(),
516 u32::try_from(current_section_owners.len()).unwrap_or(u32::MAX),
517 )
518 } else {
519 return ParsedCodeOwnersLine::Skip;
520 };
521
522 ParsedCodeOwnersLine::Rule {
523 pattern: pattern.to_string(),
524 owner,
525 owner_count,
526 negate,
527 }
528}
529
530fn split_pattern(line: &str) -> (&str, &str) {
535 let mut escaped = false;
536 for (idx, ch) in line.char_indices() {
537 if escaped {
538 escaped = false;
539 } else if ch == '\\' {
540 escaped = true;
541 } else if ch.is_whitespace() {
542 return (&line[..idx], &line[idx..]);
543 }
544 }
545 (line, "")
546}
547
548fn parse_section_header(line: &str) -> Option<(String, Vec<String>)> {
564 let rest = line.strip_prefix('^').unwrap_or(line);
565 let rest = rest.strip_prefix('[')?;
566 let close = rest.find(']')?;
567 let name = &rest[..close];
568 if name.is_empty() {
569 return None;
570 }
571 let mut after = &rest[close + 1..];
572
573 if let Some(inner) = after.strip_prefix('[') {
574 let n_close = inner.find(']')?;
575 let count = &inner[..n_close];
576 if count.is_empty() || !count.chars().all(|c| c.is_ascii_digit()) {
577 return None;
578 }
579 after = &inner[n_close + 1..];
580 }
581
582 if !after.is_empty() && !after.starts_with(char::is_whitespace) {
583 return None;
584 }
585
586 Some((
587 name.to_string(),
588 after.split_whitespace().map(String::from).collect(),
589 ))
590}
591
592fn translate_pattern(pattern: &str) -> Vec<String> {
606 let (anchored, rest) = match pattern.strip_prefix('/') {
607 Some(p) => (true, p),
608 None => (false, pattern),
609 };
610 let (directory_only, body) = match rest.strip_suffix('/') {
611 Some(p) => (true, p),
612 None => (false, rest),
613 };
614 if body.is_empty() {
615 return vec!["**".to_string()];
616 }
617
618 let base = if !anchored && !body.contains('/') {
619 format!("**/{body}")
620 } else {
621 body.to_string()
622 };
623 let contents = format!("{base}/**");
624 if directory_only {
625 return vec![contents];
626 }
627
628 let last_segment = base.rsplit('/').next().unwrap_or(&base);
629 if matches!(last_segment, "*" | "**") {
630 vec![base]
631 } else {
632 vec![base, contents]
633 }
634}
635
636pub fn directory_group(relative_path: &Path) -> &str {
641 let s = relative_path.to_str().unwrap_or("");
642 let s = if s.contains('\\') {
643 return s.split(['/', '\\']).next().unwrap_or(s);
644 } else {
645 s
646 };
647
648 match s.find('/') {
649 Some(pos) => &s[..pos],
650 None => s, }
652}
653
654#[cfg(test)]
655mod tests {
656 use super::*;
657
658 #[test]
659 fn translate_bare_glob() {
660 assert_eq!(translate_pattern("*.js"), ["**/*.js", "**/*.js/**"]);
661 }
662
663 #[test]
664 fn translate_rooted_pattern() {
665 assert_eq!(translate_pattern("/docs/*"), ["docs/*"]);
666 }
667
668 #[test]
669 fn translate_directory_pattern() {
670 assert_eq!(translate_pattern("docs/"), ["**/docs/**"]);
671 }
672
673 #[test]
674 fn translate_rooted_directory() {
675 assert_eq!(translate_pattern("/src/app/"), ["src/app/**"]);
676 }
677
678 #[test]
679 fn translate_rooted_path_without_trailing_slash() {
680 assert_eq!(translate_pattern("/docs"), ["docs", "docs/**"]);
681 }
682
683 #[test]
684 fn translate_path_with_slash() {
685 assert_eq!(
686 translate_pattern("src/utils/*.ts"),
687 ["src/utils/*.ts", "src/utils/*.ts/**"]
688 );
689 }
690
691 #[test]
692 fn translate_double_star() {
693 assert_eq!(
694 translate_pattern("**/test_*.py"),
695 ["**/test_*.py", "**/test_*.py/**"]
696 );
697 assert_eq!(translate_pattern("/build/**"), ["build/**"]);
698 }
699
700 #[test]
701 fn translate_single_file() {
702 assert_eq!(
703 translate_pattern("Makefile"),
704 ["**/Makefile", "**/Makefile/**"]
705 );
706 }
707
708 #[test]
709 fn translate_catch_all() {
710 assert_eq!(translate_pattern("*"), ["**/*"]);
711 }
712
713 #[test]
714 fn parse_simple_codeowners() {
715 let content = "* @global-owner\n/src/ @frontend\n*.rs @rust-team\n";
716 let co = CodeOwners::parse(content).unwrap();
717 assert_eq!(co.rules.len(), 3);
718 }
719
720 #[test]
721 fn parse_skips_comments_and_blanks() {
722 let content = "# Comment\n\n* @owner\n # Indented comment\n";
723 let co = CodeOwners::parse(content).unwrap();
724 assert_eq!(co.rules.len(), 1);
725 }
726
727 #[test]
728 fn parse_multi_owner_takes_first() {
729 let content = "*.ts @team-a @team-b @team-c\n";
730 let co = CodeOwners::parse(content).unwrap();
731 assert_eq!(co.rules[0].owner.as_deref(), Some("@team-a"));
732 }
733
734 #[test]
735 fn parse_skips_pattern_without_owner() {
736 let content = "*.ts\n*.js @owner\n";
737 let co = CodeOwners::parse(content).unwrap();
738 assert_eq!(co.rules.len(), 1);
739 assert_eq!(co.rules[0].owner.as_deref(), Some("@owner"));
740 }
741
742 #[test]
743 fn long_patterns_do_not_multiply_lookup_resources_by_rule_count() {
744 use std::fmt::Write as _;
745
746 let mut content = String::from("[Files] @files\n/docs/escaped\\ file.md @escaped\n");
747 for index in 0..256 {
748 writeln!(content, "file{index}?").expect("writing to a String cannot fail");
749 }
750 let literal = "a".repeat(MAX_RULE_BYTES - 2);
751 writeln!(
752 content,
753 "[Long] @long\n{literal}*\"\n[Overrides] @override\n!file0x\nfile1x"
754 )
755 .expect("writing to a String cannot fail");
756 let owners = CodeOwners::parse(&content).unwrap();
757 let start = std::time::Instant::now();
758 for _ in 0..5 {
759 for index in 2..256 {
760 assert_eq!(
761 owners.owner_of(Path::new(&format!("file{index}x"))),
762 Some("@files")
763 );
764 }
765 assert_eq!(
766 owners.owner_of(Path::new(&format!("{literal}suffix\""))),
767 Some("@long")
768 );
769 assert_eq!(owners.owner_of(Path::new("file0x")), None);
770 assert_eq!(owners.owner_of(Path::new("file1x")), Some("@override"));
771 assert_eq!(
772 owners.owner_of(Path::new("docs/escaped file.md")),
773 Some("@escaped")
774 );
775 assert_eq!(
776 owners.match_path(Path::new("file1x")).map(|m| m.section),
777 Some(Some("Overrides"))
778 );
779 }
780 assert!(
781 start.elapsed() < std::time::Duration::from_secs(25),
782 "ownership lookup exceeded its resource regression budget"
783 );
784 }
785
786 #[test]
789 fn parse_rejects_rule_that_is_too_long() {
790 let content = format!(
791 "/{}/ @owner\n/x/{}/ @owner\n",
792 "0".repeat(512),
793 "0".repeat(4_096)
794 );
795 let err = CodeOwners::parse(&content).err().unwrap_or_default();
796 assert!(err.contains("longer than 512 bytes"), "{err}");
797
798 let content = format!("/{}/ @owner\n", "0".repeat(509));
799 assert!(CodeOwners::parse(&content).is_ok());
800 }
801
802 #[test]
803 fn parse_rejects_rule_with_too_many_wildcards() {
804 let content = format!("{} @owner\n", "*a".repeat(33));
805 let err = CodeOwners::parse(&content).unwrap_err();
806 assert!(err.contains("more than 32 wildcards"), "{err}");
807 }
808
809 #[test]
810 fn parse_rejects_file_with_too_many_wildcards() {
811 let rule = format!("{} @owner\n", "*a".repeat(16));
812 let err = CodeOwners::parse(&rule.repeat(257)).unwrap_err();
813 assert!(err.contains("more than 4096 wildcards"), "{err}");
814 }
815
816 #[test]
817 fn parse_counts_every_wildcard_kind() {
818 let content = format!("!{} @owner\n", "{a,b}?[x]".repeat(11));
819 let err = CodeOwners::parse(&content).unwrap_err();
820 assert!(err.contains("more than 32 wildcards"), "{err}");
821 }
822
823 #[test]
824 fn parse_accepts_wildcards_at_the_limits() {
825 let rule = format!("{} @owner\n", "*a".repeat(32));
826 let co = CodeOwners::parse(&rule.repeat(128)).unwrap();
827 assert_eq!(co.rules.len(), 128);
828 }
829
830 #[test]
831 fn parse_empty_content() {
832 let co = CodeOwners::parse("").unwrap();
833 assert_eq!(co.owner_of(Path::new("anything.ts")), None);
834 }
835
836 #[test]
837 fn owner_of_last_match_wins() {
838 let content = "* @default\n/src/ @frontend\n";
839 let co = CodeOwners::parse(content).unwrap();
840 assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
841 }
842
843 #[test]
844 fn owner_of_falls_back_to_catch_all() {
845 let content = "* @default\n/src/ @frontend\n";
846 let co = CodeOwners::parse(content).unwrap();
847 assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
848 }
849
850 #[test]
851 fn owner_of_no_match_returns_none() {
852 let content = "/src/ @frontend\n";
853 let co = CodeOwners::parse(content).unwrap();
854 assert_eq!(co.owner_of(Path::new("README.md")), None);
855 }
856
857 #[test]
858 fn owner_of_extension_glob() {
859 let content = "*.rs @rust-team\n*.ts @ts-team\n";
860 let co = CodeOwners::parse(content).unwrap();
861 assert_eq!(co.owner_of(Path::new("src/lib.rs")), Some("@rust-team"));
862 assert_eq!(
863 co.owner_of(Path::new("packages/ui/Button.ts")),
864 Some("@ts-team")
865 );
866 }
867
868 #[test]
869 fn owner_of_nested_directory() {
870 let content = "* @default\n/packages/auth/ @auth-team\n";
871 let co = CodeOwners::parse(content).unwrap();
872 assert_eq!(
873 co.owner_of(Path::new("packages/auth/src/login.ts")),
874 Some("@auth-team")
875 );
876 assert_eq!(
877 co.owner_of(Path::new("packages/ui/Button.ts")),
878 Some("@default")
879 );
880 }
881
882 #[test]
883 fn owner_of_specific_overrides_general() {
884 let content = "\
885 * @default\n\
886 /src/ @frontend\n\
887 /src/api/ @backend\n\
888 ";
889 let co = CodeOwners::parse(content).unwrap();
890 assert_eq!(
891 co.owner_of(Path::new("src/api/routes.ts")),
892 Some("@backend")
893 );
894 assert_eq!(co.owner_of(Path::new("src/app.ts")), Some("@frontend"));
895 }
896
897 #[test]
898 fn match_path_returns_owner_and_pattern() {
899 let content = "* @default\n/src/ @frontend\n*.rs @rust-team\n";
900 let co = CodeOwners::parse(content).unwrap();
901 assert_eq!(
902 co.match_path(Path::new("src/app.ts"))
903 .map(|m| (m.owner, m.pattern)),
904 Some((Some("@frontend"), "/src/"))
905 );
906 assert_eq!(
907 co.match_path(Path::new("src/lib.rs"))
908 .map(|m| (m.owner, m.pattern)),
909 Some((Some("@rust-team"), "*.rs"))
910 );
911 assert_eq!(
912 co.match_path(Path::new("README.md"))
913 .map(|m| (m.owner, m.pattern)),
914 Some((Some("@default"), "*"))
915 );
916 }
917
918 #[test]
919 fn match_path_no_match() {
920 let content = "/src/ @frontend\n";
921 let co = CodeOwners::parse(content).unwrap();
922 assert_eq!(co.match_path(Path::new("README.md")), None);
923 }
924
925 #[test]
926 fn directory_group_simple() {
927 assert_eq!(directory_group(Path::new("src/utils/index.ts")), "src");
928 }
929
930 #[test]
931 fn directory_group_root_file() {
932 assert_eq!(directory_group(Path::new("index.ts")), "index.ts");
933 }
934
935 #[test]
936 fn directory_group_monorepo() {
937 assert_eq!(
938 directory_group(Path::new("packages/auth/src/login.ts")),
939 "packages"
940 );
941 }
942
943 #[test]
944 fn discover_nonexistent_root() {
945 let result = CodeOwners::discover(Path::new("/nonexistent/path"));
946 assert!(result.is_err());
947 let err = result.unwrap_err();
948 assert!(err.contains("no CODEOWNERS file found"));
949 assert!(err.contains("--group-by directory"));
950 }
951
952 #[cfg(unix)]
953 #[test]
954 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
955 fn codeowners_link_out_of_the_root_is_refused() {
956 let dir = tempfile::tempdir().unwrap();
957 let root = dir.path().join("project");
958 std::fs::create_dir(&root).unwrap();
959 std::fs::write(dir.path().join("OWNERS"), "* @outside-owner\n").unwrap();
960 std::os::unix::fs::symlink(dir.path().join("OWNERS"), root.join("CODEOWNERS")).unwrap();
961
962 let err = CodeOwners::discover(&root).unwrap_err();
963 assert!(err.contains("no CODEOWNERS file found"), "{err}");
964 let err = CodeOwners::load(&root, Some("CODEOWNERS")).unwrap_err();
965 assert!(err.contains("outside"), "{err}");
966 }
967
968 #[test]
969 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
970 fn a_package_config_can_name_the_codeowners_file_of_the_repository() {
971 let dir = tempfile::tempdir().unwrap();
972 let top = dir.path().join("repo");
973 let package = top.join("packages/app");
974 std::fs::create_dir_all(&package).unwrap();
975 std::fs::create_dir_all(top.join(".git")).unwrap();
976 std::fs::create_dir_all(top.join(".github")).unwrap();
977 std::fs::write(top.join(".github/CODEOWNERS"), "* @repo-owner\n").unwrap();
978 std::fs::write(dir.path().join("CODEOWNERS"), "* @outside-owner\n").unwrap();
979
980 let owners = CodeOwners::load(&package, Some("../../.github/CODEOWNERS")).unwrap();
981 assert_eq!(owners.owner_of(Path::new("a.ts")), Some("@repo-owner"));
982 let err = CodeOwners::load(&package, Some("../../../CODEOWNERS")).unwrap_err();
983 assert!(err.contains("outside"), "{err}");
984 }
985
986 #[test]
987 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
988 fn a_codeowners_read_error_omits_a_value_from_an_outside_config_file() {
989 let dir = tempfile::tempdir().unwrap();
990 let root = dir.path().join("project");
991 std::fs::create_dir_all(root.join(".git")).unwrap();
992 std::fs::write(
993 dir.path().join("outside.json"),
994 r#"{"codeowners": "owners-7531/CODEOWNERS"}"#,
995 )
996 .unwrap();
997 std::fs::write(
998 root.join(".fallowrc.json"),
999 r#"{"extends": "../outside.json"}"#,
1000 )
1001 .unwrap();
1002 let file = crate::project_config::load_config_file(
1003 &root,
1004 None,
1005 crate::project_config::ConfigFileOptions::default(),
1006 )
1007 .unwrap();
1008 let value = file.config.codeowners.unwrap();
1009
1010 let err = CodeOwners::load(&root, Some(&value)).unwrap_err();
1011 assert!(!err.contains("owners-7531"), "{err}");
1012 assert!(err.contains("codeowners"), "{err}");
1013 assert!(err.contains("outside.json"), "{err}");
1014
1015 std::fs::write(
1017 root.join(".fallowrc.json"),
1018 r#"{"codeowners": "owners-7531/CODEOWNERS"}"#,
1019 )
1020 .unwrap();
1021 crate::project_config::load_config_file(
1022 &root,
1023 None,
1024 crate::project_config::ConfigFileOptions::default(),
1025 )
1026 .unwrap();
1027 let err = CodeOwners::load(&root, Some(&value)).unwrap_err();
1028 assert!(err.contains("owners-7531"), "{err}");
1029 }
1030
1031 #[cfg(unix)]
1032 #[test]
1033 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1034 fn a_dangling_root_codeowners_link_falls_back_to_the_github_file() {
1035 let dir = tempfile::tempdir().unwrap();
1036 let root = dir.path();
1037 std::os::unix::fs::symlink("missing-owners", root.join("CODEOWNERS")).unwrap();
1038 std::fs::create_dir(root.join(".github")).unwrap();
1039 std::fs::write(root.join(".github/CODEOWNERS"), "* @github-owner\n").unwrap();
1040
1041 let owners = CodeOwners::discover(root).unwrap();
1042 assert_eq!(
1043 owners.owner_of(Path::new("src/a.ts")),
1044 Some("@github-owner")
1045 );
1046 }
1047
1048 #[test]
1049 fn from_file_nonexistent() {
1050 let result = CodeOwners::from_file(Path::new("/nonexistent/CODEOWNERS"));
1051 assert!(result.is_err());
1052 }
1053
1054 #[test]
1055 fn from_file_real_codeowners() {
1056 let root = std::path::PathBuf::from(
1057 std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"),
1058 )
1059 .parent()
1060 .unwrap()
1061 .parent()
1062 .unwrap()
1063 .to_path_buf();
1064 let path = root.join(".github/CODEOWNERS");
1065 if path.exists() {
1066 let co = CodeOwners::from_file(&path).unwrap();
1067 assert_eq!(
1068 co.owner_of(Path::new(".claude/rules/detection.md")),
1069 Some("@bartwaardenburg")
1070 );
1071 }
1072 }
1073
1074 #[test]
1075 fn email_owner() {
1076 let content = "*.js user@example.com\n";
1077 let co = CodeOwners::parse(content).unwrap();
1078 assert_eq!(co.owner_of(Path::new("index.js")), Some("user@example.com"));
1079 }
1080
1081 #[test]
1082 fn team_owner() {
1083 let content = "*.ts @org/frontend-team\n";
1084 let co = CodeOwners::parse(content).unwrap();
1085 assert_eq!(co.owner_of(Path::new("app.ts")), Some("@org/frontend-team"));
1086 }
1087
1088 #[test]
1089 fn gitlab_section_header_skipped_as_rule() {
1090 let content = "[Section Name]\n*.ts @owner\n";
1091 let co = CodeOwners::parse(content).unwrap();
1092 assert_eq!(co.rules.len(), 1);
1093 assert_eq!(co.owner_of(Path::new("app.ts")), Some("@owner"));
1094 }
1095
1096 #[test]
1097 fn gitlab_optional_section_header_skipped() {
1098 let content = "^[Optional Section]\n*.ts @owner\n";
1099 let co = CodeOwners::parse(content).unwrap();
1100 assert_eq!(co.rules.len(), 1);
1101 }
1102
1103 #[test]
1104 fn gitlab_section_header_with_approval_count_skipped() {
1105 let content = "[Section Name][2]\n*.ts @owner\n";
1106 let co = CodeOwners::parse(content).unwrap();
1107 assert_eq!(co.rules.len(), 1);
1108 }
1109
1110 #[test]
1111 fn gitlab_optional_section_with_approval_count_skipped() {
1112 let content = "^[Section Name][3] @fallback-team\nfoo/\n";
1113 let co = CodeOwners::parse(content).unwrap();
1114 assert_eq!(co.rules.len(), 1);
1115 assert_eq!(co.owner_of(Path::new("foo/bar.ts")), Some("@fallback-team"));
1116 }
1117
1118 #[test]
1119 fn gitlab_section_default_owners_inherited() {
1120 let content = "\
1121 [Utilities] @utils-team\n\
1122 src/utils/\n\
1123 [UI Components] @ui-team\n\
1124 src/components/\n\
1125 ";
1126 let co = CodeOwners::parse(content).unwrap();
1127 assert_eq!(co.rules.len(), 2);
1128 assert_eq!(
1129 co.owner_of(Path::new("src/utils/greet.ts")),
1130 Some("@utils-team")
1131 );
1132 assert_eq!(
1133 co.owner_of(Path::new("src/components/button.ts")),
1134 Some("@ui-team")
1135 );
1136 }
1137
1138 #[test]
1139 fn gitlab_inline_owner_overrides_section_default() {
1140 let content = "\
1141 [Section] @section-owner\n\
1142 src/generic/\n\
1143 src/special/ @special-owner\n\
1144 ";
1145 let co = CodeOwners::parse(content).unwrap();
1146 assert_eq!(
1147 co.owner_of(Path::new("src/generic/a.ts")),
1148 Some("@section-owner")
1149 );
1150 assert_eq!(
1151 co.owner_of(Path::new("src/special/a.ts")),
1152 Some("@special-owner")
1153 );
1154 }
1155
1156 #[test]
1157 fn gitlab_section_defaults_reset_between_sections() {
1158 let content = "\
1159 [Section1] @team-a\n\
1160 foo/\n\
1161 [Section2]\n\
1162 bar/\n\
1163 ";
1164 let co = CodeOwners::parse(content).unwrap();
1165 assert_eq!(co.rules.len(), 1);
1166 assert_eq!(co.owner_of(Path::new("foo/x.ts")), Some("@team-a"));
1167 assert_eq!(co.owner_of(Path::new("bar/x.ts")), None);
1168 }
1169
1170 #[test]
1171 fn gitlab_section_header_multiple_default_owners_uses_first() {
1172 let content = "[Section] @first @second\nfoo/\n";
1173 let co = CodeOwners::parse(content).unwrap();
1174 assert_eq!(co.owner_of(Path::new("foo/a.ts")), Some("@first"));
1175 }
1176
1177 #[test]
1178 fn gitlab_rules_before_first_section_retain_inline_owners() {
1179 let content = "\
1180 * @default-owner\n\
1181 [Utilities] @utils-team\n\
1182 src/utils/\n\
1183 ";
1184 let co = CodeOwners::parse(content).unwrap();
1185 assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
1186 assert_eq!(
1187 co.owner_of(Path::new("src/utils/greet.ts")),
1188 Some("@utils-team")
1189 );
1190 }
1191
1192 #[test]
1193 fn gitlab_issue_127_reproduction() {
1194 let content = "\
1195# Default section (no header, rules before first section)
1196* @default-owner
1197
1198[Utilities] @utils-team
1199src/utils/
1200
1201[UI Components] @ui-team
1202src/components/
1203";
1204 let co = CodeOwners::parse(content).unwrap();
1205 assert_eq!(co.owner_of(Path::new("README.md")), Some("@default-owner"));
1206 assert_eq!(
1207 co.owner_of(Path::new("src/utils/greet.ts")),
1208 Some("@utils-team")
1209 );
1210 assert_eq!(
1211 co.owner_of(Path::new("src/components/button.ts")),
1212 Some("@ui-team")
1213 );
1214 }
1215
1216 #[test]
1217 fn gitlab_negation_last_match_clears_ownership() {
1218 let content = "\
1219 * @default\n\
1220 !src/generated/\n\
1221 ";
1222 let co = CodeOwners::parse(content).unwrap();
1223 assert_eq!(co.owner_of(Path::new("README.md")), Some("@default"));
1224 assert_eq!(co.owner_of(Path::new("src/generated/bundle.js")), None);
1225 }
1226
1227 #[test]
1228 fn gitlab_negation_only_clears_when_last_match() {
1229 let content = "\
1230 * @default\n\
1231 !src/\n\
1232 /src/special/ @special\n\
1233 ";
1234 let co = CodeOwners::parse(content).unwrap();
1235 assert_eq!(co.owner_of(Path::new("src/foo.ts")), None);
1236 assert_eq!(co.owner_of(Path::new("src/special/a.ts")), Some("@special"));
1237 }
1238
1239 #[test]
1240 fn gitlab_negation_owner_and_rule_returns_none() {
1241 let content = "* @default\n!src/vendor/\n";
1242 let co = CodeOwners::parse(content).unwrap();
1243 assert_eq!(
1244 co.match_path(Path::new("README.md"))
1245 .map(|m| (m.owner, m.pattern)),
1246 Some((Some("@default"), "*"))
1247 );
1248 let excluded = co.match_path(Path::new("src/vendor/lib.js"));
1249 assert!(excluded.is_some());
1250 assert_eq!(excluded.and_then(|m| m.owner), None);
1251 }
1252
1253 #[test]
1254 fn escaped_space_stays_in_pattern() {
1255 let content = "* @default\n/docs/Security\\ Release.md @security @release\n";
1256 let co = CodeOwners::parse(content).unwrap();
1257 assert_eq!(
1258 co.match_path(Path::new("docs/Security Release.md"))
1259 .map(|m| (m.owner, m.pattern)),
1260 Some((Some("@security"), "/docs/Security\\ Release.md"))
1261 );
1262 assert_eq!(
1263 co.owner_count_of(Path::new("docs/Security Release.md")),
1264 Some(2)
1265 );
1266 assert_eq!(co.owner_of(Path::new("docs/Security")), Some("@default"));
1267 }
1268
1269 #[test]
1270 fn split_pattern_edge_cases() {
1271 assert_eq!(split_pattern("foo\\\\ @o"), ("foo\\\\", " @o"));
1272 assert_eq!(split_pattern("foo\\\tbar @o"), ("foo\\\tbar", " @o"));
1273 assert_eq!(
1274 split_pattern("caf\u{e9}\\ menu @o"),
1275 ("caf\u{e9}\\ menu", " @o")
1276 );
1277 assert_eq!(split_pattern("foo\\"), ("foo\\", ""));
1278 assert_eq!(split_pattern("foo\t@o"), ("foo", "\t@o"));
1279 }
1280
1281 #[test]
1282 fn negated_rule_with_escaped_space() {
1283 let content = "* @default\n!docs/Security\\ Release.md\n";
1284 let co = CodeOwners::parse(content).unwrap();
1285 assert_eq!(co.owner_of(Path::new("docs/Security Release.md")), None);
1286 assert_eq!(co.owner_of(Path::new("docs/other.md")), Some("@default"));
1287 }
1288
1289 #[test]
1292 fn escaped_hash_is_a_pattern() {
1293 let content = "\\#notes.md @owner\n";
1294 let co = CodeOwners::parse(content).unwrap();
1295 assert_eq!(co.owner_of(Path::new("#notes.md")), Some("@owner"));
1296 }
1297
1298 #[test]
1299 fn parse_section_header_variants() {
1300 assert_eq!(
1301 parse_section_header("[Section]"),
1302 Some(("Section".into(), vec![]))
1303 );
1304 assert_eq!(
1305 parse_section_header("^[Section]"),
1306 Some(("Section".into(), vec![]))
1307 );
1308 assert_eq!(
1309 parse_section_header("[Section][2]"),
1310 Some(("Section".into(), vec![]))
1311 );
1312 assert_eq!(
1313 parse_section_header("^[Section][2]"),
1314 Some(("Section".into(), vec![]))
1315 );
1316 assert_eq!(
1317 parse_section_header("[Section] @a @b"),
1318 Some(("Section".into(), vec!["@a".into(), "@b".into()]))
1319 );
1320 assert_eq!(
1321 parse_section_header("[Section][2] @a"),
1322 Some(("Section".into(), vec!["@a".into()]))
1323 );
1324 }
1325
1326 #[test]
1327 fn parse_section_header_rejects_malformed() {
1328 assert_eq!(parse_section_header("[unclosed"), None);
1329 assert_eq!(parse_section_header("[]"), None);
1330 assert_eq!(parse_section_header("[abc]def @owner"), None);
1331 assert_eq!(parse_section_header("[Section][] @owner"), None);
1332 assert_eq!(parse_section_header("[Section][abc] @owner"), None);
1333 }
1334
1335 #[test]
1336 fn has_sections_false_without_headers() {
1337 let co = CodeOwners::parse("* @default\n/src/ @frontend\n").unwrap();
1338 assert!(!co.has_sections());
1339 }
1340
1341 #[test]
1342 fn has_sections_true_with_headers() {
1343 let co = CodeOwners::parse("[Utilities] @utils\nsrc/utils/\n").unwrap();
1344 assert!(co.has_sections());
1345 }
1346
1347 #[test]
1348 fn match_path_returns_named_section() {
1349 let content = "\
1350 [Billing] @billing-team\n\
1351 src/billing/\n\
1352 [Search] @search-team\n\
1353 src/search/\n\
1354 ";
1355 let co = CodeOwners::parse(content).unwrap();
1356 assert_eq!(
1357 co.match_path(Path::new("src/billing/invoice.ts"))
1358 .map(|m| m.section),
1359 Some(Some("Billing"))
1360 );
1361 assert_eq!(
1362 co.match_path(Path::new("src/search/indexer.ts"))
1363 .map(|m| m.section),
1364 Some(Some("Search"))
1365 );
1366 }
1367
1368 #[test]
1369 fn match_path_returns_no_section_for_pre_section_rule() {
1370 let content = "\
1371 * @default\n\
1372 [Billing] @billing-team\n\
1373 src/billing/\n\
1374 ";
1375 let co = CodeOwners::parse(content).unwrap();
1376 assert_eq!(
1377 co.match_path(Path::new("README.md")).map(|m| m.section),
1378 Some(None)
1379 );
1380 assert_eq!(
1381 co.match_path(Path::new("src/billing/invoice.ts"))
1382 .map(|m| m.section),
1383 Some(Some("Billing"))
1384 );
1385 }
1386
1387 #[test]
1388 fn match_path_returns_none_for_unmatched_path() {
1389 let content = "[Billing] @billing-team\nsrc/billing/\n";
1390 let co = CodeOwners::parse(content).unwrap();
1391 assert_eq!(co.match_path(Path::new("src/other/x.ts")), None);
1392 }
1393
1394 #[test]
1395 fn match_path_returns_no_owner_for_negation_last_match() {
1396 let content = "\
1397 [Billing] @billing-team\n\
1398 src/billing/\n\
1399 !src/billing/vendor/\n\
1400 ";
1401 let co = CodeOwners::parse(content).unwrap();
1402 assert_eq!(
1403 co.match_path(Path::new("src/billing/invoice.ts"))
1404 .map(|m| m.section),
1405 Some(Some("Billing"))
1406 );
1407 let excluded = co.match_path(Path::new("src/billing/vendor/lib.js"));
1408 assert!(excluded.is_some());
1409 assert_eq!(excluded.and_then(|m| m.owner), None);
1410 }
1411
1412 #[test]
1413 fn match_path_returns_section_defaults() {
1414 let content = "\
1415 [Billing] @core-reviewers @alice\n\
1416 src/billing/\n\
1417 ";
1418 let co = CodeOwners::parse(content).unwrap();
1419 let (section, owners) = co
1420 .match_path(Path::new("src/billing/invoice.ts"))
1421 .map(|m| (m.section, m.section_owners))
1422 .unwrap();
1423 assert_eq!(section, Some("Billing"));
1424 assert_eq!(
1425 owners,
1426 &["@core-reviewers".to_string(), "@alice".to_string()]
1427 );
1428 }
1429
1430 #[test]
1431 fn match_path_same_owners_distinct_sections() {
1432 let content = "\
1433 [billing] @core-reviewers @alice @bob\n\
1434 src/billing/\n\
1435 [notifications] @core-reviewers @alice @bob\n\
1436 src/notifications/\n\
1437 ";
1438 let co = CodeOwners::parse(content).unwrap();
1439 let (billing_sec, _) = co
1440 .match_path(Path::new("src/billing/invoice.ts"))
1441 .map(|m| (m.section, m.section_owners))
1442 .unwrap();
1443 let (notifications_sec, _) = co
1444 .match_path(Path::new("src/notifications/email.ts"))
1445 .map(|m| (m.section, m.section_owners))
1446 .unwrap();
1447 assert_eq!(billing_sec, Some("billing"));
1448 assert_eq!(notifications_sec, Some("notifications"));
1449 }
1450
1451 #[test]
1452 fn match_path_empty_owners_for_pre_section_rule() {
1453 let content = "* @default\n[Billing]\nsrc/billing/ @billing\n";
1454 let co = CodeOwners::parse(content).unwrap();
1455 let (section, owners) = co
1456 .match_path(Path::new("README.md"))
1457 .map(|m| (m.section, m.section_owners))
1458 .unwrap();
1459 assert_eq!(section, None);
1460 assert!(owners.is_empty());
1461 }
1462
1463 #[test]
1464 fn owner_count_of_counts_all_matched_owners() {
1465 let content = "\
1466 * @default\n\
1467 src/api/ @backend @payments @security\n\
1468 [Frontend] @ui @design\n\
1469 src/ui/\n\
1470 !src/generated/\n\
1471 ";
1472 let co = CodeOwners::parse(content).unwrap();
1473 assert_eq!(co.owner_count_of(Path::new("src/api/payments.ts")), Some(3));
1474 assert_eq!(co.owner_count_of(Path::new("src/ui/button.tsx")), Some(2));
1475 assert_eq!(co.owner_count_of(Path::new("README.md")), Some(1));
1476 assert_eq!(
1477 co.owner_count_of(Path::new("src/generated/types.ts")),
1478 Some(0)
1479 );
1480 assert_eq!(
1481 co.owner_count_of(Path::new("other/generated/types.ts")),
1482 Some(1)
1483 );
1484 }
1485
1486 #[test]
1487 fn non_section_bracket_pattern_parses_as_rule() {
1488 let content = "[abc]def @owner\n";
1489 let co = CodeOwners::parse(content).unwrap();
1490 assert_eq!(co.rules.len(), 1);
1491 assert_eq!(co.owner_of(Path::new("adef")), Some("@owner"));
1492 }
1493
1494 #[test]
1495 fn pattern_without_trailing_slash_owns_directory_contents() {
1496 let content = "\
1497 src/platform/packages/shared/kbn-try-in-console @elastic/search\n\
1498 /docs @docs-team\n\
1499 ";
1500 let co = CodeOwners::parse(content).unwrap();
1501 assert_eq!(
1502 co.owner_of(Path::new(
1503 "src/platform/packages/shared/kbn-try-in-console/index.ts"
1504 )),
1505 Some("@elastic/search")
1506 );
1507 assert_eq!(
1508 co.owner_of(Path::new(
1509 "src/platform/packages/shared/kbn-try-in-console/src/components/a.tsx"
1510 )),
1511 Some("@elastic/search")
1512 );
1513 assert_eq!(
1514 co.owner_of(Path::new("docs/guide/intro.md")),
1515 Some("@docs-team")
1516 );
1517 assert_eq!(
1518 co.match_path(Path::new("docs/guide/intro.md"))
1519 .map(|m| (m.owner, m.pattern)),
1520 Some((Some("@docs-team"), "/docs"))
1521 );
1522 assert_eq!(co.owner_count_of(Path::new("docs/a.md")), Some(1));
1523 }
1524
1525 #[test]
1526 fn pattern_without_trailing_slash_still_matches_a_file() {
1527 let co = CodeOwners::parse("/package.json @root\nMakefile @build\n").unwrap();
1528 assert_eq!(co.owner_of(Path::new("package.json")), Some("@root"));
1529 assert_eq!(co.owner_of(Path::new("tools/Makefile")), Some("@build"));
1530 }
1531
1532 #[test]
1533 fn pattern_without_trailing_slash_does_not_match_sibling_prefix() {
1534 let co = CodeOwners::parse("/docs @docs-team\n").unwrap();
1535 assert_eq!(co.owner_of(Path::new("docs-old/a.md")), None);
1536 assert_eq!(co.owner_of(Path::new("docs.md")), None);
1537 }
1538
1539 #[test]
1540 fn directory_pattern_keeps_last_match_wins_order() {
1541 let content = "\
1542 /src @general\n\
1543 /src/lib @lib\n\
1544 /src/lib/legacy.ts @legacy\n\
1545 ";
1546 let co = CodeOwners::parse(content).unwrap();
1547 assert_eq!(co.owner_of(Path::new("src/main.ts")), Some("@general"));
1548 assert_eq!(co.owner_of(Path::new("src/lib/a/b.ts")), Some("@lib"));
1549 assert_eq!(co.owner_of(Path::new("src/lib/legacy.ts")), Some("@legacy"));
1550
1551 let reversed = "\
1552 /src/lib @lib\n\
1553 /src @general\n\
1554 ";
1555 let co = CodeOwners::parse(reversed).unwrap();
1556 assert_eq!(co.owner_of(Path::new("src/lib/a/b.ts")), Some("@general"));
1557 }
1558
1559 #[test]
1560 fn trailing_star_matches_direct_children_only() {
1561 let co = CodeOwners::parse("* @default\ndocs/* @docs-team\n").unwrap();
1562 assert_eq!(
1563 co.owner_of(Path::new("docs/getting-started.md")),
1564 Some("@docs-team")
1565 );
1566 assert_eq!(
1567 co.owner_of(Path::new("docs/build-app/troubleshooting.md")),
1568 Some("@default")
1569 );
1570 }
1571
1572 #[test]
1573 fn root_star_owns_root_level_files_only() {
1574 let co = CodeOwners::parse("/* @root\n").unwrap();
1577 assert_eq!(co.owner_of(Path::new("package.json")), Some("@root"));
1578 assert_eq!(co.owner_of(Path::new("src/index.ts")), None);
1579
1580 let co = CodeOwners::parse("* @all\n").unwrap();
1581 assert_eq!(co.owner_of(Path::new("src/deep/index.ts")), Some("@all"));
1582 }
1583
1584 #[test]
1585 fn single_star_does_not_cross_directories() {
1586 let co = CodeOwners::parse("* @default\n/src/*.ts @ts\n").unwrap();
1587 assert_eq!(co.owner_of(Path::new("src/index.ts")), Some("@ts"));
1588 assert_eq!(co.owner_of(Path::new("src/nested/a.ts")), Some("@default"));
1589 }
1590
1591 #[test]
1592 fn wildcard_name_owns_matching_directory_contents() {
1593 let co = CodeOwners::parse("/fixtures/date_* @data\n").unwrap();
1594 assert_eq!(
1595 co.owner_of(Path::new("fixtures/date_nanos/data.json")),
1596 Some("@data")
1597 );
1598 }
1599
1600 #[test]
1601 fn trailing_double_star_keeps_its_meaning() {
1602 let co = CodeOwners::parse("/build/logs/** @ops\n").unwrap();
1603 assert_eq!(co.owner_of(Path::new("build/logs/a/b.log")), Some("@ops"));
1604 assert_eq!(co.owner_of(Path::new("build/other.log")), None);
1605 }
1606
1607 #[test]
1608 fn unanchored_directory_pattern_matches_at_any_depth() {
1609 let co = CodeOwners::parse("apps/ @apps-team\n").unwrap();
1610 assert_eq!(co.owner_of(Path::new("apps/web/a.ts")), Some("@apps-team"));
1611 assert_eq!(
1612 co.owner_of(Path::new("packages/x/apps/web/a.ts")),
1613 Some("@apps-team")
1614 );
1615 }
1616
1617 #[test]
1618 fn negation_without_trailing_slash_clears_directory_contents() {
1619 let content = "\
1620 * @default\n\
1621 !/src/generated\n\
1622 ";
1623 let co = CodeOwners::parse(content).unwrap();
1624 assert_eq!(co.owner_of(Path::new("src/generated/types.ts")), None);
1625 assert_eq!(
1626 co.owner_count_of(Path::new("src/generated/a/b.ts")),
1627 Some(0)
1628 );
1629 assert_eq!(co.owner_of(Path::new("src/main.ts")), Some("@default"));
1630 }
1631
1632 #[test]
1633 fn gitlab_section_pattern_without_trailing_slash_owns_directory_contents() {
1634 let content = "\
1635 [Frontend] @ui\n\
1636 /src/ui\n\
1637 [Backend] @api\n\
1638 /src/api @api-lead\n\
1639 ";
1640 let co = CodeOwners::parse(content).unwrap();
1641 assert_eq!(
1642 co.match_path(Path::new("src/ui/button/a.tsx")).map(|m| (
1643 m.section,
1644 m.section_owners,
1645 m.pattern
1646 )),
1647 Some((Some("Frontend"), ["@ui".to_string()].as_slice(), "/src/ui"))
1648 );
1649 assert_eq!(
1650 co.match_path(Path::new("src/api/users.ts"))
1651 .map(|m| m.section),
1652 Some(Some("Backend"))
1653 );
1654 assert_eq!(
1655 co.owner_of(Path::new("src/api/users.ts")),
1656 Some("@api-lead")
1657 );
1658 }
1659
1660 #[test]
1661 fn parse_ignores_a_leading_bom() {
1662 for content in ["\u{FEFF}* @team\n", "* @team\n"] {
1663 let co = CodeOwners::parse(content).unwrap();
1664 assert_eq!(co.owner_of(Path::new("src/a.ts")), Some("@team"));
1665 assert_eq!(co.owner_count_of(Path::new("src/a.ts")), Some(1));
1666 }
1667 let co = CodeOwners::parse("\u{FEFF}[Docs] @docs\ndocs/\n").unwrap();
1668 assert!(co.has_sections());
1669 assert_eq!(co.owner_of(Path::new("docs/a.md")), Some("@docs"));
1670 }
1671
1672 fn section_and_owners<'a>(co: &'a CodeOwners, path: &str) -> (Option<&'a str>, Vec<String>) {
1673 let m = co.match_path(Path::new(path)).unwrap();
1674 (m.section, m.section_owners.to_vec())
1675 }
1676
1677 fn owner_list(items: &[&str]) -> Vec<String> {
1678 items.iter().map(|item| (*item).to_string()).collect()
1679 }
1680
1681 #[test]
1682 fn repeated_section_headers_merge_their_default_owners() {
1683 let co = CodeOwners::parse(
1684 "[Team] @alice\nsrc/a/\n!src/a/vendor/\n[Other] @carol\nsrc/c/\n[Team] @bob\nsrc/b/\n",
1685 )
1686 .unwrap();
1687 let team = (Some("Team"), owner_list(&["@alice", "@bob"]));
1688 assert_eq!(section_and_owners(&co, "src/a/x.ts"), team);
1689 assert_eq!(section_and_owners(&co, "src/b/x.ts"), team);
1690 assert_eq!(co.owner_of(Path::new("src/a/x.ts")), Some("@alice"));
1691 assert_eq!(co.owner_of(Path::new("src/b/x.ts")), Some("@bob"));
1692 assert_eq!(co.owner_count_of(Path::new("src/b/x.ts")), Some(1));
1693
1694 let excluded = co.match_path(Path::new("src/a/vendor/x.js")).unwrap();
1695 assert_eq!(excluded.owner, None);
1696 assert_eq!(excluded.owner_count, 0);
1697 assert_eq!(excluded.pattern, "!src/a/vendor/");
1698 assert_eq!(co.owner_count_of(Path::new("src/a/vendor/x.js")), Some(0));
1699 assert_eq!(co.owner_count_of(Path::new("other/x.ts")), None);
1700 }
1701
1702 #[test]
1703 fn repeated_section_headers_merge_without_case() {
1704 let co = CodeOwners::parse("[Docs] @a\ndocs/\n[DOCS] @b\nREADME.md\n").unwrap();
1705 let docs = (Some("Docs"), owner_list(&["@a", "@b"]));
1706 assert_eq!(section_and_owners(&co, "docs/guide.md"), docs);
1707 assert_eq!(section_and_owners(&co, "README.md"), docs);
1708 }
1709
1710 #[test]
1711 fn repeated_section_headers_keep_each_owner_one_time() {
1712 let co = CodeOwners::parse(
1713 "[Team] @alice @bob\nsrc/a/\n[Team]\nsrc/b/ @x\n[Team] @bob @carol\nsrc/c/\n",
1714 )
1715 .unwrap();
1716 let team = (Some("Team"), owner_list(&["@alice", "@bob", "@carol"]));
1717 for path in ["src/a/x.ts", "src/b/x.ts", "src/c/x.ts"] {
1718 assert_eq!(section_and_owners(&co, path), team, "{path}");
1719 }
1720 }
1721
1722 #[test]
1723 fn a_section_header_keeps_each_default_owner_one_time() {
1724 let co = CodeOwners::parse("[Team] @a @b @a\nsrc/\n").unwrap();
1725 assert_eq!(
1726 section_and_owners(&co, "src/x.ts"),
1727 (Some("Team"), owner_list(&["@a", "@b"]))
1728 );
1729 assert_eq!(co.owner_count_of(Path::new("src/x.ts")), Some(3));
1730 }
1731}