1#[derive(Clone, PartialEq, Eq, Debug)]
6pub struct GlobError {
7 pattern: String,
8 escape: Option<char>,
10}
11
12impl GlobError {
13 pub fn pattern(&self) -> &str {
15 &self.pattern
16 }
17}
18
19impl std::fmt::Display for GlobError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self.escape {
22 Some(c) => write!(
23 f,
24 "invalid escape sequence \\{} in glob pattern {:?}",
25 c, self.pattern
26 ),
27 None => write!(f, "trailing backslash in glob pattern {:?}", self.pattern),
28 }
29 }
30}
31
32impl std::error::Error for GlobError {}
33
34#[derive(Clone, Debug)]
48pub struct GlobPattern {
49 regex: regex::Regex,
50 pattern: String,
51}
52
53impl GlobPattern {
54 #[deprecated(since = "0.1.55", note = "use GlobPattern::try_new instead")]
62 pub fn new(pattern: &str) -> Self {
63 Self::try_new(pattern).unwrap()
64 }
65
66 pub fn try_new(pattern: &str) -> Result<Self, GlobError> {
76 Ok(Self {
77 regex: glob_to_regex_checked(pattern)?,
78 pattern: pattern.to_string(),
79 })
80 }
81
82 pub fn is_match(&self, path: &str) -> bool {
84 self.regex.is_match(path)
85 }
86
87 pub fn is_match_path(&self, path: &std::path::Path) -> bool {
100 path.to_str().is_some_and(|path| self.is_match(path))
101 }
102
103 pub fn pattern(&self) -> &str {
112 &self.pattern
113 }
114}
115
116impl std::fmt::Display for GlobPattern {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.write_str(&self.pattern)
119 }
120}
121
122impl std::str::FromStr for GlobPattern {
123 type Err = GlobError;
124
125 fn from_str(pattern: &str) -> Result<Self, Self::Err> {
126 Self::try_new(pattern)
127 }
128}
129
130pub(crate) fn matches_any<P: AsRef<str>>(patterns: &[P], path: &std::path::Path) -> bool {
137 let Some(path) = path.to_str() else {
138 return false;
139 };
140 patterns.iter().any(|pattern| {
141 GlobPattern::try_new(pattern.as_ref()).is_ok_and(|pattern| pattern.is_match(path))
142 })
143}
144
145pub fn literal_path(pattern: &str) -> Option<String> {
163 let mut out = String::with_capacity(pattern.len());
164 let mut it = pattern.chars();
165 while let Some(c) = it.next() {
166 match c {
167 '*' | '?' => return None,
168 '\\' => match it.next() {
169 Some(esc @ ('*' | '?' | '\\')) => out.push(esc),
170 _ => return None,
171 },
172 c => out.push(c),
173 }
174 }
175 Some(out)
176}
177
178pub fn is_glob(pattern: &str) -> bool {
181 literal_path(pattern).is_none()
182}
183
184#[deprecated(since = "0.1.46", note = "use GlobPattern instead")]
186pub fn glob_to_regex(glob: &str) -> regex::Regex {
187 glob_to_regex_checked(glob).unwrap()
188}
189
190fn glob_to_regex_checked(glob: &str) -> Result<regex::Regex, GlobError> {
191 let err = |escape| GlobError {
192 pattern: glob.to_string(),
193 escape,
194 };
195
196 let mut it = glob.chars();
197 let mut r = "^".to_string();
198
199 while let Some(c) = it.next() {
200 match c {
201 '*' => r.push_str(".*"),
202 '?' => r.push('.'),
203 '\\' => match it.next() {
204 Some(esc @ ('?' | '*' | '\\')) => r.push_str(®ex::escape(&esc.to_string())),
205 Some(x) => return Err(err(Some(x))),
206 None => return Err(err(None)),
207 },
208 c => r.push_str(®ex::escape(&c.to_string())),
209 }
210 }
211
212 r.push('$');
213
214 Ok(regex::Regex::new(r.as_str()).unwrap())
215}
216
217#[cfg(test)]
218#[allow(deprecated)]
219mod tests {
220 #[test]
221 fn test_simple() {
222 let r = super::glob_to_regex("*.rs");
223 assert!(r.is_match("foo.rs"));
224 assert!(r.is_match("bar.rs"));
225 assert!(!r.is_match("foo.rs.bak"));
226 assert!(!r.is_match("foo"));
227 }
228
229 #[test]
230 fn test_single_char() {
231 let r = super::glob_to_regex("?.rs");
232 assert!(r.is_match("a.rs"));
233 assert!(r.is_match("b.rs"));
234 assert!(!r.is_match("foo.rs"));
235 assert!(!r.is_match("foo"));
236 }
237
238 #[test]
239 fn test_escape() {
240 let r = super::glob_to_regex(r"\?.rs");
241 assert!(r.is_match("?.rs"));
242 assert!(!r.is_match("a.rs"));
243 assert!(!r.is_match("b.rs"));
244
245 let r = super::glob_to_regex(r"\*.rs");
246 assert!(r.is_match("*.rs"));
247 assert!(!r.is_match("a.rs"));
248 assert!(!r.is_match("b.rs"));
249
250 let r = super::glob_to_regex(r"\\?.rs");
251 assert!(r.is_match("\\a.rs"));
252 assert!(r.is_match("\\b.rs"));
253 assert!(!r.is_match("a.rs"));
254 }
255
256 #[should_panic]
257 #[test]
258 fn test_invalid_escape() {
259 super::glob_to_regex(r"\x.rs");
260 }
261
262 #[should_panic]
263 #[test]
264 fn test_invalid_escape2() {
265 super::glob_to_regex(r"\");
266 }
267
268 #[test]
269 fn test_glob_pattern_wildcard() {
270 let pat = super::GlobPattern::new("src/*.rs");
271 assert!(pat.is_match("src/main.rs"));
272 assert!(pat.is_match("src/lib.rs"));
273 assert!(!pat.is_match("lib/main.rs"));
274 assert!(!pat.is_match("src/main.rs.bak"));
275 }
276
277 #[test]
278 fn test_glob_pattern_deep_wildcard() {
279 let pat = super::GlobPattern::new("src/*");
280 assert!(pat.is_match("src/foo"));
281 assert!(pat.is_match("src/foo/bar.rs"));
282 assert!(!pat.is_match("lib/foo"));
283 }
284
285 #[test]
286 fn test_glob_pattern_question_mark() {
287 let pat = super::GlobPattern::new("file?.txt");
288 assert!(pat.is_match("file1.txt"));
289 assert!(pat.is_match("fileA.txt"));
290 assert!(!pat.is_match("file10.txt"));
291 assert!(!pat.is_match("file.txt"));
292 }
293
294 #[test]
295 fn test_glob_pattern_literal() {
296 let pat = super::GlobPattern::new("LICENSE");
297 assert!(pat.is_match("LICENSE"));
298 assert!(!pat.is_match("LICENSE.md"));
299 assert!(!pat.is_match("NOLICENSE"));
300 }
301
302 #[test]
303 fn test_glob_pattern_escaped_star() {
304 let pat = super::GlobPattern::new(r"\*.txt");
305 assert!(pat.is_match("*.txt"));
306 assert!(!pat.is_match("foo.txt"));
307 }
308
309 #[test]
310 fn test_glob_pattern_escaped_question() {
311 let pat = super::GlobPattern::new(r"\?.txt");
312 assert!(pat.is_match("?.txt"));
313 assert!(!pat.is_match("a.txt"));
314 }
315
316 #[test]
317 fn test_glob_pattern_escaped_backslash() {
318 let pat = super::GlobPattern::new(r"\\foo");
319 assert!(pat.is_match(r"\foo"));
320 assert!(!pat.is_match("foo"));
321 }
322
323 #[should_panic]
324 #[test]
325 fn test_glob_pattern_invalid_escape() {
326 super::GlobPattern::new(r"\x");
327 }
328
329 #[should_panic]
330 #[test]
331 fn test_glob_pattern_trailing_backslash() {
332 super::GlobPattern::new(r"\");
333 }
334
335 #[test]
336 fn test_glob_pattern_regex_special_chars() {
337 let pat = super::GlobPattern::new("file(1).txt");
338 assert!(pat.is_match("file(1).txt"));
339 assert!(!pat.is_match("file1.txt"));
340 }
341
342 #[test]
343 fn test_try_new_valid() {
344 let pat = super::GlobPattern::try_new(r"src/\*.rs").unwrap();
345 assert!(pat.is_match("src/*.rs"));
346 assert!(!pat.is_match("src/main.rs"));
347 }
348
349 #[test]
350 fn test_try_new_invalid_escape() {
351 let err = super::GlobPattern::try_new(r"foo\x").unwrap_err();
352 assert_eq!(err.pattern(), r"foo\x");
353 assert_eq!(
354 err.to_string(),
355 r#"invalid escape sequence \x in glob pattern "foo\\x""#
356 );
357 }
358
359 #[test]
360 fn test_try_new_trailing_backslash() {
361 let err = super::GlobPattern::try_new(r"foo\").unwrap_err();
362 assert_eq!(
363 err.to_string(),
364 r#"trailing backslash in glob pattern "foo\\""#
365 );
366 }
367
368 #[test]
369 fn test_from_str() {
370 let pat: super::GlobPattern = "src/*.rs".parse().unwrap();
371 assert!(pat.is_match("src/main.rs"));
372 assert!(r"\x".parse::<super::GlobPattern>().is_err());
373 }
374
375 #[test]
376 fn test_display() {
377 let pat = super::GlobPattern::try_new("src/*.rs").unwrap();
378 assert_eq!(pat.to_string(), "src/*.rs");
379 }
380
381 #[test]
382 fn test_is_match_path() {
383 let pat = super::GlobPattern::try_new("src/*.rs").unwrap();
384 assert!(pat.is_match_path(std::path::Path::new("src/main.rs")));
385 assert!(!pat.is_match_path(std::path::Path::new("lib/main.rs")));
386 }
387
388 #[cfg(unix)]
389 #[test]
390 fn test_is_match_path_non_utf8() {
391 use std::os::unix::ffi::OsStrExt;
392 let path = std::path::Path::new(std::ffi::OsStr::from_bytes(b"src/\xff.rs"));
393 let pat = super::GlobPattern::try_new("src/*").unwrap();
394 assert!(!pat.is_match_path(path));
395 }
396
397 #[test]
398 fn test_literal_path_plain() {
399 assert_eq!(
400 super::literal_path("src/main.rs").as_deref(),
401 Some("src/main.rs")
402 );
403 assert_eq!(super::literal_path("LICENSE").as_deref(), Some("LICENSE"));
404 }
405
406 #[test]
407 fn test_literal_path_unescapes() {
408 assert_eq!(super::literal_path(r"\*.txt").as_deref(), Some("*.txt"));
409 assert_eq!(super::literal_path(r"\?.txt").as_deref(), Some("?.txt"));
410 assert_eq!(super::literal_path(r"a\\b").as_deref(), Some(r"a\b"));
411 }
412
413 #[test]
414 fn test_literal_path_rejects_globs() {
415 assert_eq!(super::literal_path("src/*.rs"), None);
416 assert_eq!(super::literal_path("file?.txt"), None);
417 }
418
419 #[test]
420 fn test_literal_path_rejects_invalid_escape() {
421 assert_eq!(super::literal_path(r"foo\"), None);
424 assert_eq!(super::literal_path(r"foo\x"), None);
425 }
426
427 #[test]
428 fn test_is_glob() {
429 assert!(super::is_glob("src/*.rs"));
430 assert!(super::is_glob("file?.txt"));
431 assert!(!super::is_glob("src/main.rs"));
432 assert!(!super::is_glob(r"\*.txt"));
433 }
434}