1 use std::fmt;
2 use std::hash;
3 use std::iter;
4 use std::ops::{Deref, DerefMut};
5 use std::path::{is_separator, Path};
6 use std::str;
7
8 use regex;
9 use regex::bytes::Regex;
10
11 use {new_regex, Candidate, Error, ErrorKind};
12
13 /// Describes a matching strategy for a particular pattern.
14 ///
15 /// This provides a way to more quickly determine whether a pattern matches
16 /// a particular file path in a way that scales with a large number of
17 /// patterns. For example, if many patterns are of the form `*.ext`, then it's
18 /// possible to test whether any of those patterns matches by looking up a
19 /// file path's extension in a hash table.
20 #[derive(Clone, Debug, Eq, PartialEq)]
21 pub enum MatchStrategy {
22 /// A pattern matches if and only if the entire file path matches this
23 /// literal string.
24 Literal(String),
25 /// A pattern matches if and only if the file path's basename matches this
26 /// literal string.
27 BasenameLiteral(String),
28 /// A pattern matches if and only if the file path's extension matches this
29 /// literal string.
30 Extension(String),
31 /// A pattern matches if and only if this prefix literal is a prefix of the
32 /// candidate file path.
33 Prefix(String),
34 /// A pattern matches if and only if this prefix literal is a prefix of the
35 /// candidate file path.
36 ///
37 /// An exception: if `component` is true, then `suffix` must appear at the
38 /// beginning of a file path or immediately following a `/`.
39 Suffix {
40 /// The actual suffix.
41 suffix: String,
42 /// Whether this must start at the beginning of a path component.
43 component: bool,
44 },
45 /// A pattern matches only if the given extension matches the file path's
46 /// extension. Note that this is a necessary but NOT sufficient criterion.
47 /// Namely, if the extension matches, then a full regex search is still
48 /// required.
49 RequiredExtension(String),
50 /// A regex needs to be used for matching.
51 Regex,
52 }
53
54 impl MatchStrategy {
55 /// Returns a matching strategy for the given pattern.
new(pat: &Glob) -> MatchStrategy56 pub fn new(pat: &Glob) -> MatchStrategy {
57 if let Some(lit) = pat.basename_literal() {
58 MatchStrategy::BasenameLiteral(lit)
59 } else if let Some(lit) = pat.literal() {
60 MatchStrategy::Literal(lit)
61 } else if let Some(ext) = pat.ext() {
62 MatchStrategy::Extension(ext)
63 } else if let Some(prefix) = pat.prefix() {
64 MatchStrategy::Prefix(prefix)
65 } else if let Some((suffix, component)) = pat.suffix() {
66 MatchStrategy::Suffix { suffix: suffix, component: component }
67 } else if let Some(ext) = pat.required_ext() {
68 MatchStrategy::RequiredExtension(ext)
69 } else {
70 MatchStrategy::Regex
71 }
72 }
73 }
74
75 /// Glob represents a successfully parsed shell glob pattern.
76 ///
77 /// It cannot be used directly to match file paths, but it can be converted
78 /// to a regular expression string or a matcher.
79 #[derive(Clone, Debug, Eq)]
80 pub struct Glob {
81 glob: String,
82 re: String,
83 opts: GlobOptions,
84 tokens: Tokens,
85 }
86
87 impl PartialEq for Glob {
eq(&self, other: &Glob) -> bool88 fn eq(&self, other: &Glob) -> bool {
89 self.glob == other.glob && self.opts == other.opts
90 }
91 }
92
93 impl hash::Hash for Glob {
hash<H: hash::Hasher>(&self, state: &mut H)94 fn hash<H: hash::Hasher>(&self, state: &mut H) {
95 self.glob.hash(state);
96 self.opts.hash(state);
97 }
98 }
99
100 impl fmt::Display for Glob {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 self.glob.fmt(f)
103 }
104 }
105
106 impl str::FromStr for Glob {
107 type Err = Error;
108
from_str(glob: &str) -> Result<Self, Self::Err>109 fn from_str(glob: &str) -> Result<Self, Self::Err> {
110 Self::new(glob)
111 }
112 }
113
114 /// A matcher for a single pattern.
115 #[derive(Clone, Debug)]
116 pub struct GlobMatcher {
117 /// The underlying pattern.
118 pat: Glob,
119 /// The pattern, as a compiled regex.
120 re: Regex,
121 }
122
123 impl GlobMatcher {
124 /// Tests whether the given path matches this pattern or not.
is_match<P: AsRef<Path>>(&self, path: P) -> bool125 pub fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
126 self.is_match_candidate(&Candidate::new(path.as_ref()))
127 }
128
129 /// Tests whether the given path matches this pattern or not.
is_match_candidate(&self, path: &Candidate) -> bool130 pub fn is_match_candidate(&self, path: &Candidate) -> bool {
131 self.re.is_match(&path.path)
132 }
133
134 /// Returns the `Glob` used to compile this matcher.
glob(&self) -> &Glob135 pub fn glob(&self) -> &Glob {
136 &self.pat
137 }
138 }
139
140 /// A strategic matcher for a single pattern.
141 #[cfg(test)]
142 #[derive(Clone, Debug)]
143 struct GlobStrategic {
144 /// The match strategy to use.
145 strategy: MatchStrategy,
146 /// The underlying pattern.
147 pat: Glob,
148 /// The pattern, as a compiled regex.
149 re: Regex,
150 }
151
152 #[cfg(test)]
153 impl GlobStrategic {
154 /// Tests whether the given path matches this pattern or not.
is_match<P: AsRef<Path>>(&self, path: P) -> bool155 fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
156 self.is_match_candidate(&Candidate::new(path.as_ref()))
157 }
158
159 /// Tests whether the given path matches this pattern or not.
is_match_candidate(&self, candidate: &Candidate) -> bool160 fn is_match_candidate(&self, candidate: &Candidate) -> bool {
161 let byte_path = &*candidate.path;
162
163 match self.strategy {
164 MatchStrategy::Literal(ref lit) => lit.as_bytes() == byte_path,
165 MatchStrategy::BasenameLiteral(ref lit) => {
166 lit.as_bytes() == &*candidate.basename
167 }
168 MatchStrategy::Extension(ref ext) => {
169 ext.as_bytes() == &*candidate.ext
170 }
171 MatchStrategy::Prefix(ref pre) => {
172 starts_with(pre.as_bytes(), byte_path)
173 }
174 MatchStrategy::Suffix { ref suffix, component } => {
175 if component && byte_path == &suffix.as_bytes()[1..] {
176 return true;
177 }
178 ends_with(suffix.as_bytes(), byte_path)
179 }
180 MatchStrategy::RequiredExtension(ref ext) => {
181 let ext = ext.as_bytes();
182 &*candidate.ext == ext && self.re.is_match(byte_path)
183 }
184 MatchStrategy::Regex => self.re.is_match(byte_path),
185 }
186 }
187 }
188
189 /// A builder for a pattern.
190 ///
191 /// This builder enables configuring the match semantics of a pattern. For
192 /// example, one can make matching case insensitive.
193 ///
194 /// The lifetime `'a` refers to the lifetime of the pattern string.
195 #[derive(Clone, Debug)]
196 pub struct GlobBuilder<'a> {
197 /// The glob pattern to compile.
198 glob: &'a str,
199 /// Options for the pattern.
200 opts: GlobOptions,
201 }
202
203 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
204 struct GlobOptions {
205 /// Whether to match case insensitively.
206 case_insensitive: bool,
207 /// Whether to require a literal separator to match a separator in a file
208 /// path. e.g., when enabled, `*` won't match `/`.
209 literal_separator: bool,
210 /// Whether or not to use `\` to escape special characters.
211 /// e.g., when enabled, `\*` will match a literal `*`.
212 backslash_escape: bool,
213 }
214
215 impl GlobOptions {
default() -> GlobOptions216 fn default() -> GlobOptions {
217 GlobOptions {
218 case_insensitive: false,
219 literal_separator: false,
220 backslash_escape: !is_separator('\\'),
221 }
222 }
223 }
224
225 #[derive(Clone, Debug, Default, Eq, PartialEq)]
226 struct Tokens(Vec<Token>);
227
228 impl Deref for Tokens {
229 type Target = Vec<Token>;
deref(&self) -> &Vec<Token>230 fn deref(&self) -> &Vec<Token> {
231 &self.0
232 }
233 }
234
235 impl DerefMut for Tokens {
deref_mut(&mut self) -> &mut Vec<Token>236 fn deref_mut(&mut self) -> &mut Vec<Token> {
237 &mut self.0
238 }
239 }
240
241 #[derive(Clone, Debug, Eq, PartialEq)]
242 enum Token {
243 Literal(char),
244 Any,
245 ZeroOrMore,
246 RecursivePrefix,
247 RecursiveSuffix,
248 RecursiveZeroOrMore,
249 Class { negated: bool, ranges: Vec<(char, char)> },
250 Alternates(Vec<Tokens>),
251 }
252
253 impl Glob {
254 /// Builds a new pattern with default options.
new(glob: &str) -> Result<Glob, Error>255 pub fn new(glob: &str) -> Result<Glob, Error> {
256 GlobBuilder::new(glob).build()
257 }
258
259 /// Returns a matcher for this pattern.
compile_matcher(&self) -> GlobMatcher260 pub fn compile_matcher(&self) -> GlobMatcher {
261 let re =
262 new_regex(&self.re).expect("regex compilation shouldn't fail");
263 GlobMatcher { pat: self.clone(), re: re }
264 }
265
266 /// Returns a strategic matcher.
267 ///
268 /// This isn't exposed because it's not clear whether it's actually
269 /// faster than just running a regex for a *single* pattern. If it
270 /// is faster, then GlobMatcher should do it automatically.
271 #[cfg(test)]
compile_strategic_matcher(&self) -> GlobStrategic272 fn compile_strategic_matcher(&self) -> GlobStrategic {
273 let strategy = MatchStrategy::new(self);
274 let re =
275 new_regex(&self.re).expect("regex compilation shouldn't fail");
276 GlobStrategic { strategy: strategy, pat: self.clone(), re: re }
277 }
278
279 /// Returns the original glob pattern used to build this pattern.
glob(&self) -> &str280 pub fn glob(&self) -> &str {
281 &self.glob
282 }
283
284 /// Returns the regular expression string for this glob.
285 ///
286 /// Note that regular expressions for globs are intended to be matched on
287 /// arbitrary bytes (`&[u8]`) instead of Unicode strings (`&str`). In
288 /// particular, globs are frequently used on file paths, where there is no
289 /// general guarantee that file paths are themselves valid UTF-8. As a
290 /// result, callers will need to ensure that they are using a regex API
291 /// that can match on arbitrary bytes. For example, the
292 /// [`regex`](https://crates.io/regex)
293 /// crate's
294 /// [`Regex`](https://docs.rs/regex/*/regex/struct.Regex.html)
295 /// API is not suitable for this since it matches on `&str`, but its
296 /// [`bytes::Regex`](https://docs.rs/regex/*/regex/bytes/struct.Regex.html)
297 /// API is suitable for this.
regex(&self) -> &str298 pub fn regex(&self) -> &str {
299 &self.re
300 }
301
302 /// Returns the pattern as a literal if and only if the pattern must match
303 /// an entire path exactly.
304 ///
305 /// The basic format of these patterns is `{literal}`.
literal(&self) -> Option<String>306 fn literal(&self) -> Option<String> {
307 if self.opts.case_insensitive {
308 return None;
309 }
310 let mut lit = String::new();
311 for t in &*self.tokens {
312 match *t {
313 Token::Literal(c) => lit.push(c),
314 _ => return None,
315 }
316 }
317 if lit.is_empty() {
318 None
319 } else {
320 Some(lit)
321 }
322 }
323
324 /// Returns an extension if this pattern matches a file path if and only
325 /// if the file path has the extension returned.
326 ///
327 /// Note that this extension returned differs from the extension that
328 /// std::path::Path::extension returns. Namely, this extension includes
329 /// the '.'. Also, paths like `.rs` are considered to have an extension
330 /// of `.rs`.
ext(&self) -> Option<String>331 fn ext(&self) -> Option<String> {
332 if self.opts.case_insensitive {
333 return None;
334 }
335 let start = match self.tokens.get(0) {
336 Some(&Token::RecursivePrefix) => 1,
337 Some(_) => 0,
338 _ => return None,
339 };
340 match self.tokens.get(start) {
341 Some(&Token::ZeroOrMore) => {
342 // If there was no recursive prefix, then we only permit
343 // `*` if `*` can match a `/`. For example, if `*` can't
344 // match `/`, then `*.c` doesn't match `foo/bar.c`.
345 if start == 0 && self.opts.literal_separator {
346 return None;
347 }
348 }
349 _ => return None,
350 }
351 match self.tokens.get(start + 1) {
352 Some(&Token::Literal('.')) => {}
353 _ => return None,
354 }
355 let mut lit = ".".to_string();
356 for t in self.tokens[start + 2..].iter() {
357 match *t {
358 Token::Literal('.') | Token::Literal('/') => return None,
359 Token::Literal(c) => lit.push(c),
360 _ => return None,
361 }
362 }
363 if lit.is_empty() {
364 None
365 } else {
366 Some(lit)
367 }
368 }
369
370 /// This is like `ext`, but returns an extension even if it isn't sufficent
371 /// to imply a match. Namely, if an extension is returned, then it is
372 /// necessary but not sufficient for a match.
required_ext(&self) -> Option<String>373 fn required_ext(&self) -> Option<String> {
374 if self.opts.case_insensitive {
375 return None;
376 }
377 // We don't care at all about the beginning of this pattern. All we
378 // need to check for is if it ends with a literal of the form `.ext`.
379 let mut ext: Vec<char> = vec![]; // built in reverse
380 for t in self.tokens.iter().rev() {
381 match *t {
382 Token::Literal('/') => return None,
383 Token::Literal(c) => {
384 ext.push(c);
385 if c == '.' {
386 break;
387 }
388 }
389 _ => return None,
390 }
391 }
392 if ext.last() != Some(&'.') {
393 None
394 } else {
395 ext.reverse();
396 Some(ext.into_iter().collect())
397 }
398 }
399
400 /// Returns a literal prefix of this pattern if the entire pattern matches
401 /// if the literal prefix matches.
prefix(&self) -> Option<String>402 fn prefix(&self) -> Option<String> {
403 if self.opts.case_insensitive {
404 return None;
405 }
406 let end = match self.tokens.last() {
407 Some(&Token::ZeroOrMore) => {
408 if self.opts.literal_separator {
409 // If a trailing `*` can't match a `/`, then we can't
410 // assume a match of the prefix corresponds to a match
411 // of the overall pattern. e.g., `foo/*` with
412 // `literal_separator` enabled matches `foo/bar` but not
413 // `foo/bar/baz`, even though `foo/bar/baz` has a `foo/`
414 // literal prefix.
415 return None;
416 }
417 self.tokens.len() - 1
418 }
419 _ => self.tokens.len(),
420 };
421 let mut lit = String::new();
422 for t in &self.tokens[0..end] {
423 match *t {
424 Token::Literal(c) => lit.push(c),
425 _ => return None,
426 }
427 }
428 if lit.is_empty() {
429 None
430 } else {
431 Some(lit)
432 }
433 }
434
435 /// Returns a literal suffix of this pattern if the entire pattern matches
436 /// if the literal suffix matches.
437 ///
438 /// If a literal suffix is returned and it must match either the entire
439 /// file path or be preceded by a `/`, then also return true. This happens
440 /// with a pattern like `**/foo/bar`. Namely, this pattern matches
441 /// `foo/bar` and `baz/foo/bar`, but not `foofoo/bar`. In this case, the
442 /// suffix returned is `/foo/bar` (but should match the entire path
443 /// `foo/bar`).
444 ///
445 /// When this returns true, the suffix literal is guaranteed to start with
446 /// a `/`.
suffix(&self) -> Option<(String, bool)>447 fn suffix(&self) -> Option<(String, bool)> {
448 if self.opts.case_insensitive {
449 return None;
450 }
451 let mut lit = String::new();
452 let (start, entire) = match self.tokens.get(0) {
453 Some(&Token::RecursivePrefix) => {
454 // We only care if this follows a path component if the next
455 // token is a literal.
456 if let Some(&Token::Literal(_)) = self.tokens.get(1) {
457 lit.push('/');
458 (1, true)
459 } else {
460 (1, false)
461 }
462 }
463 _ => (0, false),
464 };
465 let start = match self.tokens.get(start) {
466 Some(&Token::ZeroOrMore) => {
467 // If literal_separator is enabled, then a `*` can't
468 // necessarily match everything, so reporting a suffix match
469 // as a match of the pattern would be a false positive.
470 if self.opts.literal_separator {
471 return None;
472 }
473 start + 1
474 }
475 _ => start,
476 };
477 for t in &self.tokens[start..] {
478 match *t {
479 Token::Literal(c) => lit.push(c),
480 _ => return None,
481 }
482 }
483 if lit.is_empty() || lit == "/" {
484 None
485 } else {
486 Some((lit, entire))
487 }
488 }
489
490 /// If this pattern only needs to inspect the basename of a file path,
491 /// then the tokens corresponding to only the basename match are returned.
492 ///
493 /// For example, given a pattern of `**/*.foo`, only the tokens
494 /// corresponding to `*.foo` are returned.
495 ///
496 /// Note that this will return None if any match of the basename tokens
497 /// doesn't correspond to a match of the entire pattern. For example, the
498 /// glob `foo` only matches when a file path has a basename of `foo`, but
499 /// doesn't *always* match when a file path has a basename of `foo`. e.g.,
500 /// `foo` doesn't match `abc/foo`.
basename_tokens(&self) -> Option<&[Token]>501 fn basename_tokens(&self) -> Option<&[Token]> {
502 if self.opts.case_insensitive {
503 return None;
504 }
505 let start = match self.tokens.get(0) {
506 Some(&Token::RecursivePrefix) => 1,
507 _ => {
508 // With nothing to gobble up the parent portion of a path,
509 // we can't assume that matching on only the basename is
510 // correct.
511 return None;
512 }
513 };
514 if self.tokens[start..].is_empty() {
515 return None;
516 }
517 for t in &self.tokens[start..] {
518 match *t {
519 Token::Literal('/') => return None,
520 Token::Literal(_) => {} // OK
521 Token::Any | Token::ZeroOrMore => {
522 if !self.opts.literal_separator {
523 // In this case, `*` and `?` can match a path
524 // separator, which means this could reach outside
525 // the basename.
526 return None;
527 }
528 }
529 Token::RecursivePrefix
530 | Token::RecursiveSuffix
531 | Token::RecursiveZeroOrMore => {
532 return None;
533 }
534 Token::Class { .. } | Token::Alternates(..) => {
535 // We *could* be a little smarter here, but either one
536 // of these is going to prevent our literal optimizations
537 // anyway, so give up.
538 return None;
539 }
540 }
541 }
542 Some(&self.tokens[start..])
543 }
544
545 /// Returns the pattern as a literal if and only if the pattern exclusively
546 /// matches the basename of a file path *and* is a literal.
547 ///
548 /// The basic format of these patterns is `**/{literal}`, where `{literal}`
549 /// does not contain a path separator.
basename_literal(&self) -> Option<String>550 fn basename_literal(&self) -> Option<String> {
551 let tokens = match self.basename_tokens() {
552 None => return None,
553 Some(tokens) => tokens,
554 };
555 let mut lit = String::new();
556 for t in tokens {
557 match *t {
558 Token::Literal(c) => lit.push(c),
559 _ => return None,
560 }
561 }
562 Some(lit)
563 }
564 }
565
566 impl<'a> GlobBuilder<'a> {
567 /// Create a new builder for the pattern given.
568 ///
569 /// The pattern is not compiled until `build` is called.
new(glob: &'a str) -> GlobBuilder<'a>570 pub fn new(glob: &'a str) -> GlobBuilder<'a> {
571 GlobBuilder { glob: glob, opts: GlobOptions::default() }
572 }
573
574 /// Parses and builds the pattern.
build(&self) -> Result<Glob, Error>575 pub fn build(&self) -> Result<Glob, Error> {
576 let mut p = Parser {
577 glob: &self.glob,
578 stack: vec![Tokens::default()],
579 chars: self.glob.chars().peekable(),
580 prev: None,
581 cur: None,
582 opts: &self.opts,
583 };
584 p.parse()?;
585 if p.stack.is_empty() {
586 Err(Error {
587 glob: Some(self.glob.to_string()),
588 kind: ErrorKind::UnopenedAlternates,
589 })
590 } else if p.stack.len() > 1 {
591 Err(Error {
592 glob: Some(self.glob.to_string()),
593 kind: ErrorKind::UnclosedAlternates,
594 })
595 } else {
596 let tokens = p.stack.pop().unwrap();
597 Ok(Glob {
598 glob: self.glob.to_string(),
599 re: tokens.to_regex_with(&self.opts),
600 opts: self.opts,
601 tokens: tokens,
602 })
603 }
604 }
605
606 /// Toggle whether the pattern matches case insensitively or not.
607 ///
608 /// This is disabled by default.
case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a>609 pub fn case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
610 self.opts.case_insensitive = yes;
611 self
612 }
613
614 /// Toggle whether a literal `/` is required to match a path separator.
literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a>615 pub fn literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
616 self.opts.literal_separator = yes;
617 self
618 }
619
620 /// When enabled, a back slash (`\`) may be used to escape
621 /// special characters in a glob pattern. Additionally, this will
622 /// prevent `\` from being interpreted as a path separator on all
623 /// platforms.
624 ///
625 /// This is enabled by default on platforms where `\` is not a
626 /// path separator and disabled by default on platforms where `\`
627 /// is a path separator.
backslash_escape(&mut self, yes: bool) -> &mut GlobBuilder<'a>628 pub fn backslash_escape(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
629 self.opts.backslash_escape = yes;
630 self
631 }
632 }
633
634 impl Tokens {
635 /// Convert this pattern to a string that is guaranteed to be a valid
636 /// regular expression and will represent the matching semantics of this
637 /// glob pattern and the options given.
to_regex_with(&self, options: &GlobOptions) -> String638 fn to_regex_with(&self, options: &GlobOptions) -> String {
639 let mut re = String::new();
640 re.push_str("(?-u)");
641 if options.case_insensitive {
642 re.push_str("(?i)");
643 }
644 re.push('^');
645 // Special case. If the entire glob is just `**`, then it should match
646 // everything.
647 if self.len() == 1 && self[0] == Token::RecursivePrefix {
648 re.push_str(".*");
649 re.push('$');
650 return re;
651 }
652 self.tokens_to_regex(options, &self, &mut re);
653 re.push('$');
654 re
655 }
656
tokens_to_regex( &self, options: &GlobOptions, tokens: &[Token], re: &mut String, )657 fn tokens_to_regex(
658 &self,
659 options: &GlobOptions,
660 tokens: &[Token],
661 re: &mut String,
662 ) {
663 for tok in tokens {
664 match *tok {
665 Token::Literal(c) => {
666 re.push_str(&char_to_escaped_literal(c));
667 }
668 Token::Any => {
669 if options.literal_separator {
670 re.push_str("[^/]");
671 } else {
672 re.push_str(".");
673 }
674 }
675 Token::ZeroOrMore => {
676 if options.literal_separator {
677 re.push_str("[^/]*");
678 } else {
679 re.push_str(".*");
680 }
681 }
682 Token::RecursivePrefix => {
683 re.push_str("(?:/?|.*/)");
684 }
685 Token::RecursiveSuffix => {
686 re.push_str("(?:/?|/.*)");
687 }
688 Token::RecursiveZeroOrMore => {
689 re.push_str("(?:/|/.*/)");
690 }
691 Token::Class { negated, ref ranges } => {
692 re.push('[');
693 if negated {
694 re.push('^');
695 }
696 for r in ranges {
697 if r.0 == r.1 {
698 // Not strictly necessary, but nicer to look at.
699 re.push_str(&char_to_escaped_literal(r.0));
700 } else {
701 re.push_str(&char_to_escaped_literal(r.0));
702 re.push('-');
703 re.push_str(&char_to_escaped_literal(r.1));
704 }
705 }
706 re.push(']');
707 }
708 Token::Alternates(ref patterns) => {
709 let mut parts = vec![];
710 for pat in patterns {
711 let mut altre = String::new();
712 self.tokens_to_regex(options, &pat, &mut altre);
713 if !altre.is_empty() {
714 parts.push(altre);
715 }
716 }
717
718 // It is possible to have an empty set in which case the
719 // resulting alternation '()' would be an error.
720 if !parts.is_empty() {
721 re.push('(');
722 re.push_str(&parts.join("|"));
723 re.push(')');
724 }
725 }
726 }
727 }
728 }
729 }
730
731 /// Convert a Unicode scalar value to an escaped string suitable for use as
732 /// a literal in a non-Unicode regex.
char_to_escaped_literal(c: char) -> String733 fn char_to_escaped_literal(c: char) -> String {
734 bytes_to_escaped_literal(&c.to_string().into_bytes())
735 }
736
737 /// Converts an arbitrary sequence of bytes to a UTF-8 string. All non-ASCII
738 /// code units are converted to their escaped form.
bytes_to_escaped_literal(bs: &[u8]) -> String739 fn bytes_to_escaped_literal(bs: &[u8]) -> String {
740 let mut s = String::with_capacity(bs.len());
741 for &b in bs {
742 if b <= 0x7F {
743 s.push_str(®ex::escape(&(b as char).to_string()));
744 } else {
745 s.push_str(&format!("\\x{:02x}", b));
746 }
747 }
748 s
749 }
750
751 struct Parser<'a> {
752 glob: &'a str,
753 stack: Vec<Tokens>,
754 chars: iter::Peekable<str::Chars<'a>>,
755 prev: Option<char>,
756 cur: Option<char>,
757 opts: &'a GlobOptions,
758 }
759
760 impl<'a> Parser<'a> {
error(&self, kind: ErrorKind) -> Error761 fn error(&self, kind: ErrorKind) -> Error {
762 Error { glob: Some(self.glob.to_string()), kind: kind }
763 }
764
parse(&mut self) -> Result<(), Error>765 fn parse(&mut self) -> Result<(), Error> {
766 while let Some(c) = self.bump() {
767 match c {
768 '?' => self.push_token(Token::Any)?,
769 '*' => self.parse_star()?,
770 '[' => self.parse_class()?,
771 '{' => self.push_alternate()?,
772 '}' => self.pop_alternate()?,
773 ',' => self.parse_comma()?,
774 '\\' => self.parse_backslash()?,
775 c => self.push_token(Token::Literal(c))?,
776 }
777 }
778 Ok(())
779 }
780
push_alternate(&mut self) -> Result<(), Error>781 fn push_alternate(&mut self) -> Result<(), Error> {
782 if self.stack.len() > 1 {
783 return Err(self.error(ErrorKind::NestedAlternates));
784 }
785 Ok(self.stack.push(Tokens::default()))
786 }
787
pop_alternate(&mut self) -> Result<(), Error>788 fn pop_alternate(&mut self) -> Result<(), Error> {
789 let mut alts = vec![];
790 while self.stack.len() >= 2 {
791 alts.push(self.stack.pop().unwrap());
792 }
793 self.push_token(Token::Alternates(alts))
794 }
795
push_token(&mut self, tok: Token) -> Result<(), Error>796 fn push_token(&mut self, tok: Token) -> Result<(), Error> {
797 if let Some(ref mut pat) = self.stack.last_mut() {
798 return Ok(pat.push(tok));
799 }
800 Err(self.error(ErrorKind::UnopenedAlternates))
801 }
802
pop_token(&mut self) -> Result<Token, Error>803 fn pop_token(&mut self) -> Result<Token, Error> {
804 if let Some(ref mut pat) = self.stack.last_mut() {
805 return Ok(pat.pop().unwrap());
806 }
807 Err(self.error(ErrorKind::UnopenedAlternates))
808 }
809
have_tokens(&self) -> Result<bool, Error>810 fn have_tokens(&self) -> Result<bool, Error> {
811 match self.stack.last() {
812 None => Err(self.error(ErrorKind::UnopenedAlternates)),
813 Some(ref pat) => Ok(!pat.is_empty()),
814 }
815 }
816
parse_comma(&mut self) -> Result<(), Error>817 fn parse_comma(&mut self) -> Result<(), Error> {
818 // If we aren't inside a group alternation, then don't
819 // treat commas specially. Otherwise, we need to start
820 // a new alternate.
821 if self.stack.len() <= 1 {
822 self.push_token(Token::Literal(','))
823 } else {
824 Ok(self.stack.push(Tokens::default()))
825 }
826 }
827
parse_backslash(&mut self) -> Result<(), Error>828 fn parse_backslash(&mut self) -> Result<(), Error> {
829 if self.opts.backslash_escape {
830 match self.bump() {
831 None => Err(self.error(ErrorKind::DanglingEscape)),
832 Some(c) => self.push_token(Token::Literal(c)),
833 }
834 } else if is_separator('\\') {
835 // Normalize all patterns to use / as a separator.
836 self.push_token(Token::Literal('/'))
837 } else {
838 self.push_token(Token::Literal('\\'))
839 }
840 }
841
parse_star(&mut self) -> Result<(), Error>842 fn parse_star(&mut self) -> Result<(), Error> {
843 let prev = self.prev;
844 if self.peek() != Some('*') {
845 self.push_token(Token::ZeroOrMore)?;
846 return Ok(());
847 }
848 assert!(self.bump() == Some('*'));
849 if !self.have_tokens()? {
850 if !self.peek().map_or(true, is_separator) {
851 self.push_token(Token::ZeroOrMore)?;
852 self.push_token(Token::ZeroOrMore)?;
853 } else {
854 self.push_token(Token::RecursivePrefix)?;
855 assert!(self.bump().map_or(true, is_separator));
856 }
857 return Ok(());
858 }
859
860 if !prev.map(is_separator).unwrap_or(false) {
861 if self.stack.len() <= 1
862 || (prev != Some(',') && prev != Some('{'))
863 {
864 self.push_token(Token::ZeroOrMore)?;
865 self.push_token(Token::ZeroOrMore)?;
866 return Ok(());
867 }
868 }
869 let is_suffix = match self.peek() {
870 None => {
871 assert!(self.bump().is_none());
872 true
873 }
874 Some(',') | Some('}') if self.stack.len() >= 2 => true,
875 Some(c) if is_separator(c) => {
876 assert!(self.bump().map(is_separator).unwrap_or(false));
877 false
878 }
879 _ => {
880 self.push_token(Token::ZeroOrMore)?;
881 self.push_token(Token::ZeroOrMore)?;
882 return Ok(());
883 }
884 };
885 match self.pop_token()? {
886 Token::RecursivePrefix => {
887 self.push_token(Token::RecursivePrefix)?;
888 }
889 Token::RecursiveSuffix => {
890 self.push_token(Token::RecursiveSuffix)?;
891 }
892 _ => {
893 if is_suffix {
894 self.push_token(Token::RecursiveSuffix)?;
895 } else {
896 self.push_token(Token::RecursiveZeroOrMore)?;
897 }
898 }
899 }
900 Ok(())
901 }
902
parse_class(&mut self) -> Result<(), Error>903 fn parse_class(&mut self) -> Result<(), Error> {
904 fn add_to_last_range(
905 glob: &str,
906 r: &mut (char, char),
907 add: char,
908 ) -> Result<(), Error> {
909 r.1 = add;
910 if r.1 < r.0 {
911 Err(Error {
912 glob: Some(glob.to_string()),
913 kind: ErrorKind::InvalidRange(r.0, r.1),
914 })
915 } else {
916 Ok(())
917 }
918 }
919 let mut ranges = vec![];
920 let negated = match self.chars.peek() {
921 Some(&'!') | Some(&'^') => {
922 let bump = self.bump();
923 assert!(bump == Some('!') || bump == Some('^'));
924 true
925 }
926 _ => false,
927 };
928 let mut first = true;
929 let mut in_range = false;
930 loop {
931 let c = match self.bump() {
932 Some(c) => c,
933 // The only way to successfully break this loop is to observe
934 // a ']'.
935 None => return Err(self.error(ErrorKind::UnclosedClass)),
936 };
937 match c {
938 ']' => {
939 if first {
940 ranges.push((']', ']'));
941 } else {
942 break;
943 }
944 }
945 '-' => {
946 if first {
947 ranges.push(('-', '-'));
948 } else if in_range {
949 // invariant: in_range is only set when there is
950 // already at least one character seen.
951 let r = ranges.last_mut().unwrap();
952 add_to_last_range(&self.glob, r, '-')?;
953 in_range = false;
954 } else {
955 assert!(!ranges.is_empty());
956 in_range = true;
957 }
958 }
959 c => {
960 if in_range {
961 // invariant: in_range is only set when there is
962 // already at least one character seen.
963 add_to_last_range(
964 &self.glob,
965 ranges.last_mut().unwrap(),
966 c,
967 )?;
968 } else {
969 ranges.push((c, c));
970 }
971 in_range = false;
972 }
973 }
974 first = false;
975 }
976 if in_range {
977 // Means that the last character in the class was a '-', so add
978 // it as a literal.
979 ranges.push(('-', '-'));
980 }
981 self.push_token(Token::Class { negated: negated, ranges: ranges })
982 }
983
bump(&mut self) -> Option<char>984 fn bump(&mut self) -> Option<char> {
985 self.prev = self.cur;
986 self.cur = self.chars.next();
987 self.cur
988 }
989
peek(&mut self) -> Option<char>990 fn peek(&mut self) -> Option<char> {
991 self.chars.peek().map(|&ch| ch)
992 }
993 }
994
995 #[cfg(test)]
starts_with(needle: &[u8], haystack: &[u8]) -> bool996 fn starts_with(needle: &[u8], haystack: &[u8]) -> bool {
997 needle.len() <= haystack.len() && needle == &haystack[..needle.len()]
998 }
999
1000 #[cfg(test)]
ends_with(needle: &[u8], haystack: &[u8]) -> bool1001 fn ends_with(needle: &[u8], haystack: &[u8]) -> bool {
1002 if needle.len() > haystack.len() {
1003 return false;
1004 }
1005 needle == &haystack[haystack.len() - needle.len()..]
1006 }
1007
1008 #[cfg(test)]
1009 mod tests {
1010 use super::Token::*;
1011 use super::{Glob, GlobBuilder, Token};
1012 use {ErrorKind, GlobSetBuilder};
1013
1014 #[derive(Clone, Copy, Debug, Default)]
1015 struct Options {
1016 casei: Option<bool>,
1017 litsep: Option<bool>,
1018 bsesc: Option<bool>,
1019 }
1020
1021 macro_rules! syntax {
1022 ($name:ident, $pat:expr, $tokens:expr) => {
1023 #[test]
1024 fn $name() {
1025 let pat = Glob::new($pat).unwrap();
1026 assert_eq!($tokens, pat.tokens.0);
1027 }
1028 };
1029 }
1030
1031 macro_rules! syntaxerr {
1032 ($name:ident, $pat:expr, $err:expr) => {
1033 #[test]
1034 fn $name() {
1035 let err = Glob::new($pat).unwrap_err();
1036 assert_eq!(&$err, err.kind());
1037 }
1038 };
1039 }
1040
1041 macro_rules! toregex {
1042 ($name:ident, $pat:expr, $re:expr) => {
1043 toregex!($name, $pat, $re, Options::default());
1044 };
1045 ($name:ident, $pat:expr, $re:expr, $options:expr) => {
1046 #[test]
1047 fn $name() {
1048 let mut builder = GlobBuilder::new($pat);
1049 if let Some(casei) = $options.casei {
1050 builder.case_insensitive(casei);
1051 }
1052 if let Some(litsep) = $options.litsep {
1053 builder.literal_separator(litsep);
1054 }
1055 if let Some(bsesc) = $options.bsesc {
1056 builder.backslash_escape(bsesc);
1057 }
1058 let pat = builder.build().unwrap();
1059 assert_eq!(format!("(?-u){}", $re), pat.regex());
1060 }
1061 };
1062 }
1063
1064 macro_rules! matches {
1065 ($name:ident, $pat:expr, $path:expr) => {
1066 matches!($name, $pat, $path, Options::default());
1067 };
1068 ($name:ident, $pat:expr, $path:expr, $options:expr) => {
1069 #[test]
1070 fn $name() {
1071 let mut builder = GlobBuilder::new($pat);
1072 if let Some(casei) = $options.casei {
1073 builder.case_insensitive(casei);
1074 }
1075 if let Some(litsep) = $options.litsep {
1076 builder.literal_separator(litsep);
1077 }
1078 if let Some(bsesc) = $options.bsesc {
1079 builder.backslash_escape(bsesc);
1080 }
1081 let pat = builder.build().unwrap();
1082 let matcher = pat.compile_matcher();
1083 let strategic = pat.compile_strategic_matcher();
1084 let set = GlobSetBuilder::new().add(pat).build().unwrap();
1085 assert!(matcher.is_match($path));
1086 assert!(strategic.is_match($path));
1087 assert!(set.is_match($path));
1088 }
1089 };
1090 }
1091
1092 macro_rules! nmatches {
1093 ($name:ident, $pat:expr, $path:expr) => {
1094 nmatches!($name, $pat, $path, Options::default());
1095 };
1096 ($name:ident, $pat:expr, $path:expr, $options:expr) => {
1097 #[test]
1098 fn $name() {
1099 let mut builder = GlobBuilder::new($pat);
1100 if let Some(casei) = $options.casei {
1101 builder.case_insensitive(casei);
1102 }
1103 if let Some(litsep) = $options.litsep {
1104 builder.literal_separator(litsep);
1105 }
1106 if let Some(bsesc) = $options.bsesc {
1107 builder.backslash_escape(bsesc);
1108 }
1109 let pat = builder.build().unwrap();
1110 let matcher = pat.compile_matcher();
1111 let strategic = pat.compile_strategic_matcher();
1112 let set = GlobSetBuilder::new().add(pat).build().unwrap();
1113 assert!(!matcher.is_match($path));
1114 assert!(!strategic.is_match($path));
1115 assert!(!set.is_match($path));
1116 }
1117 };
1118 }
1119
s(string: &str) -> String1120 fn s(string: &str) -> String {
1121 string.to_string()
1122 }
1123
class(s: char, e: char) -> Token1124 fn class(s: char, e: char) -> Token {
1125 Class { negated: false, ranges: vec![(s, e)] }
1126 }
1127
classn(s: char, e: char) -> Token1128 fn classn(s: char, e: char) -> Token {
1129 Class { negated: true, ranges: vec![(s, e)] }
1130 }
1131
rclass(ranges: &[(char, char)]) -> Token1132 fn rclass(ranges: &[(char, char)]) -> Token {
1133 Class { negated: false, ranges: ranges.to_vec() }
1134 }
1135
rclassn(ranges: &[(char, char)]) -> Token1136 fn rclassn(ranges: &[(char, char)]) -> Token {
1137 Class { negated: true, ranges: ranges.to_vec() }
1138 }
1139
1140 syntax!(literal1, "a", vec![Literal('a')]);
1141 syntax!(literal2, "ab", vec![Literal('a'), Literal('b')]);
1142 syntax!(any1, "?", vec![Any]);
1143 syntax!(any2, "a?b", vec![Literal('a'), Any, Literal('b')]);
1144 syntax!(seq1, "*", vec![ZeroOrMore]);
1145 syntax!(seq2, "a*b", vec![Literal('a'), ZeroOrMore, Literal('b')]);
1146 syntax!(
1147 seq3,
1148 "*a*b*",
1149 vec![ZeroOrMore, Literal('a'), ZeroOrMore, Literal('b'), ZeroOrMore,]
1150 );
1151 syntax!(rseq1, "**", vec![RecursivePrefix]);
1152 syntax!(rseq2, "**/", vec![RecursivePrefix]);
1153 syntax!(rseq3, "/**", vec![RecursiveSuffix]);
1154 syntax!(rseq4, "/**/", vec![RecursiveZeroOrMore]);
1155 syntax!(
1156 rseq5,
1157 "a/**/b",
1158 vec![Literal('a'), RecursiveZeroOrMore, Literal('b'),]
1159 );
1160 syntax!(cls1, "[a]", vec![class('a', 'a')]);
1161 syntax!(cls2, "[!a]", vec![classn('a', 'a')]);
1162 syntax!(cls3, "[a-z]", vec![class('a', 'z')]);
1163 syntax!(cls4, "[!a-z]", vec![classn('a', 'z')]);
1164 syntax!(cls5, "[-]", vec![class('-', '-')]);
1165 syntax!(cls6, "[]]", vec![class(']', ']')]);
1166 syntax!(cls7, "[*]", vec![class('*', '*')]);
1167 syntax!(cls8, "[!!]", vec![classn('!', '!')]);
1168 syntax!(cls9, "[a-]", vec![rclass(&[('a', 'a'), ('-', '-')])]);
1169 syntax!(cls10, "[-a-z]", vec![rclass(&[('-', '-'), ('a', 'z')])]);
1170 syntax!(cls11, "[a-z-]", vec![rclass(&[('a', 'z'), ('-', '-')])]);
1171 syntax!(
1172 cls12,
1173 "[-a-z-]",
1174 vec![rclass(&[('-', '-'), ('a', 'z'), ('-', '-')]),]
1175 );
1176 syntax!(cls13, "[]-z]", vec![class(']', 'z')]);
1177 syntax!(cls14, "[--z]", vec![class('-', 'z')]);
1178 syntax!(cls15, "[ --]", vec![class(' ', '-')]);
1179 syntax!(cls16, "[0-9a-z]", vec![rclass(&[('0', '9'), ('a', 'z')])]);
1180 syntax!(cls17, "[a-z0-9]", vec![rclass(&[('a', 'z'), ('0', '9')])]);
1181 syntax!(cls18, "[!0-9a-z]", vec![rclassn(&[('0', '9'), ('a', 'z')])]);
1182 syntax!(cls19, "[!a-z0-9]", vec![rclassn(&[('a', 'z'), ('0', '9')])]);
1183 syntax!(cls20, "[^a]", vec![classn('a', 'a')]);
1184 syntax!(cls21, "[^a-z]", vec![classn('a', 'z')]);
1185
1186 syntaxerr!(err_unclosed1, "[", ErrorKind::UnclosedClass);
1187 syntaxerr!(err_unclosed2, "[]", ErrorKind::UnclosedClass);
1188 syntaxerr!(err_unclosed3, "[!", ErrorKind::UnclosedClass);
1189 syntaxerr!(err_unclosed4, "[!]", ErrorKind::UnclosedClass);
1190 syntaxerr!(err_range1, "[z-a]", ErrorKind::InvalidRange('z', 'a'));
1191 syntaxerr!(err_range2, "[z--]", ErrorKind::InvalidRange('z', '-'));
1192
1193 const CASEI: Options =
1194 Options { casei: Some(true), litsep: None, bsesc: None };
1195 const SLASHLIT: Options =
1196 Options { casei: None, litsep: Some(true), bsesc: None };
1197 const NOBSESC: Options =
1198 Options { casei: None, litsep: None, bsesc: Some(false) };
1199 const BSESC: Options =
1200 Options { casei: None, litsep: None, bsesc: Some(true) };
1201
1202 toregex!(re_casei, "a", "(?i)^a$", &CASEI);
1203
1204 toregex!(re_slash1, "?", r"^[^/]$", SLASHLIT);
1205 toregex!(re_slash2, "*", r"^[^/]*$", SLASHLIT);
1206
1207 toregex!(re1, "a", "^a$");
1208 toregex!(re2, "?", "^.$");
1209 toregex!(re3, "*", "^.*$");
1210 toregex!(re4, "a?", "^a.$");
1211 toregex!(re5, "?a", "^.a$");
1212 toregex!(re6, "a*", "^a.*$");
1213 toregex!(re7, "*a", "^.*a$");
1214 toregex!(re8, "[*]", r"^[\*]$");
1215 toregex!(re9, "[+]", r"^[\+]$");
1216 toregex!(re10, "+", r"^\+$");
1217 toregex!(re11, "☃", r"^\xe2\x98\x83$");
1218 toregex!(re12, "**", r"^.*$");
1219 toregex!(re13, "**/", r"^.*$");
1220 toregex!(re14, "**/*", r"^(?:/?|.*/).*$");
1221 toregex!(re15, "**/**", r"^.*$");
1222 toregex!(re16, "**/**/*", r"^(?:/?|.*/).*$");
1223 toregex!(re17, "**/**/**", r"^.*$");
1224 toregex!(re18, "**/**/**/*", r"^(?:/?|.*/).*$");
1225 toregex!(re19, "a/**", r"^a(?:/?|/.*)$");
1226 toregex!(re20, "a/**/**", r"^a(?:/?|/.*)$");
1227 toregex!(re21, "a/**/**/**", r"^a(?:/?|/.*)$");
1228 toregex!(re22, "a/**/b", r"^a(?:/|/.*/)b$");
1229 toregex!(re23, "a/**/**/b", r"^a(?:/|/.*/)b$");
1230 toregex!(re24, "a/**/**/**/b", r"^a(?:/|/.*/)b$");
1231 toregex!(re25, "**/b", r"^(?:/?|.*/)b$");
1232 toregex!(re26, "**/**/b", r"^(?:/?|.*/)b$");
1233 toregex!(re27, "**/**/**/b", r"^(?:/?|.*/)b$");
1234 toregex!(re28, "a**", r"^a.*.*$");
1235 toregex!(re29, "**a", r"^.*.*a$");
1236 toregex!(re30, "a**b", r"^a.*.*b$");
1237 toregex!(re31, "***", r"^.*.*.*$");
1238 toregex!(re32, "/a**", r"^/a.*.*$");
1239 toregex!(re33, "/**a", r"^/.*.*a$");
1240 toregex!(re34, "/a**b", r"^/a.*.*b$");
1241
1242 matches!(match1, "a", "a");
1243 matches!(match2, "a*b", "a_b");
1244 matches!(match3, "a*b*c", "abc");
1245 matches!(match4, "a*b*c", "a_b_c");
1246 matches!(match5, "a*b*c", "a___b___c");
1247 matches!(match6, "abc*abc*abc", "abcabcabcabcabcabcabc");
1248 matches!(match7, "a*a*a*a*a*a*a*a*a", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
1249 matches!(match8, "a*b[xyz]c*d", "abxcdbxcddd");
1250 matches!(match9, "*.rs", ".rs");
1251 matches!(match10, "☃", "☃");
1252
1253 matches!(matchrec1, "some/**/needle.txt", "some/needle.txt");
1254 matches!(matchrec2, "some/**/needle.txt", "some/one/needle.txt");
1255 matches!(matchrec3, "some/**/needle.txt", "some/one/two/needle.txt");
1256 matches!(matchrec4, "some/**/needle.txt", "some/other/needle.txt");
1257 matches!(matchrec5, "**", "abcde");
1258 matches!(matchrec6, "**", "");
1259 matches!(matchrec7, "**", ".asdf");
1260 matches!(matchrec8, "**", "/x/.asdf");
1261 matches!(matchrec9, "some/**/**/needle.txt", "some/needle.txt");
1262 matches!(matchrec10, "some/**/**/needle.txt", "some/one/needle.txt");
1263 matches!(matchrec11, "some/**/**/needle.txt", "some/one/two/needle.txt");
1264 matches!(matchrec12, "some/**/**/needle.txt", "some/other/needle.txt");
1265 matches!(matchrec13, "**/test", "one/two/test");
1266 matches!(matchrec14, "**/test", "one/test");
1267 matches!(matchrec15, "**/test", "test");
1268 matches!(matchrec16, "/**/test", "/one/two/test");
1269 matches!(matchrec17, "/**/test", "/one/test");
1270 matches!(matchrec18, "/**/test", "/test");
1271 matches!(matchrec19, "**/.*", ".abc");
1272 matches!(matchrec20, "**/.*", "abc/.abc");
1273 matches!(matchrec21, ".*/**", ".abc");
1274 matches!(matchrec22, ".*/**", ".abc/abc");
1275 matches!(matchrec23, "foo/**", "foo");
1276 matches!(matchrec24, "**/foo/bar", "foo/bar");
1277 matches!(matchrec25, "some/*/needle.txt", "some/one/needle.txt");
1278
1279 matches!(matchrange1, "a[0-9]b", "a0b");
1280 matches!(matchrange2, "a[0-9]b", "a9b");
1281 matches!(matchrange3, "a[!0-9]b", "a_b");
1282 matches!(matchrange4, "[a-z123]", "1");
1283 matches!(matchrange5, "[1a-z23]", "1");
1284 matches!(matchrange6, "[123a-z]", "1");
1285 matches!(matchrange7, "[abc-]", "-");
1286 matches!(matchrange8, "[-abc]", "-");
1287 matches!(matchrange9, "[-a-c]", "b");
1288 matches!(matchrange10, "[a-c-]", "b");
1289 matches!(matchrange11, "[-]", "-");
1290 matches!(matchrange12, "a[^0-9]b", "a_b");
1291
1292 matches!(matchpat1, "*hello.txt", "hello.txt");
1293 matches!(matchpat2, "*hello.txt", "gareth_says_hello.txt");
1294 matches!(matchpat3, "*hello.txt", "some/path/to/hello.txt");
1295 matches!(matchpat4, "*hello.txt", "some\\path\\to\\hello.txt");
1296 matches!(matchpat5, "*hello.txt", "/an/absolute/path/to/hello.txt");
1297 matches!(matchpat6, "*some/path/to/hello.txt", "some/path/to/hello.txt");
1298 matches!(
1299 matchpat7,
1300 "*some/path/to/hello.txt",
1301 "a/bigger/some/path/to/hello.txt"
1302 );
1303
1304 matches!(matchescape, "_[[]_[]]_[?]_[*]_!_", "_[_]_?_*_!_");
1305
1306 matches!(matchcasei1, "aBcDeFg", "aBcDeFg", CASEI);
1307 matches!(matchcasei2, "aBcDeFg", "abcdefg", CASEI);
1308 matches!(matchcasei3, "aBcDeFg", "ABCDEFG", CASEI);
1309 matches!(matchcasei4, "aBcDeFg", "AbCdEfG", CASEI);
1310
1311 matches!(matchalt1, "a,b", "a,b");
1312 matches!(matchalt2, ",", ",");
1313 matches!(matchalt3, "{a,b}", "a");
1314 matches!(matchalt4, "{a,b}", "b");
1315 matches!(matchalt5, "{**/src/**,foo}", "abc/src/bar");
1316 matches!(matchalt6, "{**/src/**,foo}", "foo");
1317 matches!(matchalt7, "{[}],foo}", "}");
1318 matches!(matchalt8, "{foo}", "foo");
1319 matches!(matchalt9, "{}", "");
1320 matches!(matchalt10, "{,}", "");
1321 matches!(matchalt11, "{*.foo,*.bar,*.wat}", "test.foo");
1322 matches!(matchalt12, "{*.foo,*.bar,*.wat}", "test.bar");
1323 matches!(matchalt13, "{*.foo,*.bar,*.wat}", "test.wat");
1324
1325 matches!(matchslash1, "abc/def", "abc/def", SLASHLIT);
1326 #[cfg(unix)]
1327 nmatches!(matchslash2, "abc?def", "abc/def", SLASHLIT);
1328 #[cfg(not(unix))]
1329 nmatches!(matchslash2, "abc?def", "abc\\def", SLASHLIT);
1330 nmatches!(matchslash3, "abc*def", "abc/def", SLASHLIT);
1331 matches!(matchslash4, "abc[/]def", "abc/def", SLASHLIT); // differs
1332 #[cfg(unix)]
1333 nmatches!(matchslash5, "abc\\def", "abc/def", SLASHLIT);
1334 #[cfg(not(unix))]
1335 matches!(matchslash5, "abc\\def", "abc/def", SLASHLIT);
1336
1337 matches!(matchbackslash1, "\\[", "[", BSESC);
1338 matches!(matchbackslash2, "\\?", "?", BSESC);
1339 matches!(matchbackslash3, "\\*", "*", BSESC);
1340 matches!(matchbackslash4, "\\[a-z]", "\\a", NOBSESC);
1341 matches!(matchbackslash5, "\\?", "\\a", NOBSESC);
1342 matches!(matchbackslash6, "\\*", "\\\\", NOBSESC);
1343 #[cfg(unix)]
1344 matches!(matchbackslash7, "\\a", "a");
1345 #[cfg(not(unix))]
1346 matches!(matchbackslash8, "\\a", "/a");
1347
1348 nmatches!(matchnot1, "a*b*c", "abcd");
1349 nmatches!(matchnot2, "abc*abc*abc", "abcabcabcabcabcabcabca");
1350 nmatches!(matchnot3, "some/**/needle.txt", "some/other/notthis.txt");
1351 nmatches!(matchnot4, "some/**/**/needle.txt", "some/other/notthis.txt");
1352 nmatches!(matchnot5, "/**/test", "test");
1353 nmatches!(matchnot6, "/**/test", "/one/notthis");
1354 nmatches!(matchnot7, "/**/test", "/notthis");
1355 nmatches!(matchnot8, "**/.*", "ab.c");
1356 nmatches!(matchnot9, "**/.*", "abc/ab.c");
1357 nmatches!(matchnot10, ".*/**", "a.bc");
1358 nmatches!(matchnot11, ".*/**", "abc/a.bc");
1359 nmatches!(matchnot12, "a[0-9]b", "a_b");
1360 nmatches!(matchnot13, "a[!0-9]b", "a0b");
1361 nmatches!(matchnot14, "a[!0-9]b", "a9b");
1362 nmatches!(matchnot15, "[!-]", "-");
1363 nmatches!(matchnot16, "*hello.txt", "hello.txt-and-then-some");
1364 nmatches!(matchnot17, "*hello.txt", "goodbye.txt");
1365 nmatches!(
1366 matchnot18,
1367 "*some/path/to/hello.txt",
1368 "some/path/to/hello.txt-and-then-some"
1369 );
1370 nmatches!(
1371 matchnot19,
1372 "*some/path/to/hello.txt",
1373 "some/other/path/to/hello.txt"
1374 );
1375 nmatches!(matchnot20, "a", "foo/a");
1376 nmatches!(matchnot21, "./foo", "foo");
1377 nmatches!(matchnot22, "**/foo", "foofoo");
1378 nmatches!(matchnot23, "**/foo/bar", "foofoo/bar");
1379 nmatches!(matchnot24, "/*.c", "mozilla-sha1/sha1.c");
1380 nmatches!(matchnot25, "*.c", "mozilla-sha1/sha1.c", SLASHLIT);
1381 nmatches!(
1382 matchnot26,
1383 "**/m4/ltoptions.m4",
1384 "csharp/src/packages/repositories.config",
1385 SLASHLIT
1386 );
1387 nmatches!(matchnot27, "a[^0-9]b", "a0b");
1388 nmatches!(matchnot28, "a[^0-9]b", "a9b");
1389 nmatches!(matchnot29, "[^-]", "-");
1390 nmatches!(matchnot30, "some/*/needle.txt", "some/needle.txt");
1391 nmatches!(
1392 matchrec31,
1393 "some/*/needle.txt",
1394 "some/one/two/needle.txt",
1395 SLASHLIT
1396 );
1397 nmatches!(
1398 matchrec32,
1399 "some/*/needle.txt",
1400 "some/one/two/three/needle.txt",
1401 SLASHLIT
1402 );
1403
1404 macro_rules! extract {
1405 ($which:ident, $name:ident, $pat:expr, $expect:expr) => {
1406 extract!($which, $name, $pat, $expect, Options::default());
1407 };
1408 ($which:ident, $name:ident, $pat:expr, $expect:expr, $options:expr) => {
1409 #[test]
1410 fn $name() {
1411 let mut builder = GlobBuilder::new($pat);
1412 if let Some(casei) = $options.casei {
1413 builder.case_insensitive(casei);
1414 }
1415 if let Some(litsep) = $options.litsep {
1416 builder.literal_separator(litsep);
1417 }
1418 if let Some(bsesc) = $options.bsesc {
1419 builder.backslash_escape(bsesc);
1420 }
1421 let pat = builder.build().unwrap();
1422 assert_eq!($expect, pat.$which());
1423 }
1424 };
1425 }
1426
1427 macro_rules! literal {
1428 ($($tt:tt)*) => { extract!(literal, $($tt)*); }
1429 }
1430
1431 macro_rules! basetokens {
1432 ($($tt:tt)*) => { extract!(basename_tokens, $($tt)*); }
1433 }
1434
1435 macro_rules! ext {
1436 ($($tt:tt)*) => { extract!(ext, $($tt)*); }
1437 }
1438
1439 macro_rules! required_ext {
1440 ($($tt:tt)*) => { extract!(required_ext, $($tt)*); }
1441 }
1442
1443 macro_rules! prefix {
1444 ($($tt:tt)*) => { extract!(prefix, $($tt)*); }
1445 }
1446
1447 macro_rules! suffix {
1448 ($($tt:tt)*) => { extract!(suffix, $($tt)*); }
1449 }
1450
1451 macro_rules! baseliteral {
1452 ($($tt:tt)*) => { extract!(basename_literal, $($tt)*); }
1453 }
1454
1455 literal!(extract_lit1, "foo", Some(s("foo")));
1456 literal!(extract_lit2, "foo", None, CASEI);
1457 literal!(extract_lit3, "/foo", Some(s("/foo")));
1458 literal!(extract_lit4, "/foo/", Some(s("/foo/")));
1459 literal!(extract_lit5, "/foo/bar", Some(s("/foo/bar")));
1460 literal!(extract_lit6, "*.foo", None);
1461 literal!(extract_lit7, "foo/bar", Some(s("foo/bar")));
1462 literal!(extract_lit8, "**/foo/bar", None);
1463
1464 basetokens!(
1465 extract_basetoks1,
1466 "**/foo",
1467 Some(&*vec![Literal('f'), Literal('o'), Literal('o'),])
1468 );
1469 basetokens!(extract_basetoks2, "**/foo", None, CASEI);
1470 basetokens!(
1471 extract_basetoks3,
1472 "**/foo",
1473 Some(&*vec![Literal('f'), Literal('o'), Literal('o'),]),
1474 SLASHLIT
1475 );
1476 basetokens!(extract_basetoks4, "*foo", None, SLASHLIT);
1477 basetokens!(extract_basetoks5, "*foo", None);
1478 basetokens!(extract_basetoks6, "**/fo*o", None);
1479 basetokens!(
1480 extract_basetoks7,
1481 "**/fo*o",
1482 Some(&*vec![Literal('f'), Literal('o'), ZeroOrMore, Literal('o'),]),
1483 SLASHLIT
1484 );
1485
1486 ext!(extract_ext1, "**/*.rs", Some(s(".rs")));
1487 ext!(extract_ext2, "**/*.rs.bak", None);
1488 ext!(extract_ext3, "*.rs", Some(s(".rs")));
1489 ext!(extract_ext4, "a*.rs", None);
1490 ext!(extract_ext5, "/*.c", None);
1491 ext!(extract_ext6, "*.c", None, SLASHLIT);
1492 ext!(extract_ext7, "*.c", Some(s(".c")));
1493
1494 required_ext!(extract_req_ext1, "*.rs", Some(s(".rs")));
1495 required_ext!(extract_req_ext2, "/foo/bar/*.rs", Some(s(".rs")));
1496 required_ext!(extract_req_ext3, "/foo/bar/*.rs", Some(s(".rs")));
1497 required_ext!(extract_req_ext4, "/foo/bar/.rs", Some(s(".rs")));
1498 required_ext!(extract_req_ext5, ".rs", Some(s(".rs")));
1499 required_ext!(extract_req_ext6, "./rs", None);
1500 required_ext!(extract_req_ext7, "foo", None);
1501 required_ext!(extract_req_ext8, ".foo/", None);
1502 required_ext!(extract_req_ext9, "foo/", None);
1503
1504 prefix!(extract_prefix1, "/foo", Some(s("/foo")));
1505 prefix!(extract_prefix2, "/foo/*", Some(s("/foo/")));
1506 prefix!(extract_prefix3, "**/foo", None);
1507 prefix!(extract_prefix4, "foo/**", None);
1508
1509 suffix!(extract_suffix1, "**/foo/bar", Some((s("/foo/bar"), true)));
1510 suffix!(extract_suffix2, "*/foo/bar", Some((s("/foo/bar"), false)));
1511 suffix!(extract_suffix3, "*/foo/bar", None, SLASHLIT);
1512 suffix!(extract_suffix4, "foo/bar", Some((s("foo/bar"), false)));
1513 suffix!(extract_suffix5, "*.foo", Some((s(".foo"), false)));
1514 suffix!(extract_suffix6, "*.foo", None, SLASHLIT);
1515 suffix!(extract_suffix7, "**/*_test", Some((s("_test"), false)));
1516
1517 baseliteral!(extract_baselit1, "**/foo", Some(s("foo")));
1518 baseliteral!(extract_baselit2, "foo", None);
1519 baseliteral!(extract_baselit3, "*foo", None);
1520 baseliteral!(extract_baselit4, "*/foo", None);
1521 }
1522