use crate::cli::{Args, FilterRule, RuleKind};
#[derive(Debug, Clone)]
pub struct MatchSpec {
pub rules: Vec<FilterRule>,
pub respect_gitignore: bool,
pub use_safety_preset: bool,
pub case_sensitive: bool,
}
impl Default for MatchSpec {
fn default() -> Self {
Self {
rules: Vec::new(),
respect_gitignore: false,
use_safety_preset: true,
case_sensitive: true,
}
}
}
impl MatchSpec {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
pub fn normalize_pattern(pattern: &str) -> String {
let pattern = pattern.strip_suffix('/').unwrap_or(pattern);
let pattern = fix_double_star(pattern);
if !pattern.contains('/') {
if !pattern.contains('*') && !pattern.contains('.') {
format!("**/{}/**", pattern)
} else {
format!("**/{}", pattern)
}
} else {
pattern
}
}
pub fn from_args(args: &Args, target_path: &std::path::Path) -> Self {
let rules = args
.filter_rules
.iter()
.map(|r| FilterRule {
kind: r.kind,
pattern: Self::normalize_pattern(&r.pattern),
})
.collect();
let respect_gitignore = match args.use_gitignore {
crate::cli::UseGitignoreMode::Always => true,
crate::cli::UseGitignoreMode::Never => false,
crate::cli::UseGitignoreMode::Auto => Self::is_inside_git_repo(target_path),
};
Self {
rules,
respect_gitignore,
use_safety_preset: args.is_safe_mode(),
case_sensitive: true,
}
}
fn is_inside_git_repo(path: &std::path::Path) -> bool {
let mut current = path;
loop {
if current.join(".git").exists() {
return true;
}
match current.parent() {
Some(parent) => current = parent,
None => return false,
}
}
}
pub fn has_includes(&self) -> bool {
self.rules.iter().any(|r| r.kind == RuleKind::Include)
}
#[allow(dead_code)]
pub fn with_include_glob(mut self, patterns: Vec<String>) -> Self {
for p in patterns {
self.rules.push(FilterRule {
kind: RuleKind::Include,
pattern: Self::normalize_pattern(&p),
});
}
self
}
#[allow(dead_code)]
pub fn with_exclude_glob(mut self, patterns: Vec<String>) -> Self {
for p in patterns {
self.rules.push(FilterRule {
kind: RuleKind::Exclude,
pattern: Self::normalize_pattern(&p),
});
}
self
}
#[allow(dead_code)]
pub fn with_rules(mut self, rules: Vec<FilterRule>) -> Self {
for r in rules {
self.rules.push(FilterRule {
kind: r.kind,
pattern: Self::normalize_pattern(&r.pattern),
});
}
self
}
#[allow(dead_code)]
pub fn with_gitignore(mut self, respect: bool) -> Self {
self.respect_gitignore = respect;
self
}
#[allow(dead_code)]
pub fn with_case_sensitive(mut self, sensitive: bool) -> Self {
self.case_sensitive = sensitive;
self
}
}
fn fix_double_star(pattern: &str) -> String {
let bytes = pattern.as_bytes();
let n = bytes.len();
let mut out = String::with_capacity(n + 4);
let mut i = 0;
while i < n {
let at_segment_start = i == 0 || bytes[i - 1] == b'/';
if at_segment_start
&& i + 2 < n
&& bytes[i] == b'*'
&& bytes[i + 1] == b'*'
&& bytes[i + 2] != b'/'
&& bytes[i + 2] != b'*'
{
out.push_str("**/*");
i += 2;
continue;
}
out.push(bytes[i] as char);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_bare_name_to_recursive_dir() {
assert_eq!(MatchSpec::normalize_pattern("vendor"), "**/vendor/**");
assert_eq!(MatchSpec::normalize_pattern("__tests__"), "**/__tests__/**");
}
#[test]
fn normalize_strips_trailing_slash() {
assert_eq!(MatchSpec::normalize_pattern("hoge/"), "**/hoge/**");
assert_eq!(MatchSpec::normalize_pattern("src/lib/"), "src/lib");
}
#[test]
fn normalize_file_pattern_to_recursive() {
assert_eq!(MatchSpec::normalize_pattern("*.rs"), "**/*.rs");
assert_eq!(MatchSpec::normalize_pattern("foo.txt"), "**/foo.txt");
}
#[test]
fn normalize_keeps_path_patterns() {
assert_eq!(MatchSpec::normalize_pattern("src/*.go"), "src/*.go");
assert_eq!(MatchSpec::normalize_pattern("**/*.md"), "**/*.md");
}
#[test]
fn normalize_fixes_double_star_without_slash() {
assert_eq!(MatchSpec::normalize_pattern("**.json"), "**/*.json");
assert_eq!(MatchSpec::normalize_pattern("**.test.ts"), "**/*.test.ts");
assert_eq!(
MatchSpec::normalize_pattern("**.generated.json"),
"**/*.generated.json"
);
}
#[test]
fn normalize_keeps_valid_double_star() {
assert_eq!(MatchSpec::normalize_pattern("**/*.ts"), "**/*.ts");
assert_eq!(MatchSpec::normalize_pattern("path/**"), "path/**");
assert_eq!(MatchSpec::normalize_pattern("path/**/*.ts"), "path/**/*.ts");
assert_eq!(MatchSpec::normalize_pattern("a/**/b/**.x"), "a/**/b/**/*.x");
}
#[test]
fn has_includes_reflects_rules() {
let spec = MatchSpec::new();
assert!(!spec.has_includes());
let spec = spec.with_include_glob(vec!["*.rs".into()]);
assert!(spec.has_includes());
let only_excl = MatchSpec::new().with_exclude_glob(vec!["build".into()]);
assert!(!only_excl.has_includes());
}
}