1use std::path::{Component, Path, PathBuf};
4
5use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
6use ignore::{IncrementalIgnore, WalkBuilder};
7use serde::ser::{Serialize, SerializeStruct, Serializer};
8use thiserror::Error;
9
10use crate::ConfigSource;
11
12pub const IGNORE_POLICY_VERSION: u8 = 1;
14
15pub const PROTECTED_EXCLUDES: &[&str] = &[
17 "**/.git/**",
18 "**/.hg/**",
19 "**/.svn/**",
20 "**/.codegraph/**",
21 "**/.code-system-graph/**",
22];
23
24pub const DEFAULT_EXCLUDES: &[&str] = &[
26 "**/.next/**",
27 "**/.venv/**",
28 "**/.mypy_cache/**",
29 "**/.nox/**",
30 "**/.pytest_cache/**",
31 "**/.ruff_cache/**",
32 "**/.tox/**",
33 "**/venv/**",
34 "**/env/**",
35 "**/site-packages/**",
36 "**/node_modules/**",
37 "**/vendor/**",
38 "**/target/**",
39 "**/dist/**",
40 "**/build/**",
41 "**/__pycache__/**",
42];
43
44const PROTECTED_DIRECTORY_NAMES: &[&str] =
45 &[".git", ".hg", ".svn", ".codegraph", ".code-system-graph"];
46
47#[derive(Debug, Error)]
49pub enum IgnorePatternError {
50 #[error("ignore pattern must not be empty")]
52 Empty,
53 #[error("ignore pattern `{0}` must contain a repository-relative path component")]
55 MissingPathComponent(String),
56 #[error("ignore pattern `{0}` must be repository-relative")]
58 Absolute(String),
59 #[error("ignore pattern `{0}` must not contain a `..` component")]
61 ParentTraversal(String),
62 #[error("ignore pattern `{0}` must use `/` separators")]
64 Backslash(String),
65 #[error("ignore pattern contains unsafe control or bidirectional characters")]
67 UnsafeCharacters,
68 #[error(
70 "ignore pattern `{0}` uses unsupported glob syntax; only `*`, `?`, and whole-component `**` are supported"
71 )]
72 UnsupportedSyntax(String),
73 #[error("invalid ignore pattern `{pattern}`: {detail}")]
75 InvalidGlob {
76 pattern: String,
78 detail: String,
80 },
81 #[error("includeDefaults pattern `{pattern}` targets protected directory `{directory}`")]
83 ProtectedInclude {
84 pattern: String,
86 directory: String,
88 },
89}
90
91#[derive(Debug, Clone)]
93pub struct IgnorePolicy {
94 configured_excludes: Vec<String>,
95 configured_excludes_source: ConfigSource,
96 include_defaults: Vec<String>,
97 include_defaults_source: ConfigSource,
98 use_gitignore: bool,
99 use_gitignore_source: ConfigSource,
100 protected_matcher: GlobSet,
101 default_matcher: GlobSet,
102 configured_matcher: GlobSet,
103 include_matcher: GlobSet,
104 include_prefixes: Vec<PathBuf>,
105 include_can_match_anywhere: bool,
106}
107
108impl PartialEq for IgnorePolicy {
109 fn eq(&self, other: &Self) -> bool {
110 self.configured_excludes == other.configured_excludes
111 && self.configured_excludes_source == other.configured_excludes_source
112 && self.include_defaults == other.include_defaults
113 && self.include_defaults_source == other.include_defaults_source
114 && self.use_gitignore == other.use_gitignore
115 && self.use_gitignore_source == other.use_gitignore_source
116 }
117}
118
119impl Eq for IgnorePolicy {}
120
121impl Serialize for IgnorePolicy {
122 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
123 where
124 S: Serializer,
125 {
126 let mut state = serializer.serialize_struct("IgnorePolicy", 6)?;
127 state.serialize_field("configured_excludes", &self.configured_excludes)?;
128 state.serialize_field(
129 "configured_excludes_source",
130 &self.configured_excludes_source,
131 )?;
132 state.serialize_field("include_defaults", &self.include_defaults)?;
133 state.serialize_field("include_defaults_source", &self.include_defaults_source)?;
134 state.serialize_field("use_gitignore", &self.use_gitignore)?;
135 state.serialize_field("use_gitignore_source", &self.use_gitignore_source)?;
136 state.end()
137 }
138}
139
140impl IgnorePolicy {
141 pub fn new(
148 configured_excludes: Vec<String>,
149 configured_excludes_source: ConfigSource,
150 include_defaults: Vec<String>,
151 include_defaults_source: ConfigSource,
152 ) -> Result<Self, IgnorePatternError> {
153 Self::with_gitignore(
154 configured_excludes,
155 configured_excludes_source,
156 include_defaults,
157 include_defaults_source,
158 false,
159 ConfigSource::Default,
160 )
161 }
162
163 pub fn with_gitignore(
170 configured_excludes: Vec<String>,
171 configured_excludes_source: ConfigSource,
172 include_defaults: Vec<String>,
173 include_defaults_source: ConfigSource,
174 use_gitignore: bool,
175 use_gitignore_source: ConfigSource,
176 ) -> Result<Self, IgnorePatternError> {
177 let mut configured_excludes = normalize_patterns(configured_excludes)?;
178 let mut include_defaults = normalize_patterns(include_defaults)?;
179 validate_protected_includes(&include_defaults)?;
180 configured_excludes.sort();
181 configured_excludes.dedup();
182 include_defaults.sort();
183 include_defaults.dedup();
184 let (include_prefixes, include_can_match_anywhere) = include_prefixes(&include_defaults);
185 Ok(Self {
186 protected_matcher: compile(PROTECTED_EXCLUDES.iter().copied())?,
187 default_matcher: compile(DEFAULT_EXCLUDES.iter().copied())?,
188 configured_matcher: compile(configured_excludes.iter().map(String::as_str))?,
189 include_matcher: compile(include_defaults.iter().map(String::as_str))?,
190 configured_excludes,
191 configured_excludes_source,
192 include_defaults,
193 include_defaults_source,
194 use_gitignore,
195 use_gitignore_source,
196 include_prefixes,
197 include_can_match_anywhere,
198 })
199 }
200
201 #[must_use]
203 pub fn configured_excludes(&self) -> &[String] {
204 &self.configured_excludes
205 }
206
207 #[must_use]
209 pub const fn configured_excludes_source(&self) -> ConfigSource {
210 self.configured_excludes_source
211 }
212
213 #[must_use]
215 pub fn include_defaults(&self) -> &[String] {
216 &self.include_defaults
217 }
218
219 #[must_use]
221 pub const fn include_defaults_source(&self) -> ConfigSource {
222 self.include_defaults_source
223 }
224
225 #[must_use]
227 pub const fn use_gitignore(&self) -> bool {
228 self.use_gitignore
229 }
230
231 #[must_use]
233 pub const fn use_gitignore_source(&self) -> ConfigSource {
234 self.use_gitignore_source
235 }
236
237 #[must_use]
239 pub fn excludes(&self, relative: &Path, directory: bool) -> bool {
240 let candidate = candidate(relative);
241 let directory_candidate = directory.then(|| format!("{candidate}/"));
242 let matches = |matcher: &GlobSet| {
243 matcher.is_match(&candidate)
244 || directory_candidate
245 .as_deref()
246 .is_some_and(|candidate| matcher.is_match(candidate))
247 };
248 if matches(&self.protected_matcher) || matches(&self.configured_matcher) {
249 return true;
250 }
251 matches(&self.default_matcher)
252 && !matches(&self.include_matcher)
253 && !(directory && self.may_contain_included_default(relative))
254 }
255
256 #[must_use]
258 pub fn fingerprint_material(&self) -> String {
259 format!(
260 "version={IGNORE_POLICY_VERSION};protected={PROTECTED_EXCLUDES:?};defaults={DEFAULT_EXCLUDES:?};\
261 excludes={:?};excludes_source={:?};include_defaults={:?};include_defaults_source={:?};\
262 use_gitignore={};use_gitignore_source={:?}",
263 self.configured_excludes,
264 self.configured_excludes_source,
265 self.include_defaults,
266 self.include_defaults_source,
267 self.use_gitignore,
268 self.use_gitignore_source
269 )
270 }
271
272 fn may_contain_included_default(&self, directory: &Path) -> bool {
273 if self.include_can_match_anywhere {
274 return true;
275 }
276 self.include_prefixes
277 .iter()
278 .any(|prefix| prefix.starts_with(directory) || directory.starts_with(prefix))
279 }
280}
281
282#[derive(Debug, Error)]
284pub enum RepositoryDiscoveryError {
285 #[error("repository discovery failed under `{root}`: {source}")]
287 Ignore {
288 root: PathBuf,
290 #[source]
292 source: ignore::Error,
293 },
294 #[error("repository discovery path `{path}` escaped root `{root}`")]
296 OutsideRoot {
297 root: PathBuf,
299 path: PathBuf,
301 },
302}
303
304#[derive(Debug, Clone)]
306pub struct RepositoryPathMatcher {
307 policy: IgnorePolicy,
308 gitignore: Option<IncrementalIgnore>,
309}
310
311impl RepositoryPathMatcher {
312 #[must_use]
314 pub fn new(root: &Path, policy: IgnorePolicy) -> Self {
315 let gitignore = policy
316 .use_gitignore()
317 .then(|| {
318 let mut matchers = gitignore_walk_builder(root, true).build_matchers();
319 matchers.pop()
320 })
321 .flatten();
322 Self { policy, gitignore }
323 }
324
325 pub fn excludes(
331 &mut self,
332 relative: &Path,
333 directory: bool,
334 ) -> Result<bool, RepositoryDiscoveryError> {
335 if self.policy.excludes(relative, directory) {
336 return Ok(true);
337 }
338 let Some(matcher) = self.gitignore.as_mut() else {
339 return Ok(false);
340 };
341 let (match_result, error) = matcher.matched_with_errors(relative, directory);
342 if let Some(source) = error {
343 return Err(RepositoryDiscoveryError::Ignore {
344 root: matcher.root().to_path_buf(),
345 source,
346 });
347 }
348 Ok(match_result.is_ignore())
349 }
350}
351
352pub fn discover_repository_files(
360 root: &Path,
361 policy: &IgnorePolicy,
362 max_depth: Option<usize>,
363) -> Result<Vec<PathBuf>, RepositoryDiscoveryError> {
364 discover_repository_files_matching(root, policy, max_depth, None, |_| true)
365}
366
367pub(crate) fn discover_repository_files_matching(
368 root: &Path,
369 policy: &IgnorePolicy,
370 max_depth: Option<usize>,
371 max_results: Option<usize>,
372 mut matches: impl FnMut(&Path) -> bool,
373) -> Result<Vec<PathBuf>, RepositoryDiscoveryError> {
374 let mut builder = gitignore_walk_builder(root, policy.use_gitignore());
375 if let Some(max_depth) = max_depth {
376 builder.max_depth(Some(max_depth));
377 }
378 let filter_policy = policy.clone();
379 let filter_root = root.to_path_buf();
380 builder.filter_entry(move |entry| {
381 if entry.depth() == 0 {
382 return true;
383 }
384 let Some(file_type) = entry.file_type() else {
385 return false;
386 };
387 if file_type.is_symlink() {
388 return false;
389 }
390 entry
391 .path()
392 .strip_prefix(&filter_root)
393 .is_ok_and(|relative| !filter_policy.excludes(relative, file_type.is_dir()))
394 });
395 builder.sort_by_file_path(std::path::Path::cmp);
396
397 let mut files = Vec::new();
398 for entry in builder.build() {
399 let entry = entry.map_err(|source| RepositoryDiscoveryError::Ignore {
400 root: root.to_path_buf(),
401 source,
402 })?;
403 let Some(file_type) = entry.file_type() else {
404 continue;
405 };
406 if entry.depth() == 0 || !file_type.is_file() || file_type.is_symlink() {
407 continue;
408 }
409 let relative =
410 entry
411 .path()
412 .strip_prefix(root)
413 .map_err(|_| RepositoryDiscoveryError::OutsideRoot {
414 root: root.to_path_buf(),
415 path: entry.path().to_path_buf(),
416 })?;
417 if !matches(relative) {
418 continue;
419 }
420 files.push(relative.to_path_buf());
421 if max_results.is_some_and(|limit| files.len() >= limit) {
422 break;
423 }
424 }
425 files.sort();
426 files.dedup();
427 Ok(files)
428}
429
430fn gitignore_walk_builder(root: &Path, use_gitignore: bool) -> WalkBuilder {
431 let mut builder = WalkBuilder::new(root);
432 builder
433 .standard_filters(false)
434 .hidden(false)
435 .parents(false)
436 .ignore(false)
437 .git_ignore(use_gitignore)
438 .git_global(false)
439 .git_exclude(false)
440 .require_git(false)
441 .follow_links(false);
442 builder
443}
444
445pub fn validate_excludes(patterns: &[String]) -> Result<(), IgnorePatternError> {
451 let normalized = normalize_patterns(patterns)?;
452 compile(normalized.iter().map(String::as_str)).map(|_| ())
453}
454
455pub fn validate_include_defaults(patterns: &[String]) -> Result<(), IgnorePatternError> {
462 let normalized = normalize_patterns(patterns)?;
463 validate_protected_includes(&normalized)?;
464 compile(normalized.iter().map(String::as_str)).map(|_| ())
465}
466
467fn validate_protected_includes(patterns: &[String]) -> Result<(), IgnorePatternError> {
468 for pattern in patterns {
469 for component in pattern.split('/') {
470 if PROTECTED_DIRECTORY_NAMES.contains(&component) {
471 return Err(IgnorePatternError::ProtectedInclude {
472 pattern: pattern.clone(),
473 directory: component.to_owned(),
474 });
475 }
476 }
477 }
478 Ok(())
479}
480
481fn normalize_patterns<I, S>(patterns: I) -> Result<Vec<String>, IgnorePatternError>
482where
483 I: IntoIterator<Item = S>,
484 S: AsRef<str>,
485{
486 patterns
487 .into_iter()
488 .map(|pattern| normalize_pattern(pattern.as_ref()))
489 .collect()
490}
491
492fn normalize_pattern(pattern: &str) -> Result<String, IgnorePatternError> {
493 if pattern.trim().is_empty() {
494 return Err(IgnorePatternError::Empty);
495 }
496 if absolute_pattern(pattern) {
497 return Err(IgnorePatternError::Absolute(pattern.to_owned()));
498 }
499 if pattern.contains('\\') {
500 return Err(IgnorePatternError::Backslash(pattern.to_owned()));
501 }
502 if pattern.split('/').any(|component| component == "..") {
503 return Err(IgnorePatternError::ParentTraversal(pattern.to_owned()));
504 }
505 if pattern.chars().any(unsafe_character) {
506 return Err(IgnorePatternError::UnsafeCharacters);
507 }
508
509 let directory_only = pattern.ends_with('/')
510 || pattern
511 .split('/')
512 .rfind(|component| !component.is_empty())
513 .is_some_and(|component| component == ".");
514 let components = pattern
515 .split('/')
516 .filter(|component| !component.is_empty() && *component != ".")
517 .collect::<Vec<_>>();
518 if components.is_empty() {
519 return Err(IgnorePatternError::MissingPathComponent(pattern.to_owned()));
520 }
521 validate_supported_syntax(pattern, &components)?;
522
523 let mut normalized = components.join("/");
524 if absolute_pattern(&normalized) {
525 return Err(IgnorePatternError::Absolute(pattern.to_owned()));
526 }
527 if directory_only {
528 normalized.push('/');
529 }
530 Ok(normalized)
531}
532
533fn validate_supported_syntax(pattern: &str, components: &[&str]) -> Result<(), IgnorePatternError> {
534 let unsupported_delimiter = pattern.contains(['[', ']', '{', '}']);
535 let unsupported_recursive = components
536 .iter()
537 .any(|component| component.contains("**") && *component != "**");
538 if unsupported_delimiter || unsupported_recursive {
539 return Err(IgnorePatternError::UnsupportedSyntax(pattern.to_owned()));
540 }
541 Ok(())
542}
543
544fn absolute_pattern(pattern: &str) -> bool {
545 pattern.starts_with('/')
546 || pattern
547 .as_bytes()
548 .get(1)
549 .is_some_and(|separator| *separator == b':')
550}
551
552fn compile<'a>(patterns: impl Iterator<Item = &'a str>) -> Result<GlobSet, IgnorePatternError> {
553 let mut builder = GlobSetBuilder::new();
554 for pattern in patterns {
555 let glob = GlobBuilder::new(pattern)
556 .literal_separator(true)
557 .backslash_escape(false)
558 .build()
559 .map_err(|error| IgnorePatternError::InvalidGlob {
560 pattern: pattern.to_owned(),
561 detail: error.to_string(),
562 })?;
563 builder.add(glob);
564 }
565 builder
566 .build()
567 .map_err(|error| IgnorePatternError::InvalidGlob {
568 pattern: "<set>".to_owned(),
569 detail: error.to_string(),
570 })
571}
572
573fn include_prefixes(patterns: &[String]) -> (Vec<PathBuf>, bool) {
574 let mut prefixes = Vec::new();
575 let mut can_match_anywhere = false;
576 for pattern in patterns {
577 let mut prefix = PathBuf::new();
578 for component in pattern.split('/') {
579 if component.contains(['*', '?']) {
580 break;
581 }
582 if !component.is_empty() {
583 prefix.push(component);
584 }
585 }
586 if prefix.as_os_str().is_empty() {
587 can_match_anywhere = true;
588 } else {
589 prefixes.push(prefix);
590 }
591 }
592 prefixes.sort();
593 prefixes.dedup();
594 (prefixes, can_match_anywhere)
595}
596
597fn candidate(path: &Path) -> String {
598 path.components()
599 .filter_map(|component| match component {
600 Component::Normal(value) => Some(value.to_string_lossy()),
601 _ => None,
602 })
603 .collect::<Vec<_>>()
604 .join("/")
605}
606
607fn unsafe_character(character: char) -> bool {
608 character.is_control()
609 || matches!(
610 character,
611 '\u{061c}'
612 | '\u{200e}'
613 | '\u{200f}'
614 | '\u{202a}'..='\u{202e}'
615 | '\u{2066}'..='\u{2069}'
616 )
617}
618
619#[cfg(test)]
620mod tests {
621 use std::fs;
622
623 use tempfile::tempdir;
624
625 use super::*;
626
627 #[test]
628 fn bounded_matching_discovery_should_stop_after_the_requested_results()
629 -> Result<(), Box<dyn std::error::Error>> {
630 let repository = tempdir()?;
631 for index in 0..40 {
632 fs::write(
633 repository.path().join(format!("openapi-{index:02}.yaml")),
634 "openapi: 3.1.0\n",
635 )?;
636 }
637 let mut visited = 0_usize;
638 let files = discover_repository_files_matching(
639 repository.path(),
640 &policy(&[], &[]),
641 None,
642 Some(32),
643 |_| {
644 visited += 1;
645 true
646 },
647 )?;
648
649 assert_eq!(files.len(), 32);
650 assert_eq!(visited, 32);
651 Ok(())
652 }
653
654 fn policy(excludes: &[&str], includes: &[&str]) -> IgnorePolicy {
655 IgnorePolicy::new(
656 excludes.iter().map(ToString::to_string).collect(),
657 ConfigSource::WorkspaceManifest,
658 includes.iter().map(ToString::to_string).collect(),
659 ConfigSource::WorkspaceManifest,
660 )
661 .expect("valid fixture policy")
662 }
663
664 fn gitignore_policy(excludes: &[&str], includes: &[&str]) -> IgnorePolicy {
665 IgnorePolicy::with_gitignore(
666 excludes.iter().map(ToString::to_string).collect(),
667 ConfigSource::WorkspaceManifest,
668 includes.iter().map(ToString::to_string).collect(),
669 ConfigSource::WorkspaceManifest,
670 true,
671 ConfigSource::WorkspaceManifest,
672 )
673 .expect("valid fixture policy")
674 }
675
676 fn write(root: &Path, relative: &str, contents: &str) {
677 let path = root.join(relative);
678 if let Some(parent) = path.parent() {
679 fs::create_dir_all(parent).expect("create fixture parent");
680 }
681 fs::write(path, contents).expect("write fixture");
682 }
683
684 #[test]
685 fn gitignore_should_be_opt_in_and_support_nested_rules_and_negation() {
686 let checkout = tempdir().expect("checkout");
687 let root = checkout.path();
688 write(
689 root,
690 ".gitignore",
691 "ignored/*\n!ignored/keep.rs\nspace\\ path.rs\n",
692 );
693 write(root, "ignored/drop.rs", "drop");
694 write(root, "ignored/keep.rs", "keep");
695 write(root, "space path.rs", "space");
696 write(root, "nested/.gitignore", "*.rs\n!keep.rs\n");
697 write(root, "nested/drop.rs", "drop");
698 write(root, "nested/keep.rs", "keep");
699
700 let enabled = discover_repository_files(root, &gitignore_policy(&[], &[]), None)
701 .expect("enabled discovery");
702 assert!(enabled.contains(&PathBuf::from("ignored/keep.rs")));
703 assert!(enabled.contains(&PathBuf::from("nested/keep.rs")));
704 assert!(!enabled.contains(&PathBuf::from("ignored/drop.rs")));
705 assert!(!enabled.contains(&PathBuf::from("nested/drop.rs")));
706 assert!(!enabled.contains(&PathBuf::from("space path.rs")));
707
708 let disabled =
709 discover_repository_files(root, &policy(&[], &[]), None).expect("disabled discovery");
710 assert!(disabled.contains(&PathBuf::from("ignored/drop.rs")));
711 assert!(disabled.contains(&PathBuf::from("nested/drop.rs")));
712 assert!(disabled.contains(&PathBuf::from("space path.rs")));
713 }
714
715 #[test]
716 fn gitignore_should_not_read_parent_dot_ignore_or_git_exclude_rules() {
717 let parent = tempdir().expect("parent");
718 let root = parent.path().join("checkout");
719 fs::create_dir_all(root.join(".git/info")).expect("git metadata");
720 write(parent.path(), ".gitignore", "from-parent.rs\n");
721 write(&root, ".ignore", "from-dot-ignore.rs\n");
722 write(&root, ".git/info/exclude", "from-git-exclude.rs\n");
723 for file in [
724 "from-parent.rs",
725 "from-dot-ignore.rs",
726 "from-git-exclude.rs",
727 ] {
728 write(&root, file, file);
729 }
730
731 let files =
732 discover_repository_files(&root, &gitignore_policy(&[], &[]), None).expect("discovery");
733 for file in [
734 "from-parent.rs",
735 "from-dot-ignore.rs",
736 "from-git-exclude.rs",
737 ] {
738 assert!(files.contains(&PathBuf::from(file)), "missing {file}");
739 }
740 }
741
742 #[test]
743 fn explicit_and_protected_exclusions_should_override_gitignore_negations() {
744 let checkout = tempdir().expect("checkout");
745 let root = checkout.path();
746 write(
747 root,
748 ".gitignore",
749 "!generated/private.rs\n!vendor/sdk/lib.rs\n!.git/config\n",
750 );
751 write(root, "generated/private.rs", "private");
752 write(root, "vendor/sdk/lib.rs", "sdk");
753 write(root, ".git/config", "config");
754
755 let files = discover_repository_files(
756 root,
757 &gitignore_policy(&["generated/**"], &["vendor/sdk/**"]),
758 None,
759 )
760 .expect("discovery");
761 assert!(!files.contains(&PathBuf::from("generated/private.rs")));
762 assert!(files.contains(&PathBuf::from("vendor/sdk/lib.rs")));
763 assert!(!files.contains(&PathBuf::from(".git/config")));
764 }
765
766 #[test]
767 fn path_matcher_should_follow_nested_gitignore_rules() {
768 let checkout = tempdir().expect("checkout");
769 let root = checkout.path();
770 write(root, ".gitignore", "root.rs\n");
771 write(root, "nested/.gitignore", "*.rs\n!keep.rs\n");
772 let mut matcher = RepositoryPathMatcher::new(root, gitignore_policy(&[], &[]));
773
774 assert!(matcher.excludes(Path::new("root.rs"), false).expect("root"));
775 assert!(
776 matcher
777 .excludes(Path::new("nested/drop.rs"), false)
778 .expect("nested drop")
779 );
780 assert!(
781 !matcher
782 .excludes(Path::new("nested/keep.rs"), false)
783 .expect("nested keep")
784 );
785 }
786
787 #[test]
788 fn defaults_should_exclude_nested_dependency_tree() {
789 assert!(policy(&[], &[]).excludes(Path::new("web/node_modules/react/index.js"), false));
790 }
791
792 #[test]
793 fn configured_excludes_should_match_repository_relative_globs() {
794 assert!(policy(&["coverage/**"], &[]).excludes(Path::new("coverage/lcov.info"), false));
795 }
796
797 #[test]
798 fn configured_excludes_should_support_single_component_wildcards() {
799 assert!(policy(&["src/*/?.rs"], &[]).excludes(Path::new("src/api/x.rs"), false));
800 }
801
802 #[test]
803 fn configured_excludes_should_normalize_and_deduplicate_patterns() {
804 let policy = policy(&["./coverage//**", "coverage/./**", "coverage/**"], &[]);
805
806 assert_eq!(policy.configured_excludes(), &["coverage/**"]);
807 }
808
809 #[test]
810 fn configured_excludes_should_match_normalized_patterns() {
811 assert!(policy(&["./coverage/./**"], &[]).excludes(Path::new("coverage/lcov.info"), false));
812 }
813
814 #[test]
815 fn directory_patterns_should_preserve_their_terminal_separator() {
816 let policy = policy(&["./coverage//"], &[]);
817
818 assert!(policy.excludes(Path::new("coverage"), true));
819 assert!(!policy.excludes(Path::new("coverage"), false));
820 }
821
822 #[test]
823 fn ordinary_globs_should_match_directories_without_a_terminal_separator() {
824 let policy = policy(&["generated/*"], &[]);
825
826 assert!(policy.excludes(Path::new("generated/output"), true));
827 }
828
829 #[test]
830 fn include_defaults_should_reopen_only_selected_subtree() {
831 let policy = policy(&[], &["./vendor//internal-sdk/./**"]);
832 assert_eq!(
833 (
834 policy.excludes(Path::new("vendor/internal-sdk/src/lib.rs"), false),
835 policy.excludes(Path::new("vendor/external/src/lib.rs"), false),
836 ),
837 (false, true)
838 );
839 }
840
841 #[test]
842 fn configured_excludes_should_override_default_includes() {
843 assert!(
844 policy(
845 &["vendor/internal-sdk/private/**"],
846 &["vendor/internal-sdk/**"]
847 )
848 .excludes(Path::new("vendor/internal-sdk/private/key.rs"), false)
849 );
850 }
851
852 #[test]
853 fn include_defaults_should_keep_ancestor_traversable() {
854 assert!(!policy(&[], &["./vendor//internal-sdk/./**"]).excludes(Path::new("vendor"), true));
855 }
856
857 #[test]
858 fn canonical_equivalent_policies_should_have_the_same_fingerprint() {
859 let canonical = policy(&["coverage/**"], &["vendor/internal-sdk/**"]);
860 let redundant = policy(&["./coverage//./**"], &["./vendor//internal-sdk/./**"]);
861
862 assert_eq!(
863 canonical.fingerprint_material(),
864 redundant.fingerprint_material()
865 );
866 }
867
868 #[test]
869 fn include_defaults_should_reject_protected_directories() {
870 assert!(matches!(
871 validate_include_defaults(&["./.git//config".to_owned()]),
872 Err(IgnorePatternError::ProtectedInclude { .. })
873 ));
874 }
875
876 #[test]
877 fn patterns_should_reject_parent_traversal() {
878 assert!(matches!(
879 validate_excludes(&["./safe/../outside/**".to_owned()]),
880 Err(IgnorePatternError::ParentTraversal(_))
881 ));
882 }
883
884 #[test]
885 fn patterns_should_reject_windows_absolute_paths_after_normalization() {
886 assert!(matches!(
887 validate_excludes(&["./C:/outside/**".to_owned()]),
888 Err(IgnorePatternError::Absolute(_))
889 ));
890 }
891
892 #[test]
893 fn patterns_should_reject_whitespace_only_values() {
894 assert!(matches!(
895 validate_excludes(&[" ".to_owned()]),
896 Err(IgnorePatternError::Empty)
897 ));
898 }
899
900 #[test]
901 fn patterns_should_reject_values_without_path_components() {
902 assert!(matches!(
903 validate_excludes(&["././".to_owned()]),
904 Err(IgnorePatternError::MissingPathComponent(_))
905 ));
906 }
907
908 #[test]
909 fn patterns_should_reject_character_classes() {
910 assert!(matches!(
911 validate_excludes(&["src/[ab]/**".to_owned()]),
912 Err(IgnorePatternError::UnsupportedSyntax(_))
913 ));
914 }
915
916 #[test]
917 fn patterns_should_reject_alternations() {
918 assert!(matches!(
919 validate_excludes(&["{src,test}/**".to_owned()]),
920 Err(IgnorePatternError::UnsupportedSyntax(_))
921 ));
922 }
923
924 #[test]
925 fn patterns_should_reject_non_component_recursive_wildcards() {
926 assert!(matches!(
927 validate_excludes(&["src/**generated/**".to_owned()]),
928 Err(IgnorePatternError::UnsupportedSyntax(_))
929 ));
930 }
931
932 #[test]
933 fn patterns_should_reject_three_star_wildcards() {
934 assert!(matches!(
935 validate_excludes(&["src/***/generated".to_owned()]),
936 Err(IgnorePatternError::UnsupportedSyntax(_))
937 ));
938 }
939}