archunit/common/matching/
pattern.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
use std::error::Error;
use std::fmt;

use regex::{Regex, RegexBuilder};

/// The user-facing syntax from which a [`Pattern`] was compiled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PatternSyntax {
    /// Portable path glob syntax.
    Glob,
    /// Rust [`regex`](https://docs.rs/regex) syntax.
    Regex,
    /// Every character is matched literally.
    Literal,
}

/// Pattern compilation options.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct PatternOptions {
    /// Match ASCII and Unicode letters without regard to case.
    pub case_insensitive: bool,
}

impl PatternOptions {
    /// Creates the default case-sensitive options.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            case_insensitive: false,
        }
    }

    /// Returns options configured for case-sensitive or case-insensitive matching.
    #[must_use]
    pub const fn case_insensitive(mut self, enabled: bool) -> Self {
        self.case_insensitive = enabled;
        self
    }
}

/// A user pattern compiled to the regular-expression substrate used by every matcher.
///
/// Patterns match a complete candidate. Use `**` in a glob or `.*` in a regular expression when a
/// prefix or suffix is intentionally unconstrained.
#[derive(Debug, Clone)]
pub struct Pattern {
    source: String,
    syntax: PatternSyntax,
    regex: Regex,
}

impl Pattern {
    /// Compiles a portable, case-sensitive glob.
    ///
    /// The supported wildcards are `*`, `**`, `?`, character classes such as `[abc]` and `[a-z]`,
    /// and negated character classes such as `[!0-9]`. Backslashes are path separators rather than
    /// escapes so one glob behaves the same on every host OS.
    pub fn glob(glob: impl AsRef<str>) -> Result<Self, PatternError> {
        Self::glob_with(glob, PatternOptions::default())
    }

    /// Compiles a glob with explicit options.
    pub fn glob_with(glob: impl AsRef<str>, options: PatternOptions) -> Result<Self, PatternError> {
        let source = glob.as_ref();
        let normalized = normalize_separators(source);
        if normalized.is_empty() {
            return Err(PatternError::new(source, "glob is empty"));
        }

        let body =
            glob_to_regex(&normalized).map_err(|message| PatternError::new(source, message))?;
        Self::compile(source, PatternSyntax::Glob, &body, options)
    }

    /// Compiles a regular expression with complete-candidate matching.
    pub fn regex(expression: impl AsRef<str>) -> Result<Self, PatternError> {
        Self::regex_with(expression, PatternOptions::default())
    }

    /// Compiles a regular expression with explicit options.
    pub fn regex_with(
        expression: impl AsRef<str>,
        options: PatternOptions,
    ) -> Result<Self, PatternError> {
        let source = expression.as_ref();
        if source.trim().is_empty() {
            return Err(PatternError::new(source, "regular expression is empty"));
        }
        Self::compile(source, PatternSyntax::Regex, source, options)
    }

    /// Compiles a complete literal string, including characters meaningful to globs and regexes.
    pub fn literal(literal: impl AsRef<str>) -> Result<Self, PatternError> {
        Self::literal_with(literal, PatternOptions::default())
    }

    /// Compiles a complete literal string with explicit options.
    pub fn literal_with(
        literal: impl AsRef<str>,
        options: PatternOptions,
    ) -> Result<Self, PatternError> {
        let source = literal.as_ref();
        let normalized = normalize_separators(source);
        if normalized.is_empty() {
            return Err(PatternError::new(source, "literal is empty"));
        }
        Self::compile(
            source,
            PatternSyntax::Literal,
            &regex::escape(&normalized),
            options,
        )
    }

    /// Returns the pattern exactly as the user supplied it.
    #[must_use]
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns whether this pattern originated as a glob or a regular expression.
    #[must_use]
    pub const fn syntax(&self) -> PatternSyntax {
        self.syntax
    }

    /// Returns whether the complete normalized candidate matches.
    #[must_use]
    pub fn matches(&self, candidate: &str) -> bool {
        self.regex.is_match(&normalize_separators(candidate))
    }

    /// Replaces this pattern's match in a normalized candidate.
    ///
    /// Rust `regex` replacement syntax is supported, including `$1` and `${name}` captures. Because
    /// every [`Pattern`] is anchored, a matching replacement always covers the complete candidate.
    #[must_use]
    pub fn replace(&self, candidate: &str, replacement: &str) -> String {
        self.regex
            .replace(&normalize_separators(candidate), replacement)
            .into_owned()
    }

