-
Notifications
You must be signed in to change notification settings - Fork 78
/
lib.rs
1501 lines (1354 loc) · 51.7 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Support for matching file paths against Unix shell style patterns.
//!
//! The `glob` and `glob_with` functions allow querying the filesystem for all
//! files that match a particular pattern (similar to the libc `glob` function).
//! The methods on the `Pattern` type provide functionality for checking if
//! individual paths match a particular pattern (similar to the libc `fnmatch`
//! function).
//!
//! For consistency across platforms, and for Windows support, this module
//! is implemented entirely in Rust rather than deferring to the libc
//! `glob`/`fnmatch` functions.
//!
//! # Examples
//!
//! To print all jpg files in `/media/` and all of its subdirectories.
//!
//! ```rust,no_run
//! use glob::glob;
//!
//! for entry in glob("/media/**/*.jpg").expect("Failed to read glob pattern") {
//! match entry {
//! Ok(path) => println!("{:?}", path.display()),
//! Err(e) => println!("{:?}", e),
//! }
//! }
//! ```
//!
//! To print all files containing the letter "a", case insensitive, in a `local`
//! directory relative to the current working directory. This ignores errors
//! instead of printing them.
//!
//! ```rust,no_run
//! use glob::glob_with;
//! use glob::MatchOptions;
//!
//! let options = MatchOptions {
//! case_sensitive: false,
//! require_literal_separator: false,
//! require_literal_leading_dot: false,
//! };
//! for entry in glob_with("local/*a*", options).unwrap() {
//! if let Ok(path) = entry {
//! println!("{:?}", path.display())
//! }
//! }
//! ```
#![doc(
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://docs.rs/glob/0.3.1"
)]
#![deny(missing_docs)]
#[cfg(test)]
#[macro_use]
extern crate doc_comment;
#[cfg(test)]
doctest!("../README.md");
use std::cmp;
use std::error::Error;
use std::fmt;
use std::fs;
use std::fs::DirEntry;
use std::io;
use std::ops::Deref;
use std::path::{self, Component, Path, PathBuf};
use std::str::FromStr;
use CharSpecifier::{CharRange, SingleChar};
use MatchResult::{EntirePatternDoesntMatch, Match, SubPatternDoesntMatch};
use PatternToken::AnyExcept;
use PatternToken::{AnyChar, AnyRecursiveSequence, AnySequence, AnyWithin, Char};
/// An iterator that yields `Path`s from the filesystem that match a particular
/// pattern.
///
/// Note that it yields `GlobResult` in order to report any `IoErrors` that may
/// arise during iteration. If a directory matches but is unreadable,
/// thereby preventing its contents from being checked for matches, a
/// `GlobError` is returned to express this.
///
/// See the `glob` function for more details.
#[derive(Debug)]
pub struct Paths {
dir_patterns: Vec<Pattern>,
require_dir: bool,
options: MatchOptions,
todo: Vec<Result<(PathWrapper, usize), GlobError>>,
scope: Option<PathWrapper>,
}
/// Return an iterator that produces all the `Path`s that match the given
/// pattern using default match options, which may be absolute or relative to
/// the current working directory.
///
/// This may return an error if the pattern is invalid.
///
/// This method uses the default match options and is equivalent to calling
/// `glob_with(pattern, MatchOptions::new())`. Use `glob_with` directly if you
/// want to use non-default match options.
///
/// When iterating, each result is a `GlobResult` which expresses the
/// possibility that there was an `IoError` when attempting to read the contents
/// of the matched path. In other words, each item returned by the iterator
/// will either be an `Ok(Path)` if the path matched, or an `Err(GlobError)` if
/// the path (partially) matched _but_ its contents could not be read in order
/// to determine if its contents matched.
///
/// See the `Paths` documentation for more information.
///
/// # Examples
///
/// Consider a directory `/media/pictures` containing only the files
/// `kittens.jpg`, `puppies.jpg` and `hamsters.gif`:
///
/// ```rust,no_run
/// use glob::glob;
///
/// for entry in glob("/media/pictures/*.jpg").unwrap() {
/// match entry {
/// Ok(path) => println!("{:?}", path.display()),
///
/// // if the path matched but was unreadable,
/// // thereby preventing its contents from matching
/// Err(e) => println!("{:?}", e),
/// }
/// }
/// ```
///
/// The above code will print:
///
/// ```ignore
/// /media/pictures/kittens.jpg
/// /media/pictures/puppies.jpg
/// ```
///
/// If you want to ignore unreadable paths, you can use something like
/// `filter_map`:
///
/// ```rust
/// use glob::glob;
/// use std::result::Result;
///
/// for path in glob("/media/pictures/*.jpg").unwrap().filter_map(Result::ok) {
/// println!("{}", path.display());
/// }
/// ```
/// Paths are yielded in alphabetical order.
pub fn glob(pattern: &str) -> Result<Paths, PatternError> {
glob_with(pattern, MatchOptions::new())
}
/// Return an iterator that produces all the `Path`s that match the given
/// pattern using the specified match options, which may be absolute or relative
/// to the current working directory.
///
/// This may return an error if the pattern is invalid.
///
/// This function accepts Unix shell style patterns as described by
/// `Pattern::new(..)`. The options given are passed through unchanged to
/// `Pattern::matches_with(..)` with the exception that
/// `require_literal_separator` is always set to `true` regardless of the value
/// passed to this function.
///
/// Paths are yielded in alphabetical order.
pub fn glob_with(pattern: &str, options: MatchOptions) -> Result<Paths, PatternError> {
#[cfg(windows)]
fn check_windows_verbatim(p: &Path) -> bool {
match p.components().next() {
Some(Component::Prefix(ref p)) => {
// Allow VerbatimDisk paths. std canonicalize() generates them, and they work fine
p.kind().is_verbatim()
&& if let std::path::Prefix::VerbatimDisk(_) = p.kind() {
false
} else {
true
}
}
_ => false,
}
}
#[cfg(not(windows))]
fn check_windows_verbatim(_: &Path) -> bool {
false
}
#[cfg(windows)]
fn to_scope(p: &Path) -> PathBuf {
// FIXME handle volume relative paths here
p.to_path_buf()
}
#[cfg(not(windows))]
fn to_scope(p: &Path) -> PathBuf {
p.to_path_buf()
}
// make sure that the pattern is valid first, else early return with error
if let Err(err) = Pattern::new(pattern) {
return Err(err);
}
let mut components = Path::new(pattern).components().peekable();
loop {
match components.peek() {
Some(&Component::Prefix(..)) | Some(&Component::RootDir) => {
components.next();
}
_ => break,
}
}
let rest = components.map(|s| s.as_os_str()).collect::<PathBuf>();
let normalized_pattern = Path::new(pattern).iter().collect::<PathBuf>();
let root_len = normalized_pattern.to_str().unwrap().len() - rest.to_str().unwrap().len();
let root = if root_len > 0 {
Some(Path::new(&pattern[..root_len]))
} else {
None
};
if root_len > 0 && check_windows_verbatim(root.unwrap()) {
// FIXME: How do we want to handle verbatim paths? I'm inclined to
// return nothing, since we can't very well find all UNC shares with a
// 1-letter server name.
return Ok(Paths {
dir_patterns: Vec::new(),
require_dir: false,
options,
todo: Vec::new(),
scope: None,
});
}
let scope = root.map_or_else(|| PathBuf::from("."), to_scope);
let scope = PathWrapper::from_path(scope);
let mut dir_patterns = Vec::new();
let components =
pattern[cmp::min(root_len, pattern.len())..].split_terminator(path::is_separator);
for component in components {
dir_patterns.push(Pattern::new(component)?);
}
if root_len == pattern.len() {
dir_patterns.push(Pattern {
original: "".to_string(),
tokens: Vec::new(),
is_recursive: false,
});
}
let last_is_separator = pattern.chars().next_back().map(path::is_separator);
let require_dir = last_is_separator == Some(true);
let todo = Vec::new();
Ok(Paths {
dir_patterns,
require_dir,
options,
todo,
scope: Some(scope),
})
}
/// A glob iteration error.
///
/// This is typically returned when a particular path cannot be read
/// to determine if its contents match the glob pattern. This is possible
/// if the program lacks the appropriate permissions, for example.
#[derive(Debug)]
pub struct GlobError {
path: PathBuf,
error: io::Error,
}
impl GlobError {
/// The Path that the error corresponds to.
pub fn path(&self) -> &Path {
&self.path
}
/// The error in question.
pub fn error(&self) -> &io::Error {
&self.error
}
/// Consumes self, returning the _raw_ underlying `io::Error`
pub fn into_error(self) -> io::Error {
self.error
}
}
impl Error for GlobError {
#[allow(deprecated)]
fn description(&self) -> &str {
self.error.description()
}
#[allow(unknown_lints, bare_trait_objects)]
fn cause(&self) -> Option<&Error> {
Some(&self.error)
}
}
impl fmt::Display for GlobError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"attempting to read `{}` resulted in an error: {}",
self.path.display(),
self.error
)
}
}
#[derive(Debug)]
struct PathWrapper {
path: PathBuf,
is_directory: bool,
}
impl PathWrapper {
fn from_dir_entry(path: PathBuf, e: DirEntry) -> Self {
let is_directory = e
.file_type()
.ok()
.and_then(|file_type| {
// We need to use fs::metadata to resolve the actual path
// if it's a symlink.
if file_type.is_symlink() {
None
} else {
Some(file_type.is_dir())
}
})
.or_else(|| fs::metadata(&path).map(|m| m.is_dir()).ok())
.unwrap_or(false);
Self { path, is_directory }
}
fn from_path(path: PathBuf) -> Self {
let is_directory = fs::metadata(&path).map(|m| m.is_dir()).unwrap_or(false);
Self { path, is_directory }
}
fn into_path(self) -> PathBuf {
self.path
}
}
impl Deref for PathWrapper {
type Target = Path;
fn deref(&self) -> &Self::Target {
self.path.deref()
}
}
impl AsRef<Path> for PathWrapper {
fn as_ref(&self) -> &Path {
self.path.as_ref()
}
}
/// An alias for a glob iteration result.
///
/// This represents either a matched path or a glob iteration error,
/// such as failing to read a particular directory's contents.
pub type GlobResult = Result<PathBuf, GlobError>;
impl Iterator for Paths {
type Item = GlobResult;
fn next(&mut self) -> Option<GlobResult> {
// the todo buffer hasn't been initialized yet, so it's done at this
// point rather than in glob() so that the errors are unified that is,
// failing to fill the buffer is an iteration error construction of the
// iterator (i.e. glob()) only fails if it fails to compile the Pattern
if let Some(scope) = self.scope.take() {
if !self.dir_patterns.is_empty() {
// Shouldn't happen, but we're using -1 as a special index.
assert!(self.dir_patterns.len() < !0 as usize);
fill_todo(&mut self.todo, &self.dir_patterns, 0, &scope, self.options);
}
}
loop {
if self.dir_patterns.is_empty() || self.todo.is_empty() {
return None;
}
let (path, mut idx) = match self.todo.pop().unwrap() {
Ok(pair) => pair,
Err(e) => return Some(Err(e)),
};
// idx -1: was already checked by fill_todo, maybe path was '.' or
// '..' that we can't match here because of normalization.
if idx == !0 as usize {
if self.require_dir && !path.is_directory {
continue;
}
return Some(Ok(path.into_path()));
}
if self.dir_patterns[idx].is_recursive {
let mut next = idx;
// collapse consecutive recursive patterns
while (next + 1) < self.dir_patterns.len()
&& self.dir_patterns[next + 1].is_recursive
{
next += 1;
}
if path.is_directory {
// the path is a directory, so it's a match
// push this directory's contents
fill_todo(
&mut self.todo,
&self.dir_patterns,
next,
&path,
self.options,
);
if next == self.dir_patterns.len() - 1 {
// pattern ends in recursive pattern, so return this
// directory as a result
return Some(Ok(path.into_path()));
} else {
// advanced to the next pattern for this path
idx = next + 1;
}
} else if next == self.dir_patterns.len() - 1 {
// not a directory and it's the last pattern, meaning no
// match
continue;
} else {
// advanced to the next pattern for this path
idx = next + 1;
}
}
// not recursive, so match normally
if self.dir_patterns[idx].matches_with(
{
match path.file_name().and_then(|s| s.to_str()) {
// FIXME (#9639): How do we handle non-utf8 filenames?
// Ignore them for now; ideally we'd still match them
// against a *
None => continue,
Some(x) => x,
}
},
self.options,
) {
if idx == self.dir_patterns.len() - 1 {
// it is not possible for a pattern to match a directory
// *AND* its children so we don't need to check the
// children
if !self.require_dir || path.is_directory {
return Some(Ok(path.into_path()));
}
} else {
fill_todo(
&mut self.todo,
&self.dir_patterns,
idx + 1,
&path,
self.options,
);
}
}
}
}
}
/// A pattern parsing error.
#[derive(Debug)]
#[allow(missing_copy_implementations)]
pub struct PatternError {
/// The approximate character index of where the error occurred.
pub pos: usize,
/// A message describing the error.
pub msg: &'static str,
}
impl Error for PatternError {
fn description(&self) -> &str {
self.msg
}
}
impl fmt::Display for PatternError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Pattern syntax error near position {}: {}",
self.pos, self.msg
)
}
}
/// A compiled Unix shell style pattern.
///
/// - `?` matches any single character.
///
/// - `*` matches any (possibly empty) sequence of characters.
///
/// - `**` matches the current directory and arbitrary
/// subdirectories. To match files in arbitrary subdiretories, use
/// `**/*`.
///
/// This sequence **must** form a single path component, so both
/// `**a` and `b**` are invalid and will result in an error. A
/// sequence of more than two consecutive `*` characters is also
/// invalid.
///
/// - `[...]` matches any character inside the brackets. Character sequences
/// can also specify ranges of characters, as ordered by Unicode, so e.g.
/// `[0-9]` specifies any character between 0 and 9 inclusive. An unclosed
/// bracket is invalid.
///
/// - `[!...]` is the negation of `[...]`, i.e. it matches any characters
/// **not** in the brackets.
///
/// - The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets
/// (e.g. `[?]`). When a `]` occurs immediately following `[` or `[!` then it
/// is interpreted as being part of, rather then ending, the character set, so
/// `]` and NOT `]` can be matched by `[]]` and `[!]]` respectively. The `-`
/// character can be specified inside a character sequence pattern by placing
/// it at the start or the end, e.g. `[abc-]`.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub struct Pattern {
original: String,
tokens: Vec<PatternToken>,
is_recursive: bool,
}
/// Show the original glob pattern.
impl fmt::Display for Pattern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.original.fmt(f)
}
}
impl FromStr for Pattern {
type Err = PatternError;
fn from_str(s: &str) -> Result<Self, PatternError> {
Self::new(s)
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
enum PatternToken {
Char(char),
AnyChar,
AnySequence,
AnyRecursiveSequence,
AnyWithin(Vec<CharSpecifier>),
AnyExcept(Vec<CharSpecifier>),
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
enum CharSpecifier {
SingleChar(char),
CharRange(char, char),
}
#[derive(Copy, Clone, PartialEq)]
enum MatchResult {
Match,
SubPatternDoesntMatch,
EntirePatternDoesntMatch,
}
const ERROR_WILDCARDS: &str = "wildcards are either regular `*` or recursive `**`";
const ERROR_RECURSIVE_WILDCARDS: &str = "recursive wildcards must form a single path \
component";
const ERROR_INVALID_RANGE: &str = "invalid range pattern";
impl Pattern {
/// This function compiles Unix shell style patterns.
///
/// An invalid glob pattern will yield a `PatternError`.
pub fn new(pattern: &str) -> Result<Self, PatternError> {
let chars = pattern.chars().collect::<Vec<_>>();
let mut tokens = Vec::new();
let mut is_recursive = false;
let mut i = 0;
while i < chars.len() {
match chars[i] {
'?' => {
tokens.push(AnyChar);
i += 1;
}
'*' => {
let old = i;
while i < chars.len() && chars[i] == '*' {
i += 1;
}
let count = i - old;
if count > 2 {
return Err(PatternError {
pos: old + 2,
msg: ERROR_WILDCARDS,
});
} else if count == 2 {
// ** can only be an entire path component
// i.e. a/**/b is valid, but a**/b or a/**b is not
// invalid matches are treated literally
let is_valid = if i == 2 || path::is_separator(chars[i - count - 1]) {
// it ends in a '/'
if i < chars.len() && path::is_separator(chars[i]) {
i += 1;
true
// or the pattern ends here
// this enables the existing globbing mechanism
} else if i == chars.len() {
true
// `**` ends in non-separator
} else {
return Err(PatternError {
pos: i,
msg: ERROR_RECURSIVE_WILDCARDS,
});
}
// `**` begins with non-separator
} else {
return Err(PatternError {
pos: old - 1,
msg: ERROR_RECURSIVE_WILDCARDS,
});
};
if is_valid {
// collapse consecutive AnyRecursiveSequence to a
// single one
let tokens_len = tokens.len();
if !(tokens_len > 1 && tokens[tokens_len - 1] == AnyRecursiveSequence) {
is_recursive = true;
tokens.push(AnyRecursiveSequence);
}
}
} else {
tokens.push(AnySequence);
}
}
'[' => {
if i + 4 <= chars.len() && chars[i + 1] == '!' {
match chars[i + 3..].iter().position(|x| *x == ']') {
None => (),
Some(j) => {
let chars = &chars[i + 2..i + 3 + j];
let cs = parse_char_specifiers(chars);
tokens.push(AnyExcept(cs));
i += j + 4;
continue;
}
}
} else if i + 3 <= chars.len() && chars[i + 1] != '!' {
match chars[i + 2..].iter().position(|x| *x == ']') {
None => (),
Some(j) => {
let cs = parse_char_specifiers(&chars[i + 1..i + 2 + j]);
tokens.push(AnyWithin(cs));
i += j + 3;
continue;
}
}
}
// if we get here then this is not a valid range pattern
return Err(PatternError {
pos: i,
msg: ERROR_INVALID_RANGE,
});
}
c => {
tokens.push(Char(c));
i += 1;
}
}
}
Ok(Self {
tokens,
original: pattern.to_string(),
is_recursive,
})
}
/// Escape metacharacters within the given string by surrounding them in
/// brackets. The resulting string will, when compiled into a `Pattern`,
/// match the input string and nothing else.
pub fn escape(s: &str) -> String {
let mut escaped = String::new();
for c in s.chars() {
match c {
// note that ! does not need escaping because it is only special
// inside brackets
'?' | '*' | '[' | ']' => {
escaped.push('[');
escaped.push(c);
escaped.push(']');
}
c => {
escaped.push(c);
}
}
}
escaped
}
/// Return if the given `str` matches this `Pattern` using the default
/// match options (i.e. `MatchOptions::new()`).
///
/// # Examples
///
/// ```rust
/// use glob::Pattern;
///
/// assert!(Pattern::new("c?t").unwrap().matches("cat"));
/// assert!(Pattern::new("k[!e]tteh").unwrap().matches("kitteh"));
/// assert!(Pattern::new("d*g").unwrap().matches("doog"));
/// ```
pub fn matches(&self, str: &str) -> bool {
self.matches_with(str, MatchOptions::new())
}
/// Return if the given `Path`, when converted to a `str`, matches this
/// `Pattern` using the default match options (i.e. `MatchOptions::new()`).
pub fn matches_path(&self, path: &Path) -> bool {
// FIXME (#9639): This needs to handle non-utf8 paths
path.to_str().map_or(false, |s| self.matches(s))
}
/// Return if the given `str` matches this `Pattern` using the specified
/// match options.
pub fn matches_with(&self, str: &str, options: MatchOptions) -> bool {
self.matches_from(true, str.chars(), 0, options) == Match
}
/// Return if the given `Path`, when converted to a `str`, matches this
/// `Pattern` using the specified match options.
pub fn matches_path_with(&self, path: &Path, options: MatchOptions) -> bool {
// FIXME (#9639): This needs to handle non-utf8 paths
path.to_str()
.map_or(false, |s| self.matches_with(s, options))
}
/// Access the original glob pattern.
pub fn as_str(&self) -> &str {
&self.original
}
fn matches_from(
&self,
mut follows_separator: bool,
mut file: std::str::Chars,
i: usize,
options: MatchOptions,
) -> MatchResult {
for (ti, token) in self.tokens[i..].iter().enumerate() {
match *token {
AnySequence | AnyRecursiveSequence => {
// ** must be at the start.
debug_assert!(match *token {
AnyRecursiveSequence => follows_separator,
_ => true,
});
// Empty match
match self.matches_from(follows_separator, file.clone(), i + ti + 1, options) {
SubPatternDoesntMatch => (), // keep trying
m => return m,
};
while let Some(c) = file.next() {
if follows_separator && options.require_literal_leading_dot && c == '.' {
return SubPatternDoesntMatch;
}
follows_separator = path::is_separator(c);
match *token {
AnyRecursiveSequence if !follows_separator => continue,
AnySequence
if options.require_literal_separator && follows_separator =>
{
return SubPatternDoesntMatch
}
_ => (),
}
match self.matches_from(
follows_separator,
file.clone(),
i + ti + 1,
options,
) {
SubPatternDoesntMatch => (), // keep trying
m => return m,
}
}
}
_ => {
let c = match file.next() {
Some(c) => c,
None => return EntirePatternDoesntMatch,
};
let is_sep = path::is_separator(c);
if !match *token {
AnyChar | AnyWithin(..) | AnyExcept(..)
if (options.require_literal_separator && is_sep)
|| (follows_separator
&& options.require_literal_leading_dot
&& c == '.') =>
{
false
}
AnyChar => true,
AnyWithin(ref specifiers) => in_char_specifiers(&specifiers, c, options),
AnyExcept(ref specifiers) => !in_char_specifiers(&specifiers, c, options),
Char(c2) => chars_eq(c, c2, options.case_sensitive),
AnySequence | AnyRecursiveSequence => unreachable!(),
} {
return SubPatternDoesntMatch;
}
follows_separator = is_sep;
}
}
}
// Iter is fused.
if file.next().is_none() {
Match
} else {
SubPatternDoesntMatch
}
}
}
// Fills `todo` with paths under `path` to be matched by `patterns[idx]`,
// special-casing patterns to match `.` and `..`, and avoiding `readdir()`
// calls when there are no metacharacters in the pattern.
fn fill_todo(
todo: &mut Vec<Result<(PathWrapper, usize), GlobError>>,
patterns: &[Pattern],
idx: usize,
path: &PathWrapper,
options: MatchOptions,
) {
// convert a pattern that's just many Char(_) to a string
fn pattern_as_str(pattern: &Pattern) -> Option<String> {
let mut s = String::new();
for token in &pattern.tokens {
match *token {
Char(c) => s.push(c),
_ => return None,
}
}
Some(s)
}
let add = |todo: &mut Vec<_>, next_path: PathWrapper| {
if idx + 1 == patterns.len() {
// We know it's good, so don't make the iterator match this path
// against the pattern again. In particular, it can't match
// . or .. globs since these never show up as path components.
todo.push(Ok((next_path, !0 as usize)));
} else {
fill_todo(todo, patterns, idx + 1, &next_path, options);
}
};
let pattern = &patterns[idx];
let is_dir = path.is_directory;
let curdir = path.as_ref() == Path::new(".");
match pattern_as_str(pattern) {
Some(s) => {
// This pattern component doesn't have any metacharacters, so we
// don't need to read the current directory to know where to
// continue. So instead of passing control back to the iterator,
// we can just check for that one entry and potentially recurse
// right away.
let special = "." == s || ".." == s;
let next_path = if curdir {
PathBuf::from(s)
} else {
path.join(&s)
};
let next_path = PathWrapper::from_path(next_path);
if (special && is_dir)
|| (!special
&& (fs::metadata(&next_path).is_ok()
|| fs::symlink_metadata(&next_path).is_ok()))
{
add(todo, next_path);
}
}
None if is_dir => {
let dirs = fs::read_dir(path).and_then(|d| {
d.map(|e| {
e.map(|e| {
let path = if curdir {
PathBuf::from(e.path().file_name().unwrap())
} else {
e.path()
};
PathWrapper::from_dir_entry(path, e)
})
})
.collect::<Result<Vec<_>, _>>()
});
match dirs {
Ok(mut children) => {
if options.require_literal_leading_dot {
children
.retain(|x| !x.file_name().unwrap().to_str().unwrap().starts_with("."));
}
children.sort_by(|p1, p2| p2.file_name().cmp(&p1.file_name()));
todo.extend(children.into_iter().map(|x| Ok((x, idx))));
// Matching the special directory entries . and .. that
// refer to the current and parent directory respectively
// requires that the pattern has a leading dot, even if the
// `MatchOptions` field `require_literal_leading_dot` is not
// set.
if !pattern.tokens.is_empty() && pattern.tokens[0] == Char('.') {
for &special in &[".", ".."] {
if pattern.matches_with(special, options) {
add(todo, PathWrapper::from_path(path.join(special)));
}
}
}
}
Err(e) => {
todo.push(Err(GlobError {
path: path.to_path_buf(),
error: e,
}));
}
}
}
None => {
// not a directory, nothing more to find
}
}
}
fn parse_char_specifiers(s: &[char]) -> Vec<CharSpecifier> {
let mut cs = Vec::new();
let mut i = 0;
while i < s.len() {
if i + 3 <= s.len() && s[i + 1] == '-' {
cs.push(CharRange(s[i], s[i + 2]));
i += 3;
} else {
cs.push(SingleChar(s[i]));
i += 1;
}
}
cs
}
fn in_char_specifiers(specifiers: &[CharSpecifier], c: char, options: MatchOptions) -> bool {
for &specifier in specifiers.iter() {
match specifier {
SingleChar(sc) => {
if chars_eq(c, sc, options.case_sensitive) {
return true;
}
}
CharRange(start, end) => {
// FIXME: work with non-ascii chars properly (issue #1347)