1#![deny(missing_docs)]
118
119use std::{
120 borrow::Cow,
121 panic::{RefUnwindSafe, UnwindSafe},
122 path::Path,
123 sync::Arc,
124};
125
126use {
127 aho_corasick::AhoCorasick,
128 bstr::{B, ByteSlice, ByteVec},
129 regex_automata::{
130 PatternSet,
131 meta::Regex,
132 util::pool::{Pool, PoolGuard},
133 },
134};
135
136use crate::{
137 glob::MatchStrategy,
138 pathutil::{file_name, file_name_ext, normalize_path},
139};
140
141pub use crate::glob::{Glob, GlobBuilder, GlobMatcher};
142
143mod fnv;
144mod glob;
145mod pathutil;
146
147#[cfg(feature = "serde1")]
148mod serde_impl;
149
150#[cfg(feature = "log")]
151macro_rules! debug {
152 ($($token:tt)*) => (::log::debug!($($token)*);)
153}
154
155#[cfg(not(feature = "log"))]
156macro_rules! debug {
157 ($($token:tt)*) => {};
158}
159
160#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct Error {
163 glob: Option<String>,
165 kind: ErrorKind,
167}
168
169#[derive(Clone, Debug, Eq, PartialEq)]
171#[non_exhaustive]
172pub enum ErrorKind {
173 InvalidRecursive,
181 UnclosedClass,
183 InvalidRange(char, char),
187 UnopenedAlternates,
189 UnclosedAlternates,
191 NestedAlternates,
197 TooManyNestedAlternates,
199 DanglingEscape,
201 Regex(String),
203}
204
205impl std::error::Error for Error {
206 fn description(&self) -> &str {
207 self.kind.description()
208 }
209}
210
211impl Error {
212 pub fn glob(&self) -> Option<&str> {
214 self.glob.as_ref().map(|s| &**s)
215 }
216
217 pub fn kind(&self) -> &ErrorKind {
219 &self.kind
220 }
221}
222
223impl ErrorKind {
224 fn description(&self) -> &str {
225 match *self {
226 ErrorKind::InvalidRecursive => {
227 "invalid use of **; must be one path component"
228 }
229 ErrorKind::UnclosedClass => {
230 "unclosed character class; missing ']'"
231 }
232 ErrorKind::InvalidRange(_, _) => "invalid character range",
233 ErrorKind::UnopenedAlternates => {
234 "unopened alternate group; missing '{' \
235 (maybe escape '}' with '[}]'?)"
236 }
237 ErrorKind::UnclosedAlternates => {
238 "unclosed alternate group; missing '}' \
239 (maybe escape '{' with '[{]'?)"
240 }
241 ErrorKind::NestedAlternates => {
242 "nested alternate groups are not allowed"
243 }
244 ErrorKind::TooManyNestedAlternates => {
245 "alternate groups nested too deeply"
246 }
247 ErrorKind::DanglingEscape => "dangling '\\'",
248 ErrorKind::Regex(ref err) => err,
249 }
250 }
251}
252
253impl std::fmt::Display for Error {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 match self.glob {
256 None => self.kind.fmt(f),
257 Some(ref glob) => {
258 write!(f, "error parsing glob '{}': {}", glob, self.kind)
259 }
260 }
261 }
262}
263
264impl std::fmt::Display for ErrorKind {
265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266 match *self {
267 ErrorKind::InvalidRecursive
268 | ErrorKind::UnclosedClass
269 | ErrorKind::UnopenedAlternates
270 | ErrorKind::UnclosedAlternates
271 | ErrorKind::NestedAlternates
272 | ErrorKind::TooManyNestedAlternates
273 | ErrorKind::DanglingEscape
274 | ErrorKind::Regex(_) => write!(f, "{}", self.description()),
275 ErrorKind::InvalidRange(s, e) => {
276 write!(f, "invalid range; '{}' > '{}'", s, e)
277 }
278 }
279 }
280}
281
282fn new_regex(pat: &str) -> Result<Regex, Error> {
283 let syntax = regex_automata::util::syntax::Config::new()
284 .utf8(false)
285 .dot_matches_new_line(true);
286 let config = Regex::config()
287 .utf8_empty(false)
288 .nfa_size_limit(Some(10 * (1 << 20)))
289 .hybrid_cache_capacity(10 * (1 << 20));
290 Regex::builder().syntax(syntax).configure(config).build(pat).map_err(
291 |err| Error {
292 glob: Some(pat.to_string()),
293 kind: ErrorKind::Regex(err.to_string()),
294 },
295 )
296}
297
298fn new_regex_set(pats: Vec<String>) -> Result<Regex, Error> {
299 let syntax = regex_automata::util::syntax::Config::new()
300 .utf8(false)
301 .dot_matches_new_line(true);
302 let config = Regex::config()
303 .match_kind(regex_automata::MatchKind::All)
304 .utf8_empty(false)
305 .nfa_size_limit(Some(10 * (1 << 20)))
306 .hybrid_cache_capacity(10 * (1 << 20));
307 Regex::builder()
308 .syntax(syntax)
309 .configure(config)
310 .build_many(&pats)
311 .map_err(|err| Error {
312 glob: None,
313 kind: ErrorKind::Regex(err.to_string()),
314 })
315}
316
317#[derive(Clone)]
320pub struct GlobSet {
321 len: usize,
322 strats: Vec<GlobSetMatchStrategy>,
323 pats: Vec<Glob>,
324}
325
326impl std::fmt::Debug for GlobSet {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 f.debug_tuple("GlobSet").field(&self.pats).finish()
329 }
330}
331
332impl GlobSet {
333 #[inline]
337 pub fn builder() -> GlobSetBuilder {
338 GlobSetBuilder::new()
339 }
340
341 #[inline]
343 pub const fn empty() -> GlobSet {
344 GlobSet { len: 0, strats: vec![], pats: vec![] }
345 }
346
347 #[inline]
349 pub fn is_empty(&self) -> bool {
350 self.len == 0
351 }
352
353 #[inline]
355 pub fn len(&self) -> usize {
356 self.len
357 }
358
359 pub fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
361 self.is_match_candidate(&Candidate::new(path.as_ref()))
362 }
363
364 pub fn is_match_candidate(&self, path: &Candidate<'_>) -> bool {
369 if self.is_empty() {
370 return false;
371 }
372 for strat in &self.strats {
373 if strat.is_match(path) {
374 return true;
375 }
376 }
377 false
378 }
379
380 pub fn matches_all<P: AsRef<Path>>(&self, path: P) -> bool {
398 self.matches_all_candidate(&Candidate::new(path.as_ref()))
399 }
400
401 pub fn matches_all_candidate(&self, path: &Candidate<'_>) -> bool {
409 for strat in &self.strats {
410 if !strat.matches_all(path) {
411 return false;
412 }
413 }
414 true
415 }
416
417 pub fn matches<P: AsRef<Path>>(&self, path: P) -> Vec<usize> {
420 self.matches_candidate(&Candidate::new(path.as_ref()))
421 }
422
423 pub fn matches_candidate(&self, path: &Candidate<'_>) -> Vec<usize> {
429 let mut into = vec![];
430 if self.is_empty() {
431 return into;
432 }
433 self.matches_candidate_into(path, &mut into);
434 into
435 }
436
437 pub fn matches_into<P: AsRef<Path>>(
444 &self,
445 path: P,
446 into: &mut Vec<usize>,
447 ) {
448 self.matches_candidate_into(&Candidate::new(path.as_ref()), into);
449 }
450
451 pub fn matches_candidate_into(
461 &self,
462 path: &Candidate<'_>,
463 into: &mut Vec<usize>,
464 ) {
465 into.clear();
466 if self.is_empty() {
467 return;
468 }
469 for strat in &self.strats {
470 strat.matches_into(path, into);
471 }
472 into.sort();
473 into.dedup();
474 }
475
476 pub fn new<I, G>(globs: I) -> Result<GlobSet, Error>
480 where
481 I: IntoIterator<Item = G>,
482 G: AsRef<Glob>,
483 {
484 let mut it = globs.into_iter().peekable();
485 if it.peek().is_none() {
486 return Ok(GlobSet::empty());
487 }
488
489 let mut len = 0;
490 let mut pats = vec![];
491 let mut lits = LiteralStrategy::new();
492 let mut base_lits = LiteralStrategy::new();
493 let mut exts = ExtensionStrategy::new();
494 let mut prefixes = MultiStrategyBuilder::new();
495 let mut suffixes = MultiStrategyBuilder::new();
496 let mut required_exts = RequiredExtensionStrategyBuilder::new();
497 let mut base_regexes = MultiStrategyBuilder::new();
498 let mut regexes = MultiStrategyBuilder::new();
499 for (i, p) in it.enumerate() {
500 len += 1;
501
502 let p = p.as_ref();
503 pats.push(p.clone());
504 match MatchStrategy::new(p) {
505 MatchStrategy::Literal(lit) => {
506 lits.add(i, lit);
507 }
508 MatchStrategy::BasenameLiteral(lit) => {
509 base_lits.add(i, lit);
510 }
511 MatchStrategy::Extension(ext) => {
512 exts.add(i, ext);
513 }
514 MatchStrategy::Prefix(prefix) => {
515 prefixes.add(i, prefix);
516 }
517 MatchStrategy::Suffix { suffix, component } => {
518 if component {
519 lits.add(i, suffix[1..].to_string());
520 }
521 suffixes.add(i, suffix);
522 }
523 MatchStrategy::RequiredExtension(ext) => {
524 required_exts.add(i, ext, p.regex().to_owned());
525 }
526 MatchStrategy::BasenameRegex(re) => {
527 base_regexes.add(i, re);
528 }
529 MatchStrategy::Regex => {
530 debug!(
531 "glob `{:?}` converted to regex: `{:?}`",
532 p,
533 p.regex()
534 );
535 regexes.add(i, p.regex().to_owned());
536 }
537 }
538 }
539 debug!(
540 "built glob set; {} literals, {} basenames, {} extensions, \
541 {} prefixes, {} suffixes, {} required extensions, \
542 {} basename regexes, {} regexes",
543 lits.literals.len(),
544 base_lits.literals.len(),
545 exts.0.len(),
546 prefixes.literals.len(),
547 suffixes.literals.len(),
548 required_exts.0.len(),
549 base_regexes.literals.len(),
550 regexes.literals.len()
551 );
552 let mut strats = Vec::with_capacity(8);
553 if !exts.0.is_empty() {
555 strats.push(GlobSetMatchStrategy::Extension(exts));
556 }
557 if !base_lits.literals.is_empty() {
558 strats.push(GlobSetMatchStrategy::BasenameLiteral(base_lits));
559 }
560 if !lits.literals.is_empty() {
561 strats.push(GlobSetMatchStrategy::Literal(lits));
562 }
563 if !suffixes.is_empty() {
564 strats.push(GlobSetMatchStrategy::Suffix(suffixes.suffix()));
565 }
566 if !prefixes.is_empty() {
567 strats.push(GlobSetMatchStrategy::Prefix(prefixes.prefix()));
568 }
569 if !required_exts.0.is_empty() {
570 strats.push(GlobSetMatchStrategy::RequiredExtension(
571 required_exts.build()?,
572 ));
573 }
574 if !base_regexes.is_empty() {
575 let mut set = base_regexes.regex_set()?;
576 set.basename = true;
577 strats.push(GlobSetMatchStrategy::Regex(set));
578 }
579 if !regexes.is_empty() {
580 strats.push(GlobSetMatchStrategy::Regex(regexes.regex_set()?));
581 }
582
583 Ok(GlobSet { len, strats, pats })
584 }
585}
586
587impl Default for GlobSet {
588 fn default() -> Self {
590 GlobSet::empty()
591 }
592}
593
594#[derive(Clone, Debug)]
597pub struct GlobSetBuilder {
598 pats: Vec<Glob>,
599}
600
601impl GlobSetBuilder {
602 pub fn new() -> GlobSetBuilder {
606 GlobSetBuilder { pats: vec![] }
607 }
608
609 pub fn build(&self) -> Result<GlobSet, Error> {
613 GlobSet::new(self.pats.iter())
614 }
615
616 pub fn add(&mut self, pat: Glob) -> &mut GlobSetBuilder {
618 self.pats.push(pat);
619 self
620 }
621}
622
623#[derive(Clone)]
630pub struct Candidate<'a> {
631 path: Cow<'a, [u8]>,
632 basename: Cow<'a, [u8]>,
633 ext: Cow<'a, [u8]>,
634}
635
636impl<'a> std::fmt::Debug for Candidate<'a> {
637 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
638 f.debug_struct("Candidate")
639 .field("path", &self.path.as_bstr())
640 .field("basename", &self.basename.as_bstr())
641 .field("ext", &self.ext.as_bstr())
642 .finish()
643 }
644}
645
646impl<'a> Candidate<'a> {
647 pub fn new<P: AsRef<Path> + ?Sized>(path: &'a P) -> Candidate<'a> {
649 Self::from_cow(Vec::from_path_lossy(path.as_ref()))
650 }
651
652 pub fn from_bytes<P: AsRef<[u8]> + ?Sized>(path: &'a P) -> Candidate<'a> {
661 Self::from_cow(Cow::Borrowed(path.as_ref()))
662 }
663
664 fn from_cow(path: Cow<'a, [u8]>) -> Candidate<'a> {
665 let path = normalize_path(path);
666 let basename = file_name(&path).unwrap_or(Cow::Borrowed(B("")));
667 let ext = file_name_ext(&basename).unwrap_or(Cow::Borrowed(B("")));
668 Candidate { path, basename, ext }
669 }
670
671 fn path_prefix(&self, max: usize) -> &[u8] {
672 if self.path.len() <= max { &*self.path } else { &self.path[..max] }
673 }
674
675 fn basename_for_regex(&self) -> &[u8] {
677 if self.basename.is_empty() && self.path.ends_with(b"..") {
679 b".."
680 } else {
681 &self.basename
682 }
683 }
684
685 fn path_suffix(&self, max: usize) -> &[u8] {
686 if self.path.len() <= max {
687 &*self.path
688 } else {
689 &self.path[self.path.len() - max..]
690 }
691 }
692}
693
694#[derive(Clone, Debug)]
695enum GlobSetMatchStrategy {
696 Literal(LiteralStrategy),
697 BasenameLiteral(LiteralStrategy),
698 Extension(ExtensionStrategy),
699 Prefix(PrefixStrategy),
700 Suffix(SuffixStrategy),
701 RequiredExtension(RequiredExtensionStrategy),
702 Regex(RegexSetStrategy),
703}
704
705impl GlobSetMatchStrategy {
706 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
707 use self::GlobSetMatchStrategy::*;
708 match *self {
709 Literal(ref s) => s.is_match(candidate.path.as_bytes()),
710 BasenameLiteral(ref s) => {
711 !candidate.basename.is_empty()
712 && s.is_match(candidate.basename.as_bytes())
713 }
714 Extension(ref s) => s.is_match(candidate),
715 Prefix(ref s) => s.is_match(candidate),
716 Suffix(ref s) => s.is_match(candidate),
717 RequiredExtension(ref s) => s.is_match(candidate),
718 Regex(ref s) => s.is_match(candidate),
719 }
720 }
721
722 fn matches_into(
723 &self,
724 candidate: &Candidate<'_>,
725 matches: &mut Vec<usize>,
726 ) {
727 use self::GlobSetMatchStrategy::*;
728 match *self {
729 Literal(ref s) => {
730 s.matches_into(candidate.path.as_bytes(), matches)
731 }
732 BasenameLiteral(ref s) => {
733 if !candidate.basename.is_empty() {
734 s.matches_into(candidate.basename.as_bytes(), matches);
735 }
736 }
737 Extension(ref s) => s.matches_into(candidate, matches),
738 Prefix(ref s) => s.matches_into(candidate, matches),
739 Suffix(ref s) => s.matches_into(candidate, matches),
740 RequiredExtension(ref s) => s.matches_into(candidate, matches),
741 Regex(ref s) => s.matches_into(candidate, matches),
742 }
743 }
744
745 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
746 use self::GlobSetMatchStrategy::*;
747 match *self {
748 Literal(ref s) => s.matches_all(candidate.path.as_bytes()),
749 BasenameLiteral(ref s) => {
750 !candidate.basename.is_empty()
751 && s.matches_all(candidate.basename.as_bytes())
752 }
753 Extension(ref s) => s.matches_all(candidate),
754 Prefix(ref s) => s.matches_all(candidate),
755 Suffix(ref s) => s.matches_all(candidate),
756 RequiredExtension(ref s) => s.matches_all(candidate),
757 Regex(ref s) => s.matches_all(candidate),
758 }
759 }
760}
761
762#[derive(Clone, Debug)]
763struct LiteralStrategy {
764 literals: fnv::HashMap<Vec<u8>, Vec<usize>>,
765 lengths: u64,
767}
768
769impl LiteralStrategy {
770 fn new() -> LiteralStrategy {
771 LiteralStrategy { literals: fnv::HashMap::default(), lengths: 0 }
772 }
773
774 fn add(&mut self, global_index: usize, lit: String) {
775 self.lengths |= 1 << (lit.len() % 64);
776 self.literals
777 .entry(lit.into_bytes())
778 .or_insert(vec![])
779 .push(global_index);
780 }
781
782 fn is_match(&self, path: &[u8]) -> bool {
783 self.may_match_length(path.len()) && self.literals.contains_key(path)
784 }
785
786 fn matches_all(&self, path: &[u8]) -> bool {
787 self.literals.len() == 1 && self.is_match(path)
788 }
789
790 #[inline(never)]
791 fn matches_into(&self, path: &[u8], matches: &mut Vec<usize>) {
792 if !self.may_match_length(path.len()) {
793 return;
794 }
795 if let Some(hits) = self.literals.get(path) {
796 matches.extend(hits);
797 }
798 }
799
800 fn may_match_length(&self, len: usize) -> bool {
802 self.lengths & (1 << (len % 64)) != 0
803 }
804}
805
806#[derive(Clone, Debug)]
807struct ExtensionStrategy(fnv::HashMap<Vec<u8>, Vec<usize>>);
808
809impl ExtensionStrategy {
810 fn new() -> ExtensionStrategy {
811 ExtensionStrategy(fnv::HashMap::default())
812 }
813
814 fn add(&mut self, global_index: usize, ext: String) {
815 self.0.entry(ext.into_bytes()).or_insert(vec![]).push(global_index);
816 }
817
818 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
819 if candidate.ext.is_empty() {
820 return false;
821 }
822 self.0.contains_key(candidate.ext.as_bytes())
823 }
824
825 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
826 self.0.len() == 1 && self.is_match(candidate)
827 }
828
829 #[inline(never)]
830 fn matches_into(
831 &self,
832 candidate: &Candidate<'_>,
833 matches: &mut Vec<usize>,
834 ) {
835 if candidate.ext.is_empty() {
836 return;
837 }
838 if let Some(hits) = self.0.get(candidate.ext.as_bytes()) {
839 matches.extend(hits);
840 }
841 }
842}
843
844#[derive(Clone, Debug)]
845struct PrefixStrategy {
846 matcher: AhoCorasick,
847 map: Vec<usize>,
848 longest: usize,
849}
850
851impl PrefixStrategy {
852 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
853 let path = candidate.path_prefix(self.longest);
854 for m in self.matcher.find_overlapping_iter(path) {
855 if m.start() == 0 {
856 return true;
857 }
858 }
859 false
860 }
861
862 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
863 let path = candidate.path_prefix(self.longest);
864 let mut count = 0;
865 for m in self.matcher.find_overlapping_iter(path) {
868 if m.start() == 0 {
869 count += 1;
870 }
871 }
872 count == self.map.len()
873 }
874
875 fn matches_into(
876 &self,
877 candidate: &Candidate<'_>,
878 matches: &mut Vec<usize>,
879 ) {
880 let path = candidate.path_prefix(self.longest);
881 for m in self.matcher.find_overlapping_iter(path) {
882 if m.start() == 0 {
883 matches.push(self.map[m.pattern()]);
884 }
885 }
886 }
887}
888
889#[derive(Clone, Debug)]
890struct SuffixStrategy {
891 matcher: AhoCorasick,
892 map: Vec<usize>,
893 longest: usize,
894}
895
896impl SuffixStrategy {
897 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
898 let path = candidate.path_suffix(self.longest);
899 for m in self.matcher.find_overlapping_iter(path) {
900 if m.end() == path.len() {
901 return true;
902 }
903 }
904 false
905 }
906
907 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
908 let path = candidate.path_suffix(self.longest);
909 let mut count = 0;
910 for m in self.matcher.find_overlapping_iter(path) {
913 if m.end() == path.len() {
914 count += 1;
915 }
916 }
917 count == self.map.len()
918 }
919
920 fn matches_into(
921 &self,
922 candidate: &Candidate<'_>,
923 matches: &mut Vec<usize>,
924 ) {
925 let path = candidate.path_suffix(self.longest);
926 for m in self.matcher.find_overlapping_iter(path) {
927 if m.end() == path.len() {
928 matches.push(self.map[m.pattern()]);
929 }
930 }
931 }
932}
933
934#[derive(Clone, Debug)]
935struct RequiredExtensionStrategy(fnv::HashMap<Vec<u8>, Vec<(usize, Regex)>>);
936
937impl RequiredExtensionStrategy {
938 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
939 if candidate.ext.is_empty() {
940 return false;
941 }
942 match self.0.get(candidate.ext.as_bytes()) {
943 None => false,
944 Some(regexes) => {
945 for &(_, ref re) in regexes {
946 if re.is_match(candidate.path.as_bytes()) {
947 return true;
948 }
949 }
950 false
951 }
952 }
953 }
954
955 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
956 if self.0.len() != 1 || candidate.ext.is_empty() {
957 return false;
958 }
959 if let Some(regexes) = self.0.get(candidate.ext.as_bytes()) {
960 for &(_, ref re) in regexes {
961 if !re.is_match(candidate.path.as_bytes()) {
962 return false;
963 }
964 }
965 true
966 } else {
967 false
968 }
969 }
970
971 #[inline(never)]
972 fn matches_into(
973 &self,
974 candidate: &Candidate<'_>,
975 matches: &mut Vec<usize>,
976 ) {
977 if candidate.ext.is_empty() {
978 return;
979 }
980 if let Some(regexes) = self.0.get(candidate.ext.as_bytes()) {
981 for &(global_index, ref re) in regexes {
982 if re.is_match(candidate.path.as_bytes()) {
983 matches.push(global_index);
984 }
985 }
986 }
987 }
988}
989
990#[derive(Clone, Debug)]
991struct RegexSetStrategy {
992 matcher: Regex,
993 map: Vec<usize>,
994 basename: bool,
995 patset: Arc<Pool<PatternSet, PatternSetPoolFn>>,
1004}
1005
1006type PatternSetPoolFn =
1007 Box<dyn Fn() -> PatternSet + Send + Sync + UnwindSafe + RefUnwindSafe>;
1008
1009impl RegexSetStrategy {
1010 fn haystack<'a>(&self, candidate: &'a Candidate<'_>) -> &'a [u8] {
1012 if self.basename {
1013 candidate.basename_for_regex()
1014 } else {
1015 &candidate.path
1016 }
1017 }
1018
1019 fn is_match(&self, candidate: &Candidate<'_>) -> bool {
1020 self.matcher.is_match(self.haystack(candidate))
1021 }
1022
1023 fn find_matches(
1024 &self,
1025 candidate: &Candidate<'_>,
1026 ) -> PoolGuard<'_, PatternSet, PatternSetPoolFn> {
1027 let input = regex_automata::Input::new(self.haystack(candidate));
1028 let mut patset = self.patset.get();
1029 patset.clear();
1030 self.matcher.which_overlapping_matches(&input, &mut patset);
1031 patset
1032 }
1033
1034 fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
1035 let patset = self.find_matches(candidate);
1036 patset.is_full()
1037 }
1038
1039 fn matches_into(
1040 &self,
1041 candidate: &Candidate<'_>,
1042 matches: &mut Vec<usize>,
1043 ) {
1044 let patset = self.find_matches(candidate);
1045 for i in patset.iter() {
1046 matches.push(self.map[i]);
1047 }
1048 PoolGuard::put(patset);
1049 }
1050}
1051
1052#[derive(Clone, Debug)]
1053struct MultiStrategyBuilder {
1054 literals: Vec<String>,
1055 map: Vec<usize>,
1056 longest: usize,
1057}
1058
1059impl MultiStrategyBuilder {
1060 fn new() -> MultiStrategyBuilder {
1061 MultiStrategyBuilder { literals: vec![], map: vec![], longest: 0 }
1062 }
1063
1064 fn add(&mut self, global_index: usize, literal: String) {
1065 if literal.len() > self.longest {
1066 self.longest = literal.len();
1067 }
1068 self.map.push(global_index);
1069 self.literals.push(literal);
1070 }
1071
1072 fn prefix(self) -> PrefixStrategy {
1073 PrefixStrategy {
1074 matcher: AhoCorasick::new(&self.literals).unwrap(),
1075 map: self.map,
1076 longest: self.longest,
1077 }
1078 }
1079
1080 fn suffix(self) -> SuffixStrategy {
1081 SuffixStrategy {
1082 matcher: AhoCorasick::new(&self.literals).unwrap(),
1083 map: self.map,
1084 longest: self.longest,
1085 }
1086 }
1087
1088 fn regex_set(self) -> Result<RegexSetStrategy, Error> {
1089 let matcher = new_regex_set(self.literals)?;
1090 let pattern_len = matcher.pattern_len();
1091 let create: PatternSetPoolFn =
1092 Box::new(move || PatternSet::new(pattern_len));
1093 Ok(RegexSetStrategy {
1094 matcher,
1095 map: self.map,
1096 basename: false,
1097 patset: Arc::new(Pool::new(create)),
1098 })
1099 }
1100
1101 fn is_empty(&self) -> bool {
1102 self.literals.is_empty()
1103 }
1104}
1105
1106#[derive(Clone, Debug)]
1107struct RequiredExtensionStrategyBuilder(
1108 fnv::HashMap<Vec<u8>, Vec<(usize, String)>>,
1109);
1110
1111impl RequiredExtensionStrategyBuilder {
1112 fn new() -> RequiredExtensionStrategyBuilder {
1113 RequiredExtensionStrategyBuilder(fnv::HashMap::default())
1114 }
1115
1116 fn add(&mut self, global_index: usize, ext: String, regex: String) {
1117 self.0
1118 .entry(ext.into_bytes())
1119 .or_insert(vec![])
1120 .push((global_index, regex));
1121 }
1122
1123 fn build(self) -> Result<RequiredExtensionStrategy, Error> {
1124 let mut exts = fnv::HashMap::default();
1125 for (ext, regexes) in self.0.into_iter() {
1126 exts.insert(ext.clone(), vec![]);
1127 for (global_index, regex) in regexes {
1128 let compiled = new_regex(®ex)?;
1129 exts.get_mut(&ext).unwrap().push((global_index, compiled));
1130 }
1131 }
1132 Ok(RequiredExtensionStrategy(exts))
1133 }
1134}
1135
1136pub fn escape(s: &str) -> String {
1154 let mut escaped = String::with_capacity(s.len());
1155 for c in s.chars() {
1156 match c {
1157 '?' | '*' | '[' | ']' | '{' | '}' => {
1160 escaped.push('[');
1161 escaped.push(c);
1162 escaped.push(']');
1163 }
1164 c => {
1165 escaped.push(c);
1166 }
1167 }
1168 }
1169 escaped
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174 use crate::glob::{Glob, GlobBuilder};
1175
1176 use super::{GlobSet, GlobSetBuilder};
1177
1178 fn build_glob_set(globs: &[&str]) -> GlobSet {
1179 let mut builder = GlobSetBuilder::new();
1180 for glob in globs {
1181 builder.add(Glob::new(glob).unwrap());
1182 }
1183 builder.build().unwrap()
1184 }
1185
1186 #[test]
1187 fn debug_impl_is_concise() {
1188 let set = build_glob_set(&["src/**/*.rs", "*.c"]);
1189 assert_eq!(
1190 format!("{:?}", set),
1191 r#"GlobSet([Glob("src/**/*.rs"), Glob("*.c")])"#
1192 );
1193 assert_eq!(format!("{:?}", GlobSet::empty()), "GlobSet([])");
1194 }
1195
1196 #[test]
1197 fn set_works() {
1198 let set = build_glob_set(&["src/**/*.rs", "*.c", "src/lib.rs"]);
1199
1200 assert!(set.is_match("foo.c"));
1201 assert!(set.is_match("src/foo.c"));
1202 assert!(!set.is_match("foo.rs"));
1203 assert!(!set.is_match("tests/foo.rs"));
1204 assert!(set.is_match("src/foo.rs"));
1205 assert!(set.is_match("src/grep/src/main.rs"));
1206
1207 assert!(!set.matches_all("src/lib.rs"));
1208 assert!(!set.matches_all("src/a/b.c"));
1209
1210 let matches = set.matches("src/lib.rs");
1211 assert_eq!(2, matches.len());
1212 assert_eq!(0, matches[0]);
1213 assert_eq!(2, matches[1]);
1214 }
1215
1216 #[test]
1217 fn empty_set_works() {
1218 let set = GlobSetBuilder::new().build().unwrap();
1219 assert!(!set.is_match(""));
1220 assert!(!set.is_match("a"));
1221 assert!(set.matches_all("a"));
1222 }
1223
1224 #[test]
1225 fn matches_all_literals() {
1226 let set = build_glob_set(&["abc", "def"]);
1227
1228 assert!(!set.matches_all("abc"));
1229 assert!(!set.matches_all("def"));
1230
1231 let set = build_glob_set(&["abc"]);
1232
1233 assert!(set.matches_all("abc"));
1234 }
1235
1236 #[test]
1237 fn matches_all_basename_literals() {
1238 let set = build_glob_set(&["**/abc", "**/a.c"]);
1239
1240 assert!(!set.matches_all("foo/abc"));
1241 assert!(!set.matches_all("foo/a.c"));
1242
1243 let set = build_glob_set(&["**/a.c"]);
1244 assert!(set.matches_all("foo/a.c"));
1245 }
1246
1247 #[test]
1248 fn matches_all_extensions() {
1249 let set = build_glob_set(&["**/*.rs", "**/*.c"]);
1250
1251 assert!(!set.matches_all("foo/a.rs"));
1252 assert!(!set.matches_all("foo/a.c"));
1253
1254 let set = build_glob_set(&["**/*.rs", "*.rs"]);
1255 assert!(set.matches_all("foo/a.rs"));
1256 }
1257
1258 #[test]
1259 fn matches_all_required_extensions() {
1260 let set = build_glob_set(&["*.rs", "**/m*.rs", "a/*.rs"]);
1261
1262 assert!(set.matches_all("a/main.rs"));
1263
1264 assert!(!set.matches_all("main.rs"));
1265 assert!(!set.matches_all("a/lib.rs"));
1266
1267 let set = build_glob_set(&["x/m*.a", "y/n*.b"]);
1268
1269 for (path, index) in [("x/mt.a", 0), ("y/nz.b", 1)] {
1270 assert_eq!(set.matches(path), vec![index]);
1271 assert!(!set.matches_all(path));
1272 assert!(!set.matches_all_candidate(&crate::Candidate::new(path)));
1273 }
1274 }
1275
1276 #[test]
1277 fn matches_all_prefix() {
1278 let set = build_glob_set(&["a*", "ab*", "ab/c*"]);
1279
1280 assert!(set.matches_all("ab/c/def"));
1281 assert!(set.matches_all("ab/cd"));
1282
1283 assert!(!set.matches_all("abc"));
1284 assert!(!set.matches_all("ab/x"));
1285 assert!(!set.matches_all("a"));
1286 }
1287
1288 #[test]
1289 fn matches_all_suffix() {
1290 let set = build_glob_set(&["*.rs", "*s", "*/main.rs"]);
1291
1292 assert!(set.matches_all("a/b/c/main.rs"));
1293
1294 assert!(!set.matches_all("foo.rs"));
1295 assert!(!set.matches_all("as"));
1296 }
1297
1298 #[test]
1299 fn matches_all_regex() {
1300 let set = GlobSet::new(&[
1301 GlobBuilder::new("c*").case_insensitive(true).build().unwrap(),
1302 Glob::new("*{rs,c}").unwrap(),
1303 ])
1304 .unwrap();
1305
1306 assert!(set.matches_all("c/main.rs"));
1307 assert!(set.matches_all("C/main.c"));
1308
1309 assert!(!set.matches_all("Ca"));
1310 assert!(!set.matches_all("foo.c"));
1311 }
1312
1313 #[test]
1314 fn basename_regex_with_path_rules() {
1315 let globs: Vec<_> = ["**/.venv*", "**/*.py[cod]", "src/*"]
1316 .iter()
1317 .map(|pattern| {
1318 GlobBuilder::new(pattern)
1319 .literal_separator(true)
1320 .build()
1321 .unwrap()
1322 })
1323 .collect();
1324 let set = GlobSet::new(globs).unwrap();
1325 assert_eq!(set.matches("src/module.pyc"), vec![1, 2]);
1326 assert_eq!(set.matches("src/nested/module.pyc"), vec![1]);
1327 assert_eq!(set.matches("src/.venv-new"), vec![0, 2]);
1328 assert!(set.matches_all("src/.venv.pyc"));
1329 assert!(!set.matches_all("src/nested/.venv.pyc"));
1330 }
1331
1332 #[test]
1333 fn basename_regex_parent_component() {
1334 let set = GlobSet::new([
1335 GlobBuilder::new("**/.*").literal_separator(true).build().unwrap(),
1336 Glob::new("**/[.][.]").unwrap(),
1337 ])
1338 .unwrap();
1339 for path in ["..", "foo/..", "foo/bar/.."] {
1340 assert!(set.is_match(path), "{path}");
1341 assert!(set.matches_all(path), "{path}");
1342 assert_eq!(set.matches(path), vec![0, 1], "{path}");
1343 }
1344 assert!(!set.matches_all("foo/."));
1345 assert!(!set.matches_all("foo/a.."));
1346 }
1347
1348 #[test]
1349 fn default_set_is_empty_works() {
1350 let set: GlobSet = Default::default();
1351 assert!(!set.is_match(""));
1352 assert!(!set.is_match("a"));
1353 }
1354
1355 #[test]
1356 fn escape() {
1357 use super::escape;
1358 assert_eq!("foo", escape("foo"));
1359 assert_eq!("foo[*]", escape("foo*"));
1360 assert_eq!("[[][]]", escape("[]"));
1361 assert_eq!("[*][?]", escape("*?"));
1362 assert_eq!("src/[*][*]/[*].rs", escape("src/**/*.rs"));
1363 assert_eq!("bar[[]ab[]]baz", escape("bar[ab]baz"));
1364 assert_eq!("bar[[]!![]]!baz", escape("bar[!!]!baz"));
1365 }
1366
1367 #[test]
1371 fn set_does_not_remember() {
1372 let mut builder = GlobSetBuilder::new();
1373 builder.add(Glob::new("*foo*").unwrap());
1374 builder.add(Glob::new("*bar*").unwrap());
1375 builder.add(Glob::new("*quux*").unwrap());
1376 let set = builder.build().unwrap();
1377
1378 let matches = set.matches("ZfooZquuxZ");
1379 assert_eq!(2, matches.len());
1380 assert_eq!(0, matches[0]);
1381 assert_eq!(2, matches[1]);
1382
1383 let matches = set.matches("nada");
1384 assert_eq!(0, matches.len());
1385 }
1386
1387 #[test]
1388 fn debug() {
1389 let mut builder = GlobSetBuilder::new();
1390 builder.add(Glob::new("*foo*").unwrap());
1391 builder.add(Glob::new("*bar*").unwrap());
1392 builder.add(Glob::new("*quux*").unwrap());
1393 assert_eq!(
1394 format!("{builder:?}"),
1395 "GlobSetBuilder { pats: [Glob(\"*foo*\"), Glob(\"*bar*\"), Glob(\"*quux*\")] }",
1396 );
1397 }
1398 #[test]
1399 fn literal_length_filter() {
1400 let lengths = [0, 1, 63, 64, 65, 127, 128, 129];
1401 let mut patterns: Vec<_> =
1402 lengths.iter().map(|&len| "a".repeat(len)).collect();
1403 patterns.extend(["é.py".to_owned(), r"foo\*bar".to_owned()]);
1404 let set = GlobSet::new(patterns.iter().map(|pattern| {
1405 GlobBuilder::new(pattern).backslash_escape(true).build().unwrap()
1406 }))
1407 .unwrap();
1408 for (i, &len) in lengths.iter().enumerate() {
1409 let path = "a".repeat(len);
1410 assert!(set.is_match(&path));
1411 assert_eq!(set.matches(&path), vec![i]);
1412 }
1413 assert_eq!(set.matches("é.py"), vec![8]);
1414 assert_eq!(set.matches("foo*bar"), vec![9]);
1415 for len in [2, 62, 66, 126, 130] {
1416 assert!(!set.is_match("a".repeat(len)));
1417 }
1418 let literal = "a".repeat(65);
1419 let duplicates = GlobSet::new([
1420 Glob::new(&literal).unwrap(),
1421 Glob::new(&literal).unwrap(),
1422 ])
1423 .unwrap();
1424 assert!(duplicates.matches_all(&literal));
1425 assert_eq!(duplicates.matches(&literal), vec![0, 1]);
1426 assert!(!duplicates.is_match("a"));
1427 assert!(!duplicates.matches_all("a"));
1428 assert!(!duplicates.is_match("b".repeat(65)));
1429 }
1430
1431 #[test]
1432 fn basename_literal_length_filter() {
1433 let lengths = [1, 63, 64, 65, 127, 128, 129];
1434 let mut patterns: Vec<_> = lengths
1435 .iter()
1436 .map(|&len| format!("**/{}", "a".repeat(len)))
1437 .collect();
1438 patterns.extend(["**/é.py".to_owned(), r"**/foo\*bar".to_owned()]);
1439 let set = GlobSet::new(patterns.iter().map(|pattern| {
1440 GlobBuilder::new(pattern).backslash_escape(true).build().unwrap()
1441 }))
1442 .unwrap();
1443 for (i, &len) in lengths.iter().enumerate() {
1444 let path = format!("parent/{}", "a".repeat(len));
1445 assert!(set.is_match(&path));
1446 assert_eq!(set.matches(&path), vec![i]);
1447 }
1448 assert_eq!(set.matches("parent/é.py"), vec![7]);
1449 assert_eq!(set.matches("parent/foo*bar"), vec![8]);
1450 let literal = "a".repeat(65);
1451 let glob = Glob::new(&format!("**/{literal}")).unwrap();
1452 let duplicates = GlobSet::new([&glob, &glob]).unwrap();
1453 let path = format!("parent/{literal}");
1454 assert!(duplicates.matches_all(&path));
1455 assert_eq!(duplicates.matches(&path), vec![0, 1]);
1456 assert!(!duplicates.is_match("parent/a"));
1457 assert!(!duplicates.is_match(format!("parent/{}", "b".repeat(65))));
1458 let parent = GlobSet::new([Glob::new("**/..").unwrap()]).unwrap();
1459 assert!(!parent.is_match("parent/.."));
1460 assert!(!parent.matches_all("parent/.."));
1461 }
1462}