    fn compile(
        source: &str,
        syntax: PatternSyntax,
        body: &str,
        options: PatternOptions,
    ) -> Result<Self, PatternError> {
        let anchored = format!(r"\A(?:{body})\z");
        let regex = RegexBuilder::new(&anchored)
            .case_insensitive(options.case_insensitive)
            .build()
            .map_err(|error| PatternError::new(source, error.to_string()))?;

        Ok(Self {
            source: source.to_owned(),
            syntax,
            regex,
        })
    }
}

impl fmt::Display for Pattern {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "\"{}\"", self.source)
    }
}

/// An invalid glob or regular expression supplied by the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatternError {
    pattern: String,
    message: String,
}

impl PatternError {
    fn new(pattern: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            message: message.into(),
        }
    }

    /// Returns the pattern that could not be compiled.
    #[must_use]
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Returns the compiler's useful reason without the surrounding context.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for PatternError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "invalid pattern \"{}\": {}",
            self.pattern, self.message
        )
    }
}

impl Error for PatternError {}

fn normalize_separators(value: &str) -> String {
    let replaced = value.trim().replace('\\', "/");
    if replaced == "/" {
        return replaced;
    }

    let leading = replaced.starts_with('/');
    let normalized = replaced
        .split('/')
        .filter(|segment| !segment.is_empty())
        .collect::<Vec<_>>()
        .join("/");

    if leading && !normalized.is_empty() {
        format!("/{normalized}")
    } else {
        normalized
    }
}

fn glob_to_regex(glob: &str) -> Result<String, &'static str> {
    let characters = glob.chars().collect::<Vec<_>>();
    let mut expression = String::with_capacity(glob.len() * 2);
    let mut index = 0;

    while index < characters.len() {
        let character = characters[index];

        if character == '/'
            && characters.get(index + 1) == Some(&'*')
            && characters.get(index + 2) == Some(&'*')
        {
            if index + 3 == characters.len() {
                expression.push_str("(?:/.*)?");
                index += 3;
                continue;
            }
            if characters.get(index + 3) == Some(&'/') {
                expression.push_str("/(?:.*/)?");
                index += 4;
                continue;
            }
        }

        match character {
            '*' if characters.get(index + 1) == Some(&'*') => {
                if characters.get(index + 2) == Some(&'/') {
                    expression.push_str("(?:.*/)?");
                    index += 3;
                } else {
                    expression.push_str(".*");
                    index += 2;
                }
            }
            '*' => {
                expression.push_str("[^/]*");
                index += 1;
            }
            '?' => {
                expression.push_str("[^/]");
                index += 1;
            }
            '[' => {
                let (class, next_index) = character_class(&characters, index)?;
                expression.push_str(&class);
                index = next_index;
            }
            value => {
                push_regex_literal(&mut expression, value);
                index += 1;
            }
        }
    }

    Ok(expression)
}

fn character_class(characters: &[char], start: usize) -> Result<(String, usize), &'static str> {
    let mut end = start + 1;
    while end < characters.len() && characters[end] != ']' {
        end += 1;
    }
    if end == characters.len() {
        return Err("character class is not closed");
    }
    if end == start + 1 {
        return Err("character class is empty");
    }

    let contents = &characters[start + 1..end];
    let mut class = String::from("[");
    let mut content_index = 0;
    if contents.first() == Some(&'!') {
        class.push('^');
        content_index = 1;
    } else if contents.first() == Some(&'^') {
        class.push_str(r"\^");
        content_index = 1;
    }
    if content_index == contents.len() {
        return Err("character class has no members");
    }

    for character in &contents[content_index..] {
        match character {
            '\\' | ']' => {
                class.push('\\');
                class.push(*character);
            }
            _ => class.push(*character),
        }
    }
    class.push(']');
    Ok((class, end + 1))
}

fn push_regex_literal(expression: &mut String, character: char) {
    if matches!(
        character,
        '.' | '+' | '(' | ')' | '|' | '^' | '$' | '{' | '}' | '\\'
    ) {
        expression.push('\\');
    }
    expression.push(character);
}

#[cfg(test)]
mod tests {
    use super::{Pattern, PatternOptions, PatternSyntax};

    #[test]
    fn matches_glob_wildcards_without_crossing_segments() {
        let pattern = Pattern::glob("src/*/mod?.[rR][sS]").expect("fixture glob should compile");

        assert!(pattern.matches("src/api/mod1.rs"));
        assert!(pattern.matches(r"src\api\modx.RS"));
        assert!(!pattern.matches("src/api/internal/mod1.rs"));
        assert!(!pattern.matches("src/api/mod10.rs"));
    }

    #[test]
    fn double_star_crosses_zero_or_more_segments() {
        let between = Pattern::glob("src/**/handler.rs").expect("fixture glob should compile");
        let suffix = Pattern::glob("src/**").expect("fixture glob should compile");
        let prefix = Pattern::glob("**/handler.rs").expect("fixture glob should compile");

        for candidate in ["src/handler.rs", "src/api/handler.rs", "src/a/b/handler.rs"] {
            assert!(between.matches(candidate), "{candidate} should match");
        }
        for candidate in ["src", "src/api", "src/api/handler.rs"] {
            assert!(suffix.matches(candidate), "{candidate} should match");
        }
        assert!(prefix.matches("handler.rs"));
        assert!(prefix.matches("src/api/handler.rs"));
    }

    #[test]
    fn supports_negated_character_classes() {
        let pattern = Pattern::glob("src/[!0-9]*.rs").expect("fixture glob should compile");

        assert!(pattern.matches("src/handler.rs"));
        assert!(!pattern.matches("src/1handler.rs"));
    }

    #[test]
    fn treats_regex_metacharacters_as_glob_literals() {
        let pattern = Pattern::glob("src/file+(1).rs").expect("fixture glob should compile");

        assert!(pattern.matches("src/file+(1).rs"));
        assert!(!pattern.matches("src/file111.rs"));
    }

    #[test]
    fn anchors_globs_and_regular_expressions() {
        let glob = Pattern::glob("api").expect("fixture glob should compile");
        let regex = Pattern::regex("api").expect("fixture regex should compile");

        assert!(glob.matches("api"));
        assert!(regex.matches("api"));
        assert!(!glob.matches("src/api"));
        assert!(!regex.matches("src/api"));
    }

    #[test]
    fn literal_patterns_escape_every_metacharacter() {
        let pattern =
            Pattern::literal(r"src\handler_v[1]+.rs").expect("fixture literal should compile");

        assert!(pattern.matches("src/handler_v[1]+.rs"));
        assert!(!pattern.matches("src/handler_v1.rs"));
        assert_eq!(pattern.syntax(), PatternSyntax::Literal);
    }

    #[test]
    fn regex_is_the_escape_hatch() {
        let pattern = Pattern::regex(r"src/(api|web)/[a-z_]+\.rs")
            .expect("fixture regular expression should compile");

        assert!(pattern.matches("src/api/handler.rs"));
        assert!(pattern.matches("src/web/router.rs"));
        assert!(!pattern.matches("src/db/repository.rs"));
        assert_eq!(pattern.syntax(), PatternSyntax::Regex);
    }

    #[test]
    fn matching_is_case_sensitive_unless_requested() {
        let strict = Pattern::glob("src/API/**").expect("fixture glob should compile");
        let insensitive =
            Pattern::glob_with("src/API/**", PatternOptions::new().case_insensitive(true))
                .expect("fixture glob should compile");

        assert!(!strict.matches("src/api/handler.rs"));
        assert!(insensitive.matches("src/api/handler.rs"));
    }

    #[test]
    fn retains_the_user_source_for_diagnostics() {
        let pattern = Pattern::glob(r"src\api\**").expect("fixture glob should compile");

        assert_eq!(pattern.source(), r"src\api\**");
        assert_eq!(pattern.to_string(), r#""src\api\**""#);
    }

    #[test]
    fn replaces_complete_normalized_candidates_with_capture_groups() {
        let pattern = Pattern::regex(r"src/([^/]+)/.*\.rs")
            .expect("fixture regular expression should compile");

        assert_eq!(
            pattern.replace(r"src\application\service.rs", "$1"),
            "application"
        );
        assert_eq!(
            pattern.replace("tests/application/service.rs", "$1"),
            "tests/application/service.rs"
        );
    }

    #[test]
    fn reports_invalid_patterns_with_context() {
        let empty = Pattern::glob(" ").expect_err("empty glob should fail");
        let unclosed = Pattern::glob("src/[api").expect_err("unclosed class should fail");
        let regex = Pattern::regex("(").expect_err("invalid regex should fail");

        assert_eq!(empty.pattern(), " ");
        assert!(empty.message().contains("empty"));
        assert!(unclosed.message().contains("not closed"));
        assert!(regex.to_string().contains("invalid pattern \"(\""));
    }
}