1#![doc(
61 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
62 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
63 html_root_url = "https://docs.rs/glob/0.3.1"
64)]
65#![deny(missing_docs)]
66
67pub mod dc_glob;
68
69#[cfg(test)]
70#[macro_use]
71extern crate doc_comment;
72
73#[cfg(test)]
74doctest!("../README.md");
75
76use std::cmp;
77use std::cmp::Ordering;
78use std::error::Error;
79use std::fmt;
80use std::fs;
81use std::io;
82use std::path::{self, Component, Path, PathBuf};
83use std::str::FromStr;
84
85use CharSpecifier::{CharRange, SingleChar};
86use MatchResult::{EntirePatternDoesntMatch, Match, SubPatternDoesntMatch};
87use PatternToken::AnyExcept;
88use PatternToken::{AnyChar, AnyRecursiveSequence, AnySequence, AnyWithin, Char};
89
90pub trait Interruptible {
92 fn interrupted(&self) -> bool;
94}
95
96impl<I: Interruptible> Interruptible for &I {
97 #[inline]
98 fn interrupted(&self) -> bool {
99 (*self).interrupted()
100 }
101}
102
103pub struct Uninterruptible;
105
106impl Interruptible for Uninterruptible {
107 #[inline]
108 fn interrupted(&self) -> bool {
109 false
110 }
111}
112
113#[derive(Debug)]
123pub struct Paths<I = Uninterruptible> {
124 dir_patterns: Vec<Pattern>,
125 require_dir: bool,
126 options: MatchOptions,
127 todo: Vec<Result<(PathBuf, usize), GlobError>>,
128 scope: Option<PathBuf>,
129 interrupt: I,
130}
131
132impl Paths<Uninterruptible> {
133 pub fn single(path: &Path, relative_to: &Path) -> Self {
135 Paths {
136 dir_patterns: vec![Pattern::new("*").expect("hard coded pattern")],
137 require_dir: false,
138 options: MatchOptions::default(),
139 todo: vec![Ok((path.to_path_buf(), 0))],
140 scope: Some(relative_to.into()),
141 interrupt: Uninterruptible,
142 }
143 }
144}
145
146pub fn glob<I: Interruptible>(pattern: &str, interrupt: I) -> Result<Paths<I>, PatternError> {
204 glob_with(pattern, MatchOptions::default(), interrupt)
205}
206
207pub fn glob_with<I: Interruptible>(
221 pattern: &str,
222 options: MatchOptions,
223 interrupt: I,
224) -> Result<Paths<I>, PatternError> {
225 #[cfg(windows)]
226 fn check_windows_verbatim(p: &Path) -> bool {
227 match p.components().next() {
228 Some(Component::Prefix(ref p)) => {
229 p.kind().is_verbatim() && !matches!(p.kind(), std::path::Prefix::VerbatimDisk(_))
231 }
232 _ => false,
233 }
234 }
235 #[cfg(not(windows))]
236 fn check_windows_verbatim(_: &Path) -> bool {
237 false
238 }
239
240 #[cfg(windows)]
241 fn to_scope(p: &Path) -> PathBuf {
242 p.to_path_buf()
244 }
245 #[cfg(not(windows))]
246 fn to_scope(p: &Path) -> PathBuf {
247 p.to_path_buf()
248 }
249
250 Pattern::new(pattern)?;
252
253 let mut components = Path::new(pattern).components().peekable();
254 while let Some(&Component::Prefix(..)) | Some(&Component::RootDir) = components.peek() {
255 components.next();
256 }
257
258 let rest = components.map(|s| s.as_os_str()).collect::<PathBuf>();
259 let normalized_pattern = Path::new(pattern).iter().collect::<PathBuf>();
260 let root_len = normalized_pattern
261 .to_str()
262 .expect("internal error: expected string")
263 .len()
264 - rest
265 .to_str()
266 .expect("internal error: expected string")
267 .len();
268 let root = if root_len > 0 {
269 Some(Path::new(&pattern[..root_len]))
270 } else {
271 None
272 };
273
274 if root_len > 0
275 && check_windows_verbatim(root.expect("internal error: already checked for len > 0"))
276 {
277 return Ok(Paths {
281 dir_patterns: Vec::new(),
282 require_dir: false,
283 options,
284 todo: Vec::new(),
285 scope: None,
286 interrupt,
287 });
288 }
289
290 let scope = root.map_or_else(|| PathBuf::from("."), to_scope);
291
292 let mut dir_patterns = Vec::new();
293 let components =
294 pattern[cmp::min(root_len, pattern.len())..].split_terminator(path::is_separator);
295
296 for component in components {
297 dir_patterns.push(Pattern::new(component)?);
298 }
299
300 if root_len == pattern.len() {
301 dir_patterns.push(Pattern {
302 original: "".to_string(),
303 tokens: Vec::new(),
304 is_recursive: false,
305 });
306 }
307
308 let last_is_separator = pattern.chars().next_back().map(path::is_separator);
309 let require_dir = last_is_separator == Some(true);
310 let todo = Vec::new();
311
312 Ok(Paths {
313 dir_patterns,
314 require_dir,
315 options,
316 todo,
317 scope: Some(scope),
318 interrupt,
319 })
320}
321
322pub fn glob_with_parent<I: Interruptible>(
330 pattern: &str,
331 options: MatchOptions,
332 parent: &Path,
333 interrupt: I,
334) -> Result<Paths<I>, PatternError> {
335 match glob_with(pattern, options, interrupt) {
336 Ok(mut p) => {
337 p.scope = match p.scope {
338 None => Some(parent.to_path_buf()),
339 Some(s) if &s.to_string_lossy() == "." => Some(parent.to_path_buf()),
340 Some(s) => Some(s),
341 };
342 Ok(p)
343 }
344 Err(e) => Err(e),
345 }
346}
347
348const GLOB_CHARS: &[char] = &['*', '?', '['];
349
350pub fn is_glob(pattern: &str) -> bool {
366 pattern.contains(GLOB_CHARS)
367}
368
369pub fn is_glob_with_backend(pattern: &str) -> bool {
372 if nu_experimental::DC_GLOB.get() {
373 dc_glob::is_glob(pattern)
374 } else {
375 is_glob(pattern)
376 }
377}
378
379pub fn is_glob_component_with_backend(component: &str) -> bool {
383 if nu_experimental::DC_GLOB.get() {
384 dc_glob::is_glob_component(component)
385 } else {
386 is_glob(component)
387 }
388}
389
390pub fn escape_with_backend(pattern: &str) -> String {
393 if nu_experimental::DC_GLOB.get() {
394 dc_glob::escape(pattern)
395 } else {
396 Pattern::escape(pattern)
397 }
398}
399
400#[derive(Debug)]
406pub struct GlobError {
407 path: PathBuf,
408 error: io::Error,
409}
410
411impl GlobError {
412 pub fn path(&self) -> &Path {
414 &self.path
415 }
416
417 pub fn error(&self) -> &io::Error {
419 &self.error
420 }
421
422 pub fn into_error(self) -> io::Error {
424 self.error
425 }
426}
427
428impl Error for GlobError {
429 #[allow(deprecated)]
430 fn description(&self) -> &str {
431 self.error.description()
432 }
433
434 fn cause(&self) -> Option<&dyn Error> {
435 Some(&self.error)
436 }
437}
438
439impl fmt::Display for GlobError {
440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441 write!(
442 f,
443 "attempting to read `{}` resulted in an error: {}",
444 self.path.display(),
445 self.error
446 )
447 }
448}
449
450fn is_dir(p: &Path) -> bool {
451 fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false)
452}
453
454pub type GlobResult = Result<PathBuf, GlobError>;
459
460impl<I: Interruptible> Iterator for Paths<I> {
461 type Item = GlobResult;
462
463 fn next(&mut self) -> Option<GlobResult> {
464 if let Some(scope) = self.scope.take()
469 && !self.dir_patterns.is_empty()
470 {
471 assert!(self.dir_patterns.len() < !0);
473
474 if self.todo.len() != 1 {
476 fill_todo(
477 &mut self.todo,
478 &self.dir_patterns,
479 0,
480 &scope,
481 self.options,
482 &self.interrupt,
483 );
484 }
485 }
486
487 loop {
488 if self.dir_patterns.is_empty() || self.todo.is_empty() {
489 return None;
490 }
491
492 let (path, mut idx) = match self
493 .todo
494 .pop()
495 .expect("internal error: already checked for non-empty")
496 {
497 Ok(pair) => pair,
498 Err(e) => return Some(Err(e)),
499 };
500
501 if idx == !0 {
504 if self.require_dir && !is_dir(&path) {
505 continue;
506 }
507 return Some(Ok(path));
508 }
509
510 if self.dir_patterns[idx].is_recursive {
511 let mut next = idx;
512
513 while (next + 1) < self.dir_patterns.len()
515 && self.dir_patterns[next + 1].is_recursive
516 {
517 next += 1;
518 }
519
520 if is_dir(&path) {
521 if !self.options.recursive_match_hidden_dir
524 && path
525 .file_name()
526 .map(|name| name.to_string_lossy().starts_with('.'))
527 .unwrap_or(false)
528 {
529 continue;
530 }
531
532 fill_todo(
534 &mut self.todo,
535 &self.dir_patterns,
536 next,
537 &path,
538 self.options,
539 &self.interrupt,
540 );
541
542 if next == self.dir_patterns.len() - 1 {
543 return Some(Ok(path));
546 } else {
547 idx = next + 1;
549 }
550 } else if next == self.dir_patterns.len() - 1 {
551 continue;
554 } else {
555 idx = next + 1;
557 }
558 }
559
560 if self.dir_patterns[idx].matches_with(
562 {
563 match path.file_name().and_then(|s| s.to_str()) {
564 None => {
568 println!("warning: get non-utf8 filename {path:?}, ignored.");
569 continue;
570 }
571 Some(x) => x,
572 }
573 },
574 self.options,
575 ) {
576 if idx == self.dir_patterns.len() - 1 {
577 if !self.require_dir || is_dir(&path) {
582 return Some(Ok(path));
583 }
584 } else {
585 fill_todo(
586 &mut self.todo,
587 &self.dir_patterns,
588 idx + 1,
589 &path,
590 self.options,
591 &self.interrupt,
592 );
593 }
594 }
595 }
596 }
597}
598
599#[derive(Debug)]
601pub struct PatternError {
602 pub pos: usize,
604
605 pub msg: &'static str,
607}
608
609impl Error for PatternError {
610 fn description(&self) -> &str {
611 self.msg
612 }
613}
614
615impl fmt::Display for PatternError {
616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617 write!(
618 f,
619 "Pattern syntax error near position {}: {}",
620 self.pos, self.msg
621 )
622 }
623}
624
625#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
651pub struct Pattern {
652 original: String,
653 tokens: Vec<PatternToken>,
654 is_recursive: bool,
655}
656
657impl fmt::Display for Pattern {
659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660 self.original.fmt(f)
661 }
662}
663
664impl FromStr for Pattern {
665 type Err = PatternError;
666
667 fn from_str(s: &str) -> Result<Self, PatternError> {
668 Self::new(s)
669 }
670}
671
672#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
673enum PatternToken {
674 Char(char),
675 AnyChar,
676 AnySequence,
677 AnyRecursiveSequence,
678 AnyWithin(Vec<CharSpecifier>),
679 AnyExcept(Vec<CharSpecifier>),
680}
681
682#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
683enum CharSpecifier {
684 SingleChar(char),
685 CharRange(char, char),
686}
687
688#[derive(Copy, Clone, PartialEq)]
689enum MatchResult {
690 Match,
691 SubPatternDoesntMatch,
692 EntirePatternDoesntMatch,
693}
694
695const ERROR_WILDCARDS: &str = "wildcards are either regular `*` or recursive `**`";
696const ERROR_RECURSIVE_WILDCARDS: &str = "recursive wildcards must form a single path \
697 component";
698const ERROR_INVALID_RANGE: &str = "invalid range pattern";
699
700impl Pattern {
701 pub fn new(pattern: &str) -> Result<Self, PatternError> {
705 let chars = pattern.chars().collect::<Vec<_>>();
706 let mut tokens = Vec::new();
707 let mut is_recursive = false;
708 let mut i = 0;
709
710 while i < chars.len() {
711 match chars[i] {
712 '?' => {
713 tokens.push(AnyChar);
714 i += 1;
715 }
716 '*' => {
717 let old = i;
718
719 while i < chars.len() && chars[i] == '*' {
720 i += 1;
721 }
722
723 let count = i - old;
724
725 match count.cmp(&2) {
726 Ordering::Greater => {
727 return Err(PatternError {
728 pos: old + 2,
729 msg: ERROR_WILDCARDS,
730 });
731 }
732 Ordering::Equal => {
733 let is_valid = if i == 2 || path::is_separator(chars[i - count - 1]) {
737 if i < chars.len() && path::is_separator(chars[i]) {
739 i += 1;
740 true
741 } else if i == chars.len() {
744 true
745 } else {
747 return Err(PatternError {
748 pos: i,
749 msg: ERROR_RECURSIVE_WILDCARDS,
750 });
751 }
752 } else {
754 return Err(PatternError {
755 pos: old - 1,
756 msg: ERROR_RECURSIVE_WILDCARDS,
757 });
758 };
759
760 if is_valid {
761 let tokens_len = tokens.len();
765
766 if !(tokens_len > 1
767 && tokens[tokens_len - 1] == AnyRecursiveSequence)
768 {
769 is_recursive = true;
770 tokens.push(AnyRecursiveSequence);
771 }
772 }
773 }
774 Ordering::Less => {
775 tokens.push(AnySequence);
776 }
777 }
778 }
779 '[' => {
780 if i + 4 <= chars.len() && chars[i + 1] == '!' {
781 match chars[i + 3..].iter().position(|x| *x == ']') {
782 None => (),
783 Some(j) => {
784 let chars = &chars[i + 2..i + 3 + j];
785 let cs = parse_char_specifiers(chars);
786 tokens.push(AnyExcept(cs));
787 i += j + 4;
788 continue;
789 }
790 }
791 } else if i + 3 <= chars.len() && chars[i + 1] != '!' {
792 match chars[i + 2..].iter().position(|x| *x == ']') {
793 None => (),
794 Some(j) => {
795 let cs = parse_char_specifiers(&chars[i + 1..i + 2 + j]);
796 tokens.push(AnyWithin(cs));
797 i += j + 3;
798 continue;
799 }
800 }
801 }
802
803 return Err(PatternError {
805 pos: i,
806 msg: ERROR_INVALID_RANGE,
807 });
808 }
809 c => {
810 tokens.push(Char(c));
811 i += 1;
812 }
813 }
814 }
815
816 Ok(Self {
817 tokens,
818 original: pattern.to_string(),
819 is_recursive,
820 })
821 }
822
823 pub fn escape(s: &str) -> String {
827 let mut escaped = String::new();
828 for c in s.chars() {
829 match c {
830 '?' | '*' | '[' | ']' => {
833 escaped.push('[');
834 escaped.push(c);
835 escaped.push(']');
836 }
837 c => {
838 escaped.push(c);
839 }
840 }
841 }
842 escaped
843 }
844
845 pub fn matches(&self, str: &str) -> bool {
858 self.matches_with(str, MatchOptions::default())
859 }
860
861 pub fn matches_path(&self, path: &Path) -> bool {
864 path.to_str().is_some_and(|s| self.matches(s))
866 }
867
868 pub fn matches_with(&self, str: &str, options: MatchOptions) -> bool {
871 self.matches_from(true, str.chars(), 0, options) == Match
872 }
873
874 pub fn matches_path_with(&self, path: &Path, options: MatchOptions) -> bool {
877 path.to_str().is_some_and(|s| self.matches_with(s, options))
879 }
880
881 pub fn as_str(&self) -> &str {
883 &self.original
884 }
885
886 fn matches_from(
887 &self,
888 mut follows_separator: bool,
889 mut file: std::str::Chars,
890 i: usize,
891 options: MatchOptions,
892 ) -> MatchResult {
893 for (ti, token) in self.tokens[i..].iter().enumerate() {
894 match *token {
895 AnySequence | AnyRecursiveSequence => {
896 debug_assert!(match *token {
898 AnyRecursiveSequence => follows_separator,
899 _ => true,
900 });
901
902 match self.matches_from(follows_separator, file.clone(), i + ti + 1, options) {
904 SubPatternDoesntMatch => (), m => return m,
906 };
907
908 while let Some(c) = file.next() {
909 if follows_separator && options.require_literal_leading_dot && c == '.' {
910 return SubPatternDoesntMatch;
911 }
912 follows_separator = path::is_separator(c);
913 match *token {
914 AnyRecursiveSequence if !follows_separator => continue,
915 AnySequence
916 if options.require_literal_separator && follows_separator =>
917 {
918 return SubPatternDoesntMatch;
919 }
920 _ => (),
921 }
922 match self.matches_from(
923 follows_separator,
924 file.clone(),
925 i + ti + 1,
926 options,
927 ) {
928 SubPatternDoesntMatch => (), m => return m,
930 }
931 }
932 }
933 _ => {
934 let c = match file.next() {
935 Some(c) => c,
936 None => return EntirePatternDoesntMatch,
937 };
938
939 let is_sep = path::is_separator(c);
940
941 if !match *token {
942 AnyChar | AnyWithin(..) | AnyExcept(..)
943 if (options.require_literal_separator && is_sep)
944 || (follows_separator
945 && options.require_literal_leading_dot
946 && c == '.') =>
947 {
948 false
949 }
950 AnyChar => true,
951 AnyWithin(ref specifiers) => in_char_specifiers(specifiers, c, options),
952 AnyExcept(ref specifiers) => !in_char_specifiers(specifiers, c, options),
953 Char(c2) => chars_eq(c, c2, options.case_sensitive),
954 AnySequence | AnyRecursiveSequence => unreachable!(),
955 } {
956 return SubPatternDoesntMatch;
957 }
958 follows_separator = is_sep;
959 }
960 }
961 }
962
963 if file.next().is_none() {
965 Match
966 } else {
967 SubPatternDoesntMatch
968 }
969 }
970}
971
972fn fill_todo(
976 todo: &mut Vec<Result<(PathBuf, usize), GlobError>>,
977 patterns: &[Pattern],
978 idx: usize,
979 path: &Path,
980 options: MatchOptions,
981 interrupt: &impl Interruptible,
982) {
983 fn pattern_as_str(pattern: &Pattern) -> Option<String> {
985 let mut s = String::new();
986 for token in &pattern.tokens {
987 match *token {
988 Char(c) => s.push(c),
989 _ => return None,
990 }
991 }
992
993 Some(s)
994 }
995
996 let add = |todo: &mut Vec<_>, next_path: PathBuf| {
997 if idx + 1 == patterns.len() {
998 todo.push(Ok((next_path, !0)));
1002 } else {
1003 fill_todo(todo, patterns, idx + 1, &next_path, options, interrupt);
1004 }
1005 };
1006
1007 let pattern = &patterns[idx];
1008 let is_dir = is_dir(path);
1009 let curdir = path == Path::new(".");
1010 match pattern_as_str(pattern) {
1011 Some(s) => {
1012 let special = "." == s || ".." == s;
1018 let next_path = if curdir {
1019 PathBuf::from(s)
1020 } else {
1021 path.join(&s)
1022 };
1023 if (special && is_dir)
1024 || (!special
1025 && (fs::metadata(&next_path).is_ok()
1026 || fs::symlink_metadata(&next_path).is_ok()))
1027 {
1028 add(todo, next_path);
1029 }
1030 }
1031 None if is_dir => {
1032 let dirs = fs::read_dir(path).and_then(|d| {
1033 d.map(|e| {
1034 if interrupt.interrupted() {
1035 return Err(io::Error::from(io::ErrorKind::Interrupted));
1036 }
1037 e.map(|e| {
1038 if curdir {
1039 PathBuf::from(
1040 e.path()
1041 .file_name()
1042 .expect("internal error: missing filename"),
1043 )
1044 } else {
1045 e.path()
1046 }
1047 })
1048 })
1049 .collect::<Result<Vec<_>, _>>()
1050 });
1051 match dirs {
1052 Ok(mut children) => {
1053 children.sort_by(|p1, p2| p2.file_name().cmp(&p1.file_name()));
1064 todo.extend(children.into_iter().map(|x| Ok((x, idx))));
1065
1066 if !pattern.tokens.is_empty() && pattern.tokens[0] == Char('.') {
1072 for &special in &[".", ".."] {
1073 if pattern.matches_with(special, options) {
1074 add(todo, path.join(special));
1075 }
1076 }
1077 }
1078 }
1079 Err(e) => {
1080 todo.push(Err(GlobError {
1081 path: path.to_path_buf(),
1082 error: e,
1083 }));
1084 }
1085 }
1086 }
1087 None => {
1088 }
1090 }
1091}
1092
1093fn parse_char_specifiers(s: &[char]) -> Vec<CharSpecifier> {
1094 let mut cs = Vec::new();
1095 let mut i = 0;
1096 while i < s.len() {
1097 if i + 3 <= s.len() && s[i + 1] == '-' {
1098 cs.push(CharRange(s[i], s[i + 2]));
1099 i += 3;
1100 } else {
1101 cs.push(SingleChar(s[i]));
1102 i += 1;
1103 }
1104 }
1105 cs
1106}
1107
1108fn in_char_specifiers(specifiers: &[CharSpecifier], c: char, options: MatchOptions) -> bool {
1109 for &specifier in specifiers.iter() {
1110 match specifier {
1111 SingleChar(sc) => {
1112 if chars_eq(c, sc, options.case_sensitive) {
1113 return true;
1114 }
1115 }
1116 CharRange(start, end) => {
1117 if !options.case_sensitive && c.is_ascii() && start.is_ascii() && end.is_ascii() {
1119 if start.is_ascii_alphabetic() && end.is_ascii_alphabetic() {
1122 let start = start.to_ascii_lowercase();
1123 let end = end.to_ascii_lowercase();
1124 let c = c.to_ascii_lowercase();
1125 if (start..=end).contains(&c) {
1126 return true;
1127 }
1128 }
1129 }
1130
1131 if (start..=end).contains(&c) {
1132 return true;
1133 }
1134 }
1135 }
1136 }
1137
1138 false
1139}
1140
1141fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool {
1143 if cfg!(windows) && path::is_separator(a) && path::is_separator(b) {
1144 true
1145 } else if !case_sensitive && a.is_ascii() && b.is_ascii() {
1146 a.eq_ignore_ascii_case(&b)
1148 } else {
1149 a == b
1150 }
1151}
1152
1153#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1155pub struct MatchOptions {
1156 pub case_sensitive: bool,
1161
1162 pub require_literal_separator: bool,
1166
1167 pub require_literal_leading_dot: bool,
1173
1174 pub recursive_match_hidden_dir: bool,
1177}
1178
1179impl Default for MatchOptions {
1181 fn default() -> Self {
1182 Self {
1183 case_sensitive: true,
1184 require_literal_separator: false,
1185 require_literal_leading_dot: false,
1186 recursive_match_hidden_dir: true,
1187 }
1188 }
1189}
1190
1191#[cfg(test)]
1192mod test {
1193 use crate::{Paths, PatternError, Uninterruptible};
1194
1195 use super::{MatchOptions, Pattern, glob as glob_with_signals};
1196 use std::path::Path;
1197
1198 fn glob(pattern: &str) -> Result<Paths, PatternError> {
1199 glob_with_signals(pattern, Uninterruptible)
1200 }
1201
1202 #[test]
1203 fn test_pattern_from_str() {
1204 assert!("a*b".parse::<Pattern>().unwrap().matches("a_b"));
1205 assert_eq!("a/**b".parse::<Pattern>().unwrap_err().pos, 4);
1206 }
1207
1208 #[test]
1209 fn test_wildcard_errors() {
1210 assert!(Pattern::new("a/**b").unwrap_err().pos == 4);
1211 assert!(Pattern::new("a/bc**").unwrap_err().pos == 3);
1212 assert!(Pattern::new("a/*****").unwrap_err().pos == 4);
1213 assert!(Pattern::new("a/b**c**d").unwrap_err().pos == 2);
1214 assert!(Pattern::new("a**b").unwrap_err().pos == 0);
1215 }
1216
1217 #[test]
1218 fn test_unclosed_bracket_errors() {
1219 assert!(Pattern::new("abc[def").unwrap_err().pos == 3);
1220 assert!(Pattern::new("abc[!def").unwrap_err().pos == 3);
1221 assert!(Pattern::new("abc[").unwrap_err().pos == 3);
1222 assert!(Pattern::new("abc[!").unwrap_err().pos == 3);
1223 assert!(Pattern::new("abc[d").unwrap_err().pos == 3);
1224 assert!(Pattern::new("abc[!d").unwrap_err().pos == 3);
1225 assert!(Pattern::new("abc[]").unwrap_err().pos == 3);
1226 assert!(Pattern::new("abc[!]").unwrap_err().pos == 3);
1227 }
1228
1229 #[test]
1230 fn test_glob_errors() {
1231 assert!(glob("a/**b").err().unwrap().pos == 4);
1232 assert!(glob("abc[def").err().unwrap().pos == 3);
1233 }
1234
1235 #[cfg(all(
1239 unix,
1240 not(target_os = "macos"),
1241 not(target_os = "android"),
1242 not(target_os = "ios")
1243 ))]
1244 #[test]
1245 fn test_iteration_errors() {
1246 use std::io;
1247 let mut iter = glob("/root/*").unwrap();
1248
1249 match std::fs::read_dir("/root/") {
1250 Ok(_) => {}
1252
1253 Err(err) if err.kind() == io::ErrorKind::NotFound => {
1255 assert!(iter.count() == 0);
1256 }
1257
1258 Err(_) => {
1260 let next = iter.next();
1262 assert!(next.is_some());
1263
1264 let err = next.unwrap();
1265 assert!(err.is_err());
1266
1267 let err = err.err().unwrap();
1268 assert!(err.path() == Path::new("/root"));
1269 assert!(err.error().kind() == io::ErrorKind::PermissionDenied);
1270 }
1271 }
1272 }
1273
1274 #[test]
1275 fn test_absolute_pattern() {
1276 assert!(glob("/").unwrap().next().is_some());
1277 assert!(glob("//").unwrap().next().is_some());
1278
1279 assert!(glob("/*").unwrap().next().is_some());
1281
1282 #[cfg(not(windows))]
1283 fn win() {}
1284
1285 #[cfg(windows)]
1286 fn win() {
1287 use std::env::current_dir;
1288 use std::path::Component;
1289
1290 let root_with_device = current_dir()
1292 .ok()
1293 .map(|p| match p.components().next().unwrap() {
1294 Component::Prefix(prefix_component) => {
1295 Path::new(prefix_component.as_os_str()).join("*")
1296 }
1297 _ => panic!("no prefix in this path"),
1298 })
1299 .unwrap();
1300 assert!(
1302 glob(root_with_device.as_os_str().to_str().unwrap())
1303 .unwrap()
1304 .next()
1305 .is_some()
1306 );
1307 }
1308 win()
1309 }
1310
1311 #[test]
1312 fn test_wildcards() {
1313 assert!(Pattern::new("a*b").unwrap().matches("a_b"));
1314 assert!(Pattern::new("a*b*c").unwrap().matches("abc"));
1315 assert!(!Pattern::new("a*b*c").unwrap().matches("abcd"));
1316 assert!(Pattern::new("a*b*c").unwrap().matches("a_b_c"));
1317 assert!(Pattern::new("a*b*c").unwrap().matches("a___b___c"));
1318 assert!(
1319 Pattern::new("abc*abc*abc")
1320 .unwrap()
1321 .matches("abcabcabcabcabcabcabc")
1322 );
1323 assert!(
1324 !Pattern::new("abc*abc*abc")
1325 .unwrap()
1326 .matches("abcabcabcabcabcabcabca")
1327 );
1328 assert!(
1329 Pattern::new("a*a*a*a*a*a*a*a*a")
1330 .unwrap()
1331 .matches("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
1332 );
1333 assert!(Pattern::new("a*b[xyz]c*d").unwrap().matches("abxcdbxcddd"));
1334 }
1335
1336 #[test]
1337 fn test_recursive_wildcards() {
1338 let pat = Pattern::new("some/**/needle.txt").unwrap();
1339 assert!(pat.matches("some/needle.txt"));
1340 assert!(pat.matches("some/one/needle.txt"));
1341 assert!(pat.matches("some/one/two/needle.txt"));
1342 assert!(pat.matches("some/other/needle.txt"));
1343 assert!(!pat.matches("some/other/notthis.txt"));
1344
1345 let pat = Pattern::new("**").unwrap();
1348 assert!(pat.is_recursive);
1349 assert!(pat.matches("abcde"));
1350 assert!(pat.matches(""));
1351 assert!(pat.matches(".asdf"));
1352 assert!(pat.matches("/x/.asdf"));
1353
1354 let pat = Pattern::new("some/**/**/needle.txt").unwrap();
1356 assert!(pat.matches("some/needle.txt"));
1357 assert!(pat.matches("some/one/needle.txt"));
1358 assert!(pat.matches("some/one/two/needle.txt"));
1359 assert!(pat.matches("some/other/needle.txt"));
1360 assert!(!pat.matches("some/other/notthis.txt"));
1361
1362 let pat = Pattern::new("**/test").unwrap();
1364 assert!(pat.matches("one/two/test"));
1365 assert!(pat.matches("one/test"));
1366 assert!(pat.matches("test"));
1367
1368 let pat = Pattern::new("/**/test").unwrap();
1370 assert!(pat.matches("/one/two/test"));
1371 assert!(pat.matches("/one/test"));
1372 assert!(pat.matches("/test"));
1373 assert!(!pat.matches("/one/notthis"));
1374 assert!(!pat.matches("/notthis"));
1375
1376 let pat = Pattern::new("**/.*").unwrap();
1378 assert!(pat.matches(".abc"));
1379 assert!(pat.matches("abc/.abc"));
1380 assert!(!pat.matches("ab.c"));
1381 assert!(!pat.matches("abc/ab.c"));
1382 }
1383
1384 #[test]
1385 fn test_lots_of_files() {
1386 glob("/*/*/*/*").unwrap().nth(10000);
1388 }
1389
1390 #[test]
1391 fn test_range_pattern() {
1392 let pat = Pattern::new("a[0-9]b").unwrap();
1393 for i in 0..10 {
1394 assert!(pat.matches(&format!("a{i}b")), "a{i}b =~ a[0-9]b");
1395 }
1396 assert!(!pat.matches("a_b"));
1397
1398 let pat = Pattern::new("a[!0-9]b").unwrap();
1399 for i in 0..10 {
1400 assert!(!pat.matches(&format!("a{i}b")));
1401 }
1402 assert!(pat.matches("a_b"));
1403
1404 let pats = ["[a-z123]", "[1a-z23]", "[123a-z]"];
1405 for &p in pats.iter() {
1406 let pat = Pattern::new(p).unwrap();
1407 for c in "abcdefghijklmnopqrstuvwxyz".chars() {
1408 assert!(pat.matches(&c.to_string()));
1409 }
1410 for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() {
1411 let options = MatchOptions {
1412 case_sensitive: false,
1413 ..MatchOptions::default()
1414 };
1415 assert!(pat.matches_with(&c.to_string(), options));
1416 }
1417 assert!(pat.matches("1"));
1418 assert!(pat.matches("2"));
1419 assert!(pat.matches("3"));
1420 }
1421
1422 let pats = ["[abc-]", "[-abc]", "[a-c-]"];
1423 for &p in pats.iter() {
1424 let pat = Pattern::new(p).unwrap();
1425 assert!(pat.matches("a"));
1426 assert!(pat.matches("b"));
1427 assert!(pat.matches("c"));
1428 assert!(pat.matches("-"));
1429 assert!(!pat.matches("d"));
1430 }
1431
1432 let pat = Pattern::new("[2-1]").unwrap();
1433 assert!(!pat.matches("1"));
1434 assert!(!pat.matches("2"));
1435
1436 assert!(Pattern::new("[-]").unwrap().matches("-"));
1437 assert!(!Pattern::new("[!-]").unwrap().matches("-"));
1438 }
1439
1440 #[test]
1441 fn test_pattern_matches() {
1442 let txt_pat = Pattern::new("*hello.txt").unwrap();
1443 assert!(txt_pat.matches("hello.txt"));
1444 assert!(txt_pat.matches("gareth_says_hello.txt"));
1445 assert!(txt_pat.matches("some/path/to/hello.txt"));
1446 assert!(txt_pat.matches("some\\path\\to\\hello.txt"));
1447 assert!(txt_pat.matches("/an/absolute/path/to/hello.txt"));
1448 assert!(!txt_pat.matches("hello.txt-and-then-some"));
1449 assert!(!txt_pat.matches("goodbye.txt"));
1450
1451 let dir_pat = Pattern::new("*some/path/to/hello.txt").unwrap();
1452 assert!(dir_pat.matches("some/path/to/hello.txt"));
1453 assert!(dir_pat.matches("a/bigger/some/path/to/hello.txt"));
1454 assert!(!dir_pat.matches("some/path/to/hello.txt-and-then-some"));
1455 assert!(!dir_pat.matches("some/other/path/to/hello.txt"));
1456 }
1457
1458 #[test]
1459 fn test_pattern_escape() {
1460 let s = "_[_]_?_*_!_";
1461 assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_string());
1462 assert!(Pattern::new(&Pattern::escape(s)).unwrap().matches(s));
1463 }
1464
1465 #[test]
1466 fn test_pattern_matches_case_insensitive() {
1467 let pat = Pattern::new("aBcDeFg").unwrap();
1468 let options = MatchOptions {
1469 case_sensitive: false,
1470 require_literal_separator: false,
1471 require_literal_leading_dot: false,
1472 recursive_match_hidden_dir: true,
1473 };
1474
1475 assert!(pat.matches_with("aBcDeFg", options));
1476 assert!(pat.matches_with("abcdefg", options));
1477 assert!(pat.matches_with("ABCDEFG", options));
1478 assert!(pat.matches_with("AbCdEfG", options));
1479 }
1480
1481 #[test]
1482 fn test_pattern_matches_case_insensitive_range() {
1483 let pat_within = Pattern::new("[a]").unwrap();
1484 let pat_except = Pattern::new("[!a]").unwrap();
1485
1486 let options_case_insensitive = MatchOptions {
1487 case_sensitive: false,
1488 require_literal_separator: false,
1489 require_literal_leading_dot: false,
1490 recursive_match_hidden_dir: false,
1491 };
1492 let options_case_sensitive = MatchOptions {
1493 case_sensitive: true,
1494 require_literal_separator: false,
1495 require_literal_leading_dot: false,
1496 recursive_match_hidden_dir: false,
1497 };
1498
1499 assert!(pat_within.matches_with("a", options_case_insensitive));
1500 assert!(pat_within.matches_with("A", options_case_insensitive));
1501 assert!(!pat_within.matches_with("A", options_case_sensitive));
1502
1503 assert!(!pat_except.matches_with("a", options_case_insensitive));
1504 assert!(!pat_except.matches_with("A", options_case_insensitive));
1505 assert!(pat_except.matches_with("A", options_case_sensitive));
1506 }
1507
1508 #[test]
1509 fn test_pattern_matches_require_literal_separator() {
1510 let options_require_literal = MatchOptions {
1511 case_sensitive: true,
1512 require_literal_separator: true,
1513 require_literal_leading_dot: false,
1514 recursive_match_hidden_dir: true,
1515 };
1516 let options_not_require_literal = MatchOptions {
1517 case_sensitive: true,
1518 require_literal_separator: false,
1519 require_literal_leading_dot: false,
1520 recursive_match_hidden_dir: true,
1521 };
1522
1523 assert!(
1524 Pattern::new("abc/def")
1525 .unwrap()
1526 .matches_with("abc/def", options_require_literal)
1527 );
1528 assert!(
1529 !Pattern::new("abc?def")
1530 .unwrap()
1531 .matches_with("abc/def", options_require_literal)
1532 );
1533 assert!(
1534 !Pattern::new("abc*def")
1535 .unwrap()
1536 .matches_with("abc/def", options_require_literal)
1537 );
1538 assert!(
1539 !Pattern::new("abc[/]def")
1540 .unwrap()
1541 .matches_with("abc/def", options_require_literal)
1542 );
1543
1544 assert!(
1545 Pattern::new("abc/def")
1546 .unwrap()
1547 .matches_with("abc/def", options_not_require_literal)
1548 );
1549 assert!(
1550 Pattern::new("abc?def")
1551 .unwrap()
1552 .matches_with("abc/def", options_not_require_literal)
1553 );
1554 assert!(
1555 Pattern::new("abc*def")
1556 .unwrap()
1557 .matches_with("abc/def", options_not_require_literal)
1558 );
1559 assert!(
1560 Pattern::new("abc[/]def")
1561 .unwrap()
1562 .matches_with("abc/def", options_not_require_literal)
1563 );
1564 }
1565
1566 #[test]
1567 fn test_pattern_matches_require_literal_leading_dot() {
1568 let options_require_literal_leading_dot = MatchOptions {
1569 case_sensitive: true,
1570 require_literal_separator: false,
1571 require_literal_leading_dot: true,
1572 recursive_match_hidden_dir: true,
1573 };
1574 let options_not_require_literal_leading_dot = MatchOptions {
1575 case_sensitive: true,
1576 require_literal_separator: false,
1577 require_literal_leading_dot: false,
1578 recursive_match_hidden_dir: true,
1579 };
1580
1581 let f = |options| {
1582 Pattern::new("*.txt")
1583 .unwrap()
1584 .matches_with(".hello.txt", options)
1585 };
1586 assert!(f(options_not_require_literal_leading_dot));
1587 assert!(!f(options_require_literal_leading_dot));
1588
1589 let f = |options| {
1590 Pattern::new(".*.*")
1591 .unwrap()
1592 .matches_with(".hello.txt", options)
1593 };
1594 assert!(f(options_not_require_literal_leading_dot));
1595 assert!(f(options_require_literal_leading_dot));
1596
1597 let f = |options| {
1598 Pattern::new("aaa/bbb/*")
1599 .unwrap()
1600 .matches_with("aaa/bbb/.ccc", options)
1601 };
1602 assert!(f(options_not_require_literal_leading_dot));
1603 assert!(!f(options_require_literal_leading_dot));
1604
1605 let f = |options| {
1606 Pattern::new("aaa/bbb/*")
1607 .unwrap()
1608 .matches_with("aaa/bbb/c.c.c.", options)
1609 };
1610 assert!(f(options_not_require_literal_leading_dot));
1611 assert!(f(options_require_literal_leading_dot));
1612
1613 let f = |options| {
1614 Pattern::new("aaa/bbb/.*")
1615 .unwrap()
1616 .matches_with("aaa/bbb/.ccc", options)
1617 };
1618 assert!(f(options_not_require_literal_leading_dot));
1619 assert!(f(options_require_literal_leading_dot));
1620
1621 let f = |options| {
1622 Pattern::new("aaa/?bbb")
1623 .unwrap()
1624 .matches_with("aaa/.bbb", options)
1625 };
1626 assert!(f(options_not_require_literal_leading_dot));
1627 assert!(!f(options_require_literal_leading_dot));
1628
1629 let f = |options| {
1630 Pattern::new("aaa/[.]bbb")
1631 .unwrap()
1632 .matches_with("aaa/.bbb", options)
1633 };
1634 assert!(f(options_not_require_literal_leading_dot));
1635 assert!(!f(options_require_literal_leading_dot));
1636
1637 let f = |options| Pattern::new("**/*").unwrap().matches_with(".bbb", options);
1638 assert!(f(options_not_require_literal_leading_dot));
1639 assert!(!f(options_require_literal_leading_dot));
1640 }
1641
1642 #[test]
1643 fn test_matches_path() {
1644 assert!(Pattern::new("a/b").unwrap().matches_path(Path::new("a/b")));
1647 }
1648
1649 #[test]
1650 fn test_path_join() {
1651 let pattern = Path::new("one").join(Path::new("**/*.rs"));
1652 assert!(Pattern::new(pattern.to_str().unwrap()).is_ok());
1653 }
1654}