archaven 1.0.0

A small Rust dependency rule checker for modular architectures.
Documentation
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use std::path::Path;

use globset::{Glob, GlobSet, GlobSetBuilder};

use crate::{
    ArchavenError, Dependency, DependencyGraph, Location, ModulePath, PathPattern, Violation,
    Violations,
};

/// A custom dependency rule set.
pub trait RuleSet {
    /// Checks a graph and returns all violations found by this rule set.
    ///
    /// # Errors
    ///
    /// Returns an error when the rule set configuration is invalid.
    fn check(&self, graph: &DependencyGraph) -> Result<Violations, ArchavenError>;
}

/// Describes dependency access from one path pattern to one or more target patterns.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Access {
    from: String,
    to: Vec<String>,
    reason: Option<String>,
}

impl Access {
    /// Starts an access rule from a source pattern.
    #[must_use]
    pub fn from(pattern: impl Into<String>) -> Self {
        Self {
            from: pattern.into(),
            to: Vec::new(),
            reason: None,
        }
    }

    /// Adds one allowed or denied target pattern.
    #[must_use]
    pub fn to(mut self, pattern: impl Into<String>) -> Self {
        self.to.push(pattern.into());
        self
    }

    /// Adds many allowed or denied target patterns.
    #[must_use]
    pub fn to_any<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.to.extend(patterns.into_iter().map(Into::into));
        self
    }

    /// Adds a human-readable reason used in violation messages.
    #[must_use]
    pub fn because(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    fn compile(&self, rule_name: &str) -> Result<CompiledAccess, ArchavenError> {
        if self.to.is_empty() {
            return Err(ArchavenError::invalid_rule(
                rule_name,
                "access rule must define at least one target pattern",
            ));
        }

        let from = PathPattern::parse(&self.from)?;
        let to = self
            .to
            .iter()
            .map(|pattern| PathPattern::parse(pattern))
            .collect::<Result<Vec<_>, _>>()?;

        Ok(CompiledAccess {
            from,
            to,
            reason: self.reason.clone(),
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct CompiledAccess {
    from: PathPattern,
    to: Vec<PathPattern>,
    reason: Option<String>,
}

impl CompiledAccess {
    fn matches(&self, source: &ModulePath, target: &ModulePath) -> bool {
        self.from.matches(source) && self.to.iter().any(|pattern| pattern.matches(target))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Scope {
    Global,
    Between(String),
    Within(String),
    Directories(String),
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum CompiledScope {
    Global,
    Between(PathPattern),
    Within(PathPattern),
    Directories(DirectoryPattern),
}

/// Neutral dependency rule.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Rule {
    name: String,
    scope: Scope,
    deny_all: bool,
    allows: Vec<Access>,
    denies: Vec<Access>,
    ignored_files: Vec<String>,
    ignore_module_roots: bool,
    allow_only_module_roots: bool,
    reason: Option<String>,
}

impl Rule {
    /// Creates a global rule over absolute module path patterns.
    #[must_use]
    pub fn new() -> Self {
        Self {
            name: "dependency rule".to_owned(),
            scope: Scope::Global,
            deny_all: false,
            allows: Vec::new(),
            denies: Vec::new(),
            ignored_files: Vec::new(),
            ignore_module_roots: false,
            allow_only_module_roots: false,
            reason: None,
        }
    }

    /// Creates a rule for dependencies between different instances of a scope pattern.
    #[must_use]
    pub fn between(scope: impl Into<String>) -> Self {
        Self {
            scope: Scope::Between(scope.into()),
            ..Self::new()
        }
    }

    /// Creates a rule for dependencies inside the same instance of a scope pattern.
    #[must_use]
    pub fn within(scope: impl Into<String>) -> Self {
        Self {
            scope: Scope::Within(scope.into()),
            ..Self::new()
        }
    }

    /// Creates a rule for source directories matching a module path pattern.
    #[must_use]
    pub fn directories(scope: impl Into<String>) -> Self {
        Self {
            name: "directory rule".to_owned(),
            scope: Scope::Directories(scope.into()),
            ..Self::new()
        }
    }

    /// Sets a human-readable rule name.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Denies all dependencies in this rule's scope unless an `allow` matches.
    #[must_use]
    pub fn deny_all(mut self) -> Self {
        self.deny_all = true;
        self
    }

    /// Adds an allowed access exception.
    #[must_use]
    pub fn allow(mut self, access: Access) -> Self {
        self.allows.push(access);
        self
    }

    /// Adds an explicitly denied access pattern.
    #[must_use]
    pub fn deny(mut self, access: Access) -> Self {
        self.denies.push(access);
        self
    }

    /// Ignores dependencies discovered in source files matching the given glob patterns.
    #[must_use]
    pub fn ignore_files<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.ignored_files.extend(
            patterns
                .into_iter()
                .map(|pattern| pattern.as_ref().to_owned()),
        );
        self
    }

    /// Ignores dependencies discovered in Rust module root files.
    ///
    /// Module root files are `mod.rs`, `lib.rs`, and files named after a child
    /// directory such as `orders.rs` for an `orders/` directory.
    #[must_use]
    pub fn ignore_module_roots(mut self) -> Self {
        self.ignore_module_roots = true;
        self
    }

    /// Allows only Rust module root files directly inside matching directories.
    ///
    /// Matching directories may contain `mod.rs`, `lib.rs`, and files named
    /// after child directories such as `orders.rs` for an `orders/` directory.
    #[must_use]
    pub fn allow_only_module_roots(mut self) -> Self {
        self.allow_only_module_roots = true;
        self
    }

    /// Adds a default reason used when no more specific reason is available.
    #[must_use]
    pub fn because(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Checks this rule against an already-built dependency graph.
    ///
    /// # Errors
    ///
    /// Returns an error when the rule contains an invalid pattern.
    pub fn check(&self, graph: &DependencyGraph) -> Result<Violations, ArchavenError> {
        Ok(self.compile()?.check(graph))
    }

    fn compile(&self) -> Result<CompiledRule, ArchavenError> {
        let scope = match &self.scope {
            Scope::Global => CompiledScope::Global,
            Scope::Between(pattern) => CompiledScope::Between(PathPattern::parse(pattern)?),
            Scope::Within(pattern) => CompiledScope::Within(PathPattern::parse(pattern)?),
            Scope::Directories(pattern) => {
                CompiledScope::Directories(DirectoryPattern::parse(&self.name, pattern)?)
            }
        };

        if matches!(self.scope, Scope::Directories(_)) && !self.allow_only_module_roots {
            return Err(ArchavenError::invalid_rule(
                &self.name,
                "directory rule must define a directory policy",
            ));
        }

        if !matches!(self.scope, Scope::Directories(_)) && self.allow_only_module_roots {
            return Err(ArchavenError::invalid_rule(
                &self.name,
                "`allow_only_module_roots` can only be used with `Rule::directories`",
            ));
        }

        let allows = self
            .allows
            .iter()
            .map(|access| access.compile(&self.name))
            .collect::<Result<Vec<_>, _>>()?;
        let denies = self
            .denies
            .iter()
            .map(|access| access.compile(&self.name))
            .collect::<Result<Vec<_>, _>>()?;
        let ignored_files = compile_ignored_files(&self.ignored_files)?;

        Ok(CompiledRule {
            name: self.name.clone(),
            scope,
            deny_all: self.deny_all,
            allows,
            denies,
            ignored_files,
            ignore_module_roots: self.ignore_module_roots,
            allow_only_module_roots: self.allow_only_module_roots,
            reason: self.reason.clone(),
        })
    }
}

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

impl RuleSet for Rule {
    fn check(&self, graph: &DependencyGraph) -> Result<Violations, ArchavenError> {
        Ok(self.compile()?.check(graph))
    }
}

struct CompiledRule {
    name: String,
    scope: CompiledScope,
    deny_all: bool,
    allows: Vec<CompiledAccess>,
    denies: Vec<CompiledAccess>,
    ignored_files: GlobSet,
    ignore_module_roots: bool,
    allow_only_module_roots: bool,
    reason: Option<String>,
}

impl CompiledRule {
    fn check(&self, graph: &DependencyGraph) -> Violations {
        if matches!(self.scope, CompiledScope::Directories(_)) {
            return self.check_directories(graph);
        }

        let mut violations = Violations::new();

        for dependency in graph.dependencies() {
            if self.ignores_dependency_file(graph, dependency.location().file()) {
                continue;
            }

            if let Some(context) = self.context(dependency) {
                if let Some(deny) = self
                    .denies
                    .iter()
                    .find(|access| access.matches(&context.source, &context.target))
                {
                    violations.push(Violation::new(
                        &self.name,
                        self.reason_for_explicit_deny(deny),
                        dependency,
                    ));
                    continue;
                }

                if self.deny_all
                    && !self
                        .allows
                        .iter()
                        .any(|access| access.matches(&context.source, &context.target))
                {
                    violations.push(Violation::new(
                        &self.name,
                        self.reason_for_default_deny(),
                        dependency,
                    ));
                }
            }
        }

        violations
    }

    fn check_directories(&self, graph: &DependencyGraph) -> Violations {
        let mut violations = Violations::new();
        let CompiledScope::Directories(pattern) = &self.scope else {
            return violations;
        };

        if !self.allow_only_module_roots {
            return violations;
        }

        for directory in graph
            .directories()
            .iter()
            .filter(|directory| pattern.matches(directory.module()))
        {
            for file in directory.files() {
                if is_module_root_file(file, directory.child_directories()) {
                    continue;
                }

                let module = module_for_directory_file(directory.module(), file);
                violations.push(Violation::for_file(
                    &self.name,
                    self.reason.clone().unwrap_or_else(|| {
                        "only module root files are allowed in this directory".to_owned()
                    }),
                    module,
                    Location::new(directory.path().join(file)),
                ));
            }
        }

        violations
    }

    fn ignores_dependency_file(&self, graph: &DependencyGraph, file: &Path) -> bool {
        self.ignores_file(file) || (self.ignore_module_roots && is_module_root_path(graph, file))
    }

    fn ignores_file(&self, file: &Path) -> bool {
        let normalized = file.to_string_lossy().replace('\\', "/");

        if self.ignored_files.is_match(normalized.as_str()) {
            return true;
        }

        let trimmed = normalized.trim_start_matches('/');
        let segments = trimmed.split('/').collect::<Vec<_>>();
        (1..segments.len()).any(|start| {
            let suffix = segments[start..].join("/");
            self.ignored_files.is_match(suffix.as_str())
        })
    }

    fn context(&self, dependency: &Dependency) -> Option<EvalContext> {
        match &self.scope {
            CompiledScope::Global => Some(EvalContext {
                source: dependency.source().clone(),
                target: dependency.target().clone(),
            }),
            CompiledScope::Between(pattern) => {
                let source = pattern.match_prefix(dependency.source())?;
                let target = pattern.match_prefix(dependency.target())?;

                (source.matched() != target.matched()).then(|| EvalContext {
                    source: source.remainder().clone(),
                    target: target.remainder().clone(),
                })
            }
            CompiledScope::Within(pattern) => {
                let source = pattern.match_prefix(dependency.source())?;
                let target = pattern.match_prefix(dependency.target())?;

                (source.matched() == target.matched()).then(|| EvalContext {
                    source: source.remainder().clone(),
                    target: target.remainder().clone(),
                })
            }
            CompiledScope::Directories(_) => None,
        }
    }

    fn reason_for_explicit_deny(&self, deny: &CompiledAccess) -> String {
        deny.reason
            .clone()
            .or_else(|| self.reason.clone())
            .unwrap_or_else(|| "dependency is denied by this rule".to_owned())
    }

    fn reason_for_default_deny(&self) -> String {
        if let Some(reason) = &self.reason {
            return reason.clone();
        }

        let reasons = self
            .allows
            .iter()
            .filter_map(|access| access.reason.as_deref())
            .collect::<Vec<_>>();

        if reasons.is_empty() {
            "dependency is not allowed by this rule".to_owned()
        } else {
            format!(
                "dependency is not allowed by this rule; allowed access: {}",
                reasons.join("; ")
            )
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct DirectoryPattern {
    pattern: PathPattern,
}

impl DirectoryPattern {
    fn parse(rule_name: &str, pattern: &str) -> Result<Self, ArchavenError> {
        if pattern
            .split("::")
            .map(str::trim)
            .any(|segment| segment == "**")
        {
            return Err(ArchavenError::invalid_rule(
                rule_name,
                "directory rules do not support `**`",
            ));
        }

        let star_count = pattern
            .split("::")
            .map(str::trim)
            .filter(|segment| *segment == "*")
            .count();

        if star_count == 0 {
            return Err(ArchavenError::invalid_rule(
                rule_name,
                "directory rules support at least one `*` segment",
            ));
        }

        Ok(Self {
            pattern: PathPattern::parse(pattern)?,
        })
    }

    fn matches(&self, path: &ModulePath) -> bool {
        self.pattern.matches(path)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct EvalContext {
    source: ModulePath,
    target: ModulePath,
}

fn compile_ignored_files(patterns: &[String]) -> Result<GlobSet, ArchavenError> {
    let mut builder = GlobSetBuilder::new();

    for pattern in patterns {
        let glob = Glob::new(pattern)
            .map_err(|source| ArchavenError::invalid_pattern(pattern, source.to_string()))?;
        builder.add(glob);
    }

    builder
        .build()
        .map_err(|source| ArchavenError::invalid_pattern(patterns.join(", "), source.to_string()))
}

fn is_module_root_path(graph: &DependencyGraph, file: &Path) -> bool {
    graph.directories().iter().any(|directory| {
        file.parent()
            .is_some_and(|parent| parent == directory.path())
            && file.file_name().is_some_and(|name| {
                is_module_root_file(&name.to_string_lossy(), directory.child_directories())
            })
    })
}

fn is_module_root_file(
    file_name: &str,
    child_directories: &std::collections::BTreeSet<String>,
) -> bool {
    matches!(file_name, "mod.rs" | "lib.rs")
        || file_name
            .strip_suffix(".rs")
            .is_some_and(|stem| child_directories.contains(stem))
}

fn module_for_directory_file(directory: &ModulePath, file_name: &str) -> ModulePath {
    let Some(stem) = file_name.strip_suffix(".rs") else {
        return directory.clone();
    };

    let mut segments = directory.segments().to_vec();
    match stem {
        "mod" | "lib" => {}
        other => segments.push(other.to_owned()),
    }
    ModulePath::from_segments(segments)
}