Skip to main content

debian_copyright/
glob.rs

1/// An invalid DEP-5 glob pattern.
2///
3/// The only way a pattern can be invalid is a backslash that does not escape
4/// `*`, `?` or `\`, including a backslash at the end of the pattern.
5#[derive(Clone, PartialEq, Eq, Debug)]
6pub struct GlobError {
7    pattern: String,
8    /// The escaped character, or `None` for a trailing backslash.
9    escape: Option<char>,
10}
11
12impl GlobError {
13    /// The pattern that failed to compile.
14    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/// A compiled DEP-5 glob pattern that can efficiently match many paths.
35///
36/// The pattern uses the glob syntax defined by the DEP-5 specification:
37/// `*` matches any sequence of characters, `?` matches a single character,
38/// and backslash escapes `*`, `?` and `\`.
39///
40/// # Examples
41///
42/// ```
43/// let pat = debian_copyright::GlobPattern::try_new("src/*.rs").unwrap();
44/// assert!(pat.is_match("src/main.rs"));
45/// assert!(!pat.is_match("lib/main.rs"));
46/// ```
47#[derive(Clone, Debug)]
48pub struct GlobPattern {
49    regex: regex::Regex,
50    pattern: String,
51}
52
53impl GlobPattern {
54    /// Compile a DEP-5 glob pattern.
55    ///
56    /// # Panics
57    ///
58    /// Panics if the pattern contains an invalid escape sequence. Patterns
59    /// read from copyright files are arbitrary input, so prefer
60    /// [`try_new`](Self::try_new).
61    #[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    /// Compile a DEP-5 glob pattern, reporting an invalid escape sequence.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// let pat = debian_copyright::GlobPattern::try_new(r"\*.txt").unwrap();
72    /// assert!(pat.is_match("*.txt"));
73    /// assert!(debian_copyright::GlobPattern::try_new(r"\x").is_err());
74    /// ```
75    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    /// Check whether a path matches this pattern.
83    pub fn is_match(&self, path: &str) -> bool {
84        self.regex.is_match(path)
85    }
86
87    /// Check whether a path matches this pattern.
88    ///
89    /// Returns `false` for a path that is not valid UTF-8, since DEP-5
90    /// patterns cannot name one.
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// use std::path::Path;
96    /// let pat = debian_copyright::GlobPattern::try_new("src/*.rs").unwrap();
97    /// assert!(pat.is_match_path(Path::new("src/main.rs")));
98    /// ```
99    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    /// The glob pattern this matcher was compiled from.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// let pat = debian_copyright::GlobPattern::try_new("src/*.rs").unwrap();
109    /// assert_eq!(pat.pattern(), "src/*.rs");
110    /// ```
111    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
130/// Whether any of `patterns` matches `path`.
131///
132/// A pattern that is not a valid glob, and a path that is not valid UTF-8,
133/// match nothing: copyright files and filesystems both hand us arbitrary
134/// input, and a match check is no place to fail. Callers that need to know a
135/// pattern is broken should compile it with [`GlobPattern::try_new`].
136pub(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
145/// Decode a DEP-5 file pattern that names a single literal path.
146///
147/// A pattern is literal when it has no unescaped `*` or `?` wildcard. Escapes
148/// (`\*`, `\?`, `\\`) are resolved to the characters they stand for, so the
149/// returned string is the actual filename the pattern designates. Patterns that
150/// contain a wildcard (and therefore match many paths) return `None`.
151///
152/// # Examples
153///
154/// ```
155/// assert_eq!(debian_copyright::glob::literal_path("src/main.rs").as_deref(), Some("src/main.rs"));
156/// assert_eq!(debian_copyright::glob::literal_path(r"\*.txt").as_deref(), Some("*.txt"));
157/// assert_eq!(debian_copyright::glob::literal_path("src/*.rs"), None);
158/// ```
159///
160/// A malformed trailing or invalid escape returns `None` rather than panicking,
161/// since callers decode arbitrary file contents.
162pub 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
178/// Whether a DEP-5 file pattern contains a wildcard, i.e. can match more than
179/// one path. The inverse of [`literal_path`] returning `Some`.
180pub fn is_glob(pattern: &str) -> bool {
181    literal_path(pattern).is_none()
182}
183
184/// Convert a glob pattern to a regular expression.
185#[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(&regex::escape(&esc.to_string())),
205                Some(x) => return Err(err(Some(x))),
206                None => return Err(err(None)),
207            },
208            c => r.push_str(&regex::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        // A trailing or invalid escape is not a valid literal; return None
422        // rather than panicking on arbitrary input.
423        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}