archunit/common/matching/
factory.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
use super::{
    Filter, Pattern, PatternError, PatternOptions, PatternSpec, PatternSyntax, PatternTarget,
};

/// Options shared by every matcher produced by a [`RegexFactory`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct RegexFactoryOptions {
    syntax: PatternSyntax,
    case_insensitive: bool,
}

impl RegexFactoryOptions {
    /// Creates case-sensitive glob options.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            syntax: PatternSyntax::Glob,
            case_insensitive: false,
        }
    }

    /// Returns options configured to read user input as `syntax`.
    #[must_use]
    pub const fn syntax(mut self, syntax: PatternSyntax) -> Self {
        self.syntax = syntax;
        self
    }

    /// 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
    }

    /// Returns the selected input syntax.
    #[must_use]
    pub const fn pattern_syntax(self) -> PatternSyntax {
        self.syntax
    }

    /// Returns whether generated matchers ignore letter case.
    #[must_use]
    pub const fn is_case_insensitive(self) -> bool {
        self.case_insensitive
    }
}

impl Default for RegexFactoryOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Compiles user patterns consistently and binds them to selector targets.
///
/// The default factory reads case-sensitive globs. Construct one with [`RegexFactoryOptions`] when
/// a rule family accepts regular expressions or case-insensitive matching.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct RegexFactory {
    options: RegexFactoryOptions,
}

impl RegexFactory {
    /// Creates a factory with explicit compilation options.
    #[must_use]
    pub const fn new(options: RegexFactoryOptions) -> Self {
        Self { options }
    }

    /// Returns this factory's immutable options.
    #[must_use]
    pub const fn options(self) -> RegexFactoryOptions {
        self.options
    }

    /// Compiles one pattern according to this factory's syntax and case behavior.
    pub fn compile(&self, source: impl AsRef<str>) -> Result<Pattern, PatternError> {
        let pattern_options = PatternOptions::new().case_insensitive(self.options.case_insensitive);
        match self.options.syntax {
            PatternSyntax::Glob => Pattern::glob_with(source, pattern_options),
            PatternSyntax::Regex => Pattern::regex_with(source, pattern_options),
            PatternSyntax::Literal => Pattern::literal_with(source, pattern_options),
        }
    }

    /// Matches a pattern against the last path segment.
    pub fn filename_matcher(&self, source: impl Into<PatternSpec>) -> Result<Filter, PatternError> {
        self.matcher(source, PatternTarget::Filename)
    }

    /// Matches a pattern against a file's containing folder.
    pub fn folder_matcher(&self, source: impl Into<PatternSpec>) -> Result<Filter, PatternError> {
        self.matcher(source, PatternTarget::PathWithoutFilename)
    }

    /// Matches a pattern against the complete normalized path.
    pub fn path_matcher(&self, source: impl Into<PatternSpec>) -> Result<Filter, PatternError> {
        self.matcher(source, PatternTarget::Path)
    }

    /// Matches a pattern against an unqualified Rust type name.
    pub fn type_name_matcher(
        &self,
        source: impl Into<PatternSpec>,
    ) -> Result<Filter, PatternError> {
        self.matcher(source, PatternTarget::TypeName)
    }

    /// Matches exactly one normalized file path, treating every character literally.
    pub fn exact_file_matcher(&self, path: impl Into<PatternSpec>) -> Result<Filter, PatternError> {
        let specification = path.into();
        let options = PatternOptions::new().case_insensitive(self.options.case_insensitive);
        let pattern = Pattern::literal_with(specification.source(), options)?;
        self.bind_exclusions(
            Filter::new(pattern, PatternTarget::Path),
            &specification,
            PatternTarget::Path,
        )
    }

    fn matcher(
        &self,
        source: impl Into<PatternSpec>,
        target: PatternTarget,
    ) -> Result<Filter, PatternError> {
        let specification = source.into();
        let pattern = self.compile(specification.source())?;
        self.bind_exclusions(Filter::new(pattern, target), &specification, target)
    }

    fn bind_exclusions(
        &self,
        filter: Filter,
        specification: &PatternSpec,
        parent_target: PatternTarget,
    ) -> Result<Filter, PatternError> {
        let exclusions = specification
            .exclusions()
            .iter()
            .map(|exclusion| {
                self.compile(exclusion.source()).map(|pattern| {
                    Filter::new(pattern, exclusion.target().unwrap_or(parent_target))
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(filter.with_exclusions(exclusions))
    }
}

#[cfg(test)]
mod tests {
    use super::{RegexFactory, RegexFactoryOptions};
    use crate::common::{PatternSyntax, PatternTarget, pattern};

    #[test]
    fn defaults_to_case_sensitive_globs() {
        let factory = RegexFactory::default();
        let filter = factory
            .folder_matcher("crates/api/**")
            .expect("fixture glob should compile");

        assert_eq!(factory.options(), RegexFactoryOptions::new());
        assert_eq!(filter.pattern().syntax(), PatternSyntax::Glob);
        assert!(filter.matches("crates/api/src/handler.rs"));
        assert!(!filter.matches("crates/API/src/handler.rs"));
    }

    #[test]
    fn compiles_every_selector_with_the_expected_target() {
        let factory = RegexFactory::default();
        let cases = [
            (
                factory
                    .filename_matcher("*.rs")
                    .expect("fixture glob should compile"),
                PatternTarget::Filename,
            ),
            (
                factory
                    .folder_matcher("src/**")
                    .expect("fixture glob should compile"),
                PatternTarget::PathWithoutFilename,
            ),
            (
                factory
                    .path_matcher("src/**")
                    .expect("fixture glob should compile"),
                PatternTarget::Path,
            ),
            (
                factory
                    .type_name_matcher("*Handler")
                    .expect("fixture glob should compile"),
                PatternTarget::TypeName,
            ),
        ];

        for (filter, expected_target) in cases {
            assert_eq!(filter.target(), expected_target);
        }
    }

    #[test]
    fn reads_regular_expression_syntax_when_requested() {
        let factory = RegexFactory::new(RegexFactoryOptions::new().syntax(PatternSyntax::Regex));
        let filter = factory
            .filename_matcher(r"handler_v[0-9]+\.rs")
            .expect("fixture regular expression should compile");

        assert!(filter.matches("src/handler_v12.rs"));
        assert!(!filter.matches("src/handler_vX.rs"));
        assert_eq!(filter.pattern().syntax(), PatternSyntax::Regex);
    }

    #[test]
    fn exact_file_matcher_is_literal_in_every_factory_syntax() {
        for factory in [
            RegexFactory::default(),
            RegexFactory::new(RegexFactoryOptions::new().syntax(PatternSyntax::Regex)),
        ] {
            let filter = factory
                .exact_file_matcher(r"src\handler_v[1]+.rs")
                .expect("fixture literal should compile");

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

    #[test]
    fn case_behavior_is_shared_by_pattern_and_literal_matchers() {
        let factory = RegexFactory::new(RegexFactoryOptions::new().case_insensitive(true));

        assert!(
            factory
                .filename_matcher("HANDLER.RS")
                .expect("fixture glob should compile")
                .matches("src/handler.rs")
        );
        assert!(
            factory
                .exact_file_matcher("SRC/HANDLER.RS")
                .expect("fixture literal should compile")
                .matches("src/handler.rs")
        );
    }

    #[test]
    fn reports_invalid_input_from_every_matcher() {
        let factory = RegexFactory::default();

        assert!(factory.filename_matcher("").is_err());
        assert!(factory.folder_matcher("src/[api").is_err());
        assert!(factory.path_matcher("").is_err());
        assert!(factory.type_name_matcher("[Type").is_err());
        assert!(factory.exact_file_matcher(" ").is_err());
    }

    #[test]
    fn compiles_plain_and_targeted_exclusions_with_factory_options() {
        let factory = RegexFactory::new(
            RegexFactoryOptions::new()
                .syntax(PatternSyntax::Regex)
                .case_insensitive(true),
        );
        let filter = factory
            .path_matcher(
                pattern(r"src/.*")
                    .except(r"src/generated/.*")
                    .except_with_name(r".*_generated\.rs"),
            )
            .expect("fixture expressions should compile");

        assert!(filter.matches("SRC/domain/service.rs"));
        assert!(!filter.matches("src/GENERATED/model.rs"));
        assert!(!filter.matches("src/domain/MODEL_GENERATED.RS"));
        assert_eq!(filter.exclusions()[0].target(), PatternTarget::Path);
        assert_eq!(filter.exclusions()[1].target(), PatternTarget::Filename);
        assert_eq!(
            filter.exclusions()[0].pattern().syntax(),
            PatternSyntax::Regex
        );
    }

    #[test]
    fn invalid_exclusions_are_reported_after_a_valid_parent() {
        let error = RegexFactory::default()
            .path_matcher(pattern("src/**").except("src/[generated"))
            .expect_err("invalid exclusion should fail the selector");

        assert_eq!(error.pattern(), "src/[generated");
    }

    #[test]
    fn exact_file_selectors_keep_a_literal_parent_and_glob_exclusions() {
        let filter = RegexFactory::default()
            .exact_file_matcher(pattern("src/model[1].rs").except("src/model*.rs"))
            .expect("literal parent and glob exclusion should compile");

        assert_eq!(filter.pattern().syntax(), PatternSyntax::Literal);
        assert_eq!(
            filter.exclusions()[0].pattern().syntax(),
            PatternSyntax::Glob
        );
        assert!(!filter.matches("src/model[1].rs"));
        assert!(!filter.matches("src/model1.rs"));
    }
}