easement 0.3.0

Architecture quality gate for polyglot codebases
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::components::ComponentMap;
use crate::config::{Config, Listed};
use crate::lang::Target;
use crate::scan::{Dep, slash};
use crate::scope::Scope;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RuleId {
    /// An import between components that `may_depend_on` does not allow.
    Dependency,
    /// An import of a path outside the target component's public API.
    Privacy,
    /// A dependency cycle between components.
    Cycle,
    /// A component uses an external module its rule does not allow.
    External,
    /// A component exceeds a coupling limit.
    Metric,
    /// A file that belongs to no component, in strict mode.
    Orphan,
    /// An import between instances of an isolated component.
    Isolation,
    /// A directory of a component lacks an import or a file the rules require.
    Required,
    /// A file a component's rules forbid.
    File,
    /// A use of a name the rules forbid or the target does not make public.
    Symbol,
    /// An inline suppression that matches no violation.
    UnusedSuppression,
    /// An inline suppression without a reason.
    SuppressionReason,
}

impl RuleId {
    pub fn as_str(self) -> &'static str {
        match self {
            RuleId::Dependency => "dependency",
            RuleId::Privacy => "privacy",
            RuleId::Cycle => "cycle",
            RuleId::External => "external",
            RuleId::Metric => "metric",
            RuleId::Orphan => "orphan",
            RuleId::Isolation => "isolation",
            RuleId::Required => "required",
            RuleId::File => "file",
            RuleId::Symbol => "symbol",
            RuleId::UnusedSuppression => "unused-suppression",
            RuleId::SuppressionReason => "suppression-reason",
        }
    }

    /// Rules that an inline comment can suppress.
    pub const SUPPRESSIBLE: [RuleId; 5] = [
        RuleId::Dependency,
        RuleId::Privacy,
        RuleId::External,
        RuleId::Isolation,
        RuleId::Symbol,
    ];

    pub fn suppressible(s: &str) -> Option<Self> {
        Self::SUPPRESSIBLE.into_iter().find(|r| r.as_str() == s)
    }
}

fn default_rule() -> RuleId {
    RuleId::Dependency
}

#[derive(Debug, Clone, Serialize)]
pub struct Violation {
    pub rule: RuleId,
    pub file: String,
    pub line: usize,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub because: Option<String>,
    pub from: String,
    pub to: String,
    pub target: String,
    pub specifier: String,
    /// Every import behind the violation; diff mode keeps it if any of them changed.
    #[serde(skip)]
    pub evidence: Vec<(String, usize)>,
}

/// Identity of a violation for the baseline: line numbers are left out so that
/// unrelated edits do not invalidate it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Key {
    #[serde(default = "default_rule")]
    pub rule: RuleId,
    pub file: String,
    pub target: String,
    pub from: String,
    pub to: String,
}

impl Violation {
    pub fn key(&self) -> Key {
        Key {
            rule: self.rule,
            file: self.file.clone(),
            target: self.target.clone(),
            from: self.from.clone(),
            to: self.to.clone(),
        }
    }
}

fn is_zero(n: &usize) -> bool {
    *n == 0
}

#[derive(Debug, Default, Serialize)]
pub struct Stats {
    pub files: usize,
    pub internal_deps: usize,
    pub external_deps: usize,
    pub unmapped_files: usize,
    pub suppressed: usize,
    /// Indexers that ran, and indexes taken from the cache instead.
    #[serde(skip_serializing_if = "is_zero")]
    pub indexed: usize,
    #[serde(skip_serializing_if = "is_zero")]
    pub from_cache: usize,
    /// Source files of an indexed language that its indexer did not cover.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub uncovered: Vec<String>,
    /// `--component` and `--scope` of the run, as `component web`, `path src/api`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub limited_to: Vec<String>,
    /// In diff mode: `a -> b` for component dependencies that exist only
    /// because of the changed lines.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub new_dependencies: Vec<String>,
}

/// A name used through an import, with the import resolved.
#[derive(Debug, Clone)]
pub struct SymbolRef {
    pub file: std::path::PathBuf,
    pub line: usize,
    pub specifier: String,
    pub name: String,
    pub target: Target,
}

/// An import between two different components.
#[derive(Debug, Clone)]
pub struct Edge {
    pub from: String,
    pub to: String,
    pub file: String,
    pub line: usize,
}

/// Checks every internal dependency against the dependency and privacy rules.
/// Every violating import is returned, one per line, see [`dedupe`]. The edges
/// between components feed [`cycles`].
pub fn evaluate(
    config: &Config,
    map: &ComponentMap,
    scope: &Scope,
    deps: &[Dep],
) -> (Vec<Violation>, Vec<Edge>, Stats) {
    let mut stats = Stats::default();
    let mut found = Vec::new();
    let mut edges = Vec::new();
    let mut unmapped = BTreeSet::new();
    for dep in deps {
        let file = slash(&dep.file);
        // Violations and edges come from the whole project; the counters follow the scope.
        let counted = scope.contains(map, &file);
        let target = match &dep.target {
            Target::Internal(path) => slash(path),
            Target::External(module) => {
                stats.external_deps += usize::from(counted);
                if let Some(from) = map.component_of(&file)
                    && let Some(problem) = map.external_problem(from, module)
                {
                    found.push(Violation {
                        rule: RuleId::External,
                        evidence: vec![(file.clone(), dep.line)],
                        file,
                        line: dep.line,
                        message: format!("{from} -> external {module} {}", problem.what),
                        because: problem
                            .because
                            .or_else(|| config.reason(from))
                            .map(str::to_string),
                        from: from.to_string(),
                        to: String::new(),
                        target: module.clone(),
                        specifier: dep.specifier.clone(),
                    });
                }
                continue;
            }
        };
        stats.internal_deps += usize::from(counted);
        let Some(from) = map.component_of(&file) else {
            if counted {
                unmapped.insert(file);
            }
            continue;
        };
        let Some(to) = map.component_of(&target) else {
            continue;
        };
        if from == to {
            if let (Some(here), Some(there)) = (map.instance_of(&file), map.instance_of(&target))
                && here != there
            {
                found.push(Violation {
                    rule: RuleId::Isolation,
                    evidence: vec![(file.clone(), dep.line)],
                    file,
                    line: dep.line,
                    message: format!(
                        "{here} -> {there}: instances of {from} must not import each other (imports {})",
                        dep.specifier
                    ),
                    because: config.components[from]
                        .because
                        .clone()
                        .or_else(|| config.reason(from).map(str::to_string)),
                    from: from.to_string(),
                    to: to.to_string(),
                    target,
                    specifier: dep.specifier.clone(),
                });
            }
            continue;
        }
        edges.push(Edge {
            from: from.to_string(),
            to: to.to_string(),
            file: file.clone(),
            line: dep.line,
        });
        let importers = config.components[to].allow_importers.as_deref();
        let (rule, message, because) = if !config.allows(from, to) {
            let how = if config.forbids(from, to) {
                "is forbidden"
            } else {
                "is not allowed"
            };
            (
                RuleId::Dependency,
                format!("{from} -> {to} {how} (imports {})", dep.specifier),
                config
                    .forbid_reason(from, to)
                    .or_else(|| config.reason(from)),
            )
        } else if importers.is_some_and(|list| !list.iter().any(|c| c == from)) {
            (
                RuleId::Dependency,
                format!(
                    "{from} -> {to}: {to} may be imported only from {} (imports {})",
                    importers.unwrap_or_default().join(", "),
                    dep.specifier
                ),
                config.components[to].because.as_deref(),
            )
        } else if !map.is_public(to, &target) {
            (
                RuleId::Privacy,
                format!(
                    "{from} -> {to}: {target} is not in the public API of {to} (imports {})",
                    dep.specifier
                ),
                config.components[to].because.as_deref(),
            )
        } else {
            continue;
        };
        found.push(Violation {
            rule,
            evidence: vec![(file.clone(), dep.line)],
            file,
            line: dep.line,
            message,
            because: because.map(str::to_string),
            from: from.to_string(),
            to: to.to_string(),
            target,
            specifier: dep.specifier.clone(),
        });
    }
    stats.unmapped_files = unmapped.len();
    (found, edges, stats)
}

/// Component dependencies, as `a -> b`, whose every import sits on a line
/// that `changed` accepts: the edges that did not exist before the change.
pub fn new_dependencies(edges: &[Edge], changed: impl Fn(&str, usize) -> bool) -> Vec<String> {
    let mut all_changed: BTreeMap<(&str, &str), bool> = BTreeMap::new();
    for e in edges {
        let entry = all_changed.entry((&e.from, &e.to)).or_insert(true);
        *entry &= changed(&e.file, e.line);
    }
    all_changed
        .into_iter()
        .filter(|(_, new)| *new)
        .map(|((from, to), _)| format!("{from} -> {to}"))
        .collect()
}

/// Dependency cycles between the components covered by `no_cycles`: one
/// violation per strongly connected group, with the shortest cycle through it.
pub fn cycles(config: &Config, edges: &[Edge]) -> Vec<Violation> {
    let covered: Vec<&Edge> = edges
        .iter()
        .filter(|e| config.no_cycles.covers(&e.from) && config.no_cycles.covers(&e.to))
        .collect();
    let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for e in &covered {
        graph.entry(&e.from).or_default().insert(&e.to);
        graph.entry(&e.to).or_default();
    }
    let mut groups: Vec<BTreeSet<&str>> = strongly_connected(&graph)
        .into_iter()
        .filter(|g| g.len() > 1)
        .map(|g| g.into_iter().collect())
        .collect();
    groups.sort();
    groups
        .into_iter()
        .map(|members| {
            let start = *members.first().expect("non-empty group");
            let cycle = shortest_cycle(&graph, &members, start);
            let first = covered
                .iter()
                .filter(|e| e.from == cycle[0] && e.to == cycle[1])
                .min_by(|x, y| (&x.file, x.line).cmp(&(&y.file, y.line)))
                .expect("cycle edge exists");
            let path = cycle.join(" -> ");
            let names: Vec<&str> = members.iter().copied().collect();
            let message = if members.len() == cycle.len() - 1 {
                format!("component dependency cycle: {path}")
            } else {
                format!(
                    "component dependency cycle among {} components: {} (shortest: {path})",
                    members.len(),
                    names.join(", ")
                )
            };
            let mut evidence: Vec<(String, usize)> = covered
                .iter()
                .filter(|e| members.contains(e.from.as_str()) && members.contains(e.to.as_str()))
                .map(|e| (e.file.clone(), e.line))
                .collect();
            evidence.sort();
            Violation {
                rule: RuleId::Cycle,
                file: first.file.clone(),
                line: first.line,
                message,
                because: None,
                // The key of a cycle is its members only, so moving the evidence does not churn the baseline.
                from: names.join(","),
                to: String::new(),
                target: String::new(),
                specifier: String::new(),
                evidence,
            }
        })
        .collect()
}

/// Tarjan's algorithm; component graphs are small, so recursion is fine.
fn strongly_connected<'a>(graph: &BTreeMap<&'a str, BTreeSet<&'a str>>) -> Vec<Vec<&'a str>> {
    #[derive(Default)]
    struct State<'a> {
        index: BTreeMap<&'a str, usize>,
        low: BTreeMap<&'a str, usize>,
        stack: Vec<&'a str>,
        on_stack: BTreeSet<&'a str>,
        groups: Vec<Vec<&'a str>>,
    }
    fn visit<'a>(v: &'a str, graph: &BTreeMap<&'a str, BTreeSet<&'a str>>, s: &mut State<'a>) {
        let i = s.index.len();
        s.index.insert(v, i);
        s.low.insert(v, i);
        s.stack.push(v);
        s.on_stack.insert(v);
        for &w in &graph[v] {
            if !s.index.contains_key(w) {
                visit(w, graph, s);
                let low = s.low[v].min(s.low[w]);
                s.low.insert(v, low);
            } else if s.on_stack.contains(w) {
                let low = s.low[v].min(s.index[w]);
                s.low.insert(v, low);
            }
        }
        if s.low[v] == s.index[v] {
            let mut group = Vec::new();
            while let Some(w) = s.stack.pop() {
                s.on_stack.remove(w);
                group.push(w);
                if w == v {
                    break;
                }
            }
            s.groups.push(group);
        }
    }
    let mut state = State::default();
    for &v in graph.keys() {
        if !state.index.contains_key(v) {
            visit(v, graph, &mut state);
        }
    }
    state.groups
}

/// Shortest path from `start` back to itself inside `members`, breadth-first:
/// `[start, …, start]`.
fn shortest_cycle<'a>(
    graph: &BTreeMap<&'a str, BTreeSet<&'a str>>,
    members: &BTreeSet<&'a str>,
    start: &'a str,
) -> Vec<&'a str> {
    let mut prev: BTreeMap<&str, &str> = BTreeMap::new();
    let mut queue = VecDeque::from([start]);
    while let Some(v) = queue.pop_front() {
        for &w in &graph[v] {
            if !members.contains(w) {
                continue;
            }
            if w == start {
                let mut path = vec![v];
                let mut cur = v;
                while cur != start {
                    cur = prev[cur];
                    path.push(cur);
                }
                path.reverse();
                path.push(start);
                return path;
            }
            if w != start && !prev.contains_key(w) {
                prev.insert(w, v);
                queue.push_back(w);
            }
        }
    }
    unreachable!("a strongly connected group has a cycle through every member")
}

/// Coupling limits: `max_fan_out` counts the components a component depends
/// on, `max_instability` is `out / (in + out)` over the same component edges.
pub fn metrics(config: &Config, edges: &[Edge]) -> Vec<Violation> {
    let mut out: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    let mut incoming: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for e in edges {
        out.entry(&e.from).or_default().insert(&e.to);
        incoming.entry(&e.to).or_default().insert(&e.from);
    }
    let mut found = Vec::new();
    for (name, rule) in &config.rules {
        let Some(targets) = out.get(name.as_str()) else {
            continue;
        };
        let fan_out = targets.len();
        let fan_in = incoming.get(name.as_str()).map_or(0, BTreeSet::len);
        let instability = fan_out as f64 / (fan_in + fan_out) as f64;
        let mut evidence: Vec<(String, usize)> = edges
            .iter()
            .filter(|e| e.from == *name)
            .map(|e| (e.file.clone(), e.line))
            .collect();
        evidence.sort();
        let (file, line) = evidence[0].clone();
        let list = targets.iter().copied().collect::<Vec<_>>().join(", ");
        let mut over = |limit: &str, message: String| {
            found.push(Violation {
                rule: RuleId::Metric,
                file: file.clone(),
                line,
                message,
                because: rule.because.clone(),
                from: name.clone(),
                to: String::new(),
                target: limit.to_string(),
                specifier: String::new(),
                evidence: evidence.clone(),
            });
        };
        if let Some(max) = rule.max_fan_out
            && fan_out > max
        {
            over(
                "max_fan_out",
                format!(
                    "{name} depends on {fan_out} components, more than max_fan_out {max}: {list}"
                ),
            );
        }
        if let Some(max) = rule.max_instability
            && instability > max
        {
            over(
                "max_instability",
                format!(
                    "{name} has instability {instability:.2} ({fan_out} out, {fan_in} in), above max_instability {max}"
                ),
            );
        }
    }
    found
}

/// What a directory of a component imports and holds.
#[derive(Default)]
struct Unit {
    /// Checked files, sorted; the first one carries the violations.
    files: BTreeSet<String>,
    components: BTreeSet<String>,
    external: BTreeSet<String>,
}

/// `must_depend_on`, `must_use_external`, `requires_file` and `requires_directive`: every directory
/// that holds checked files of a component must import what the rule lists and
/// contain the files it names. One violation per directory and missing item.
pub fn required(
    root: &Path,
    config: &Config,
    map: &ComponentMap,
    deps: &[Dep],
    paths: &[String],
    all_files: &[String],
) -> Vec<Violation> {
    let parent = |file: &str| file.rsplit_once('/').map_or("", |(dir, _)| dir).to_string();
    let wanted = |from: &str| {
        config.rules.get(from).is_some_and(|r| {
            !(r.must_depend_on.is_empty()
                && r.must_use_external.is_empty()
                && r.requires_file.is_empty()
                && r.requires_directive.is_empty())
        })
    };
    let mut units: BTreeMap<(String, String), Unit> = BTreeMap::new();
    for file in paths {
        if let Some(component) = map.component_of(file).filter(|c| wanted(c)) {
            units
                .entry((component.to_string(), parent(file)))
                .or_default()
                .files
                .insert(file.clone());
        }
    }
    for dep in deps {
        let file = slash(&dep.file);
        let Some(component) = map.component_of(&file) else {
            continue;
        };
        let Some(unit) = units.get_mut(&(component.to_string(), parent(&file))) else {
            continue;
        };
        match &dep.target {
            Target::Internal(target) => {
                if let Some(to) = map.component_of(&slash(target)) {
                    unit.components.insert(to.to_string());
                }
            }
            Target::External(module) => {
                unit.external.insert(module.clone());
            }
        }
    }
    let mut dir_files: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for file in all_files {
        let (dir, name) = file.rsplit_once('/').unwrap_or(("", file));
        dir_files.entry(dir).or_default().push(name);
    }
    let mut found = Vec::new();
    for ((component, dir), unit) in &units {
        let rule = &config.rules[component];
        let first = unit.files.first().expect("a unit has files").clone();
        let shown = if dir.is_empty() { "." } else { dir };
        let mut missing = |target: String, message: String, wanted: &Listed| {
            found.push(Violation {
                rule: RuleId::Required,
                file: first.clone(),
                line: 1,
                message,
                because: wanted
                    .because()
                    .or(rule.because.as_deref())
                    .map(str::to_string),
                from: component.clone(),
                to: String::new(),
                target,
                specifier: String::new(),
                evidence: vec![(first.clone(), 1)],
            });
        };
        for wanted in &rule.must_depend_on {
            if !unit.components.contains(wanted.name()) {
                missing(
                    format!("import {}", wanted.name()),
                    format!(
                        "{shown} ({component}) must import {}, and no file in it does",
                        wanted.name()
                    ),
                    wanted,
                );
            }
        }
        for wanted in &rule.must_use_external {
            let used = ComponentMap::external_matches(wanted.name(), unit.external.iter());
            if !used {
                missing(
                    format!("external {}", wanted.name()),
                    format!(
                        "{shown} ({component}) must use the external module {}, and no file in it does",
                        wanted.name()
                    ),
                    wanted,
                );
            }
        }
        for wanted in &rule.requires_file {
            let names = dir_files.get(dir.as_str()).map_or(&[][..], Vec::as_slice);
            let present = globset::Glob::new(wanted.name())
                .map(|g| g.compile_matcher())
                .is_ok_and(|m| names.iter().any(|n| m.is_match(n)));
            if !present {
                missing(
                    format!("file {}", wanted.name()),
                    format!(
                        "{shown} ({component}) must contain a file {}",
                        wanted.name()
                    ),
                    wanted,
                );
            }
        }
        for wanted in &rule.requires_directive {
            let Ok(pattern) = regex::Regex::new(wanted.name()) else {
                continue;
            };
            let present = unit.files.iter().any(|file| {
                std::fs::read_to_string(root.join(file)).is_ok_and(|text| pattern.is_match(&text))
            });
            if !present {
                missing(
                    format!("directive {}", wanted.name()),
                    format!(
                        "{shown} ({component}) must contain a comment or text matching `{}`, and no file in it does",
                        wanted.name()
                    ),
                    wanted,
                );
            }
        }
    }
    found
}

/// `forbid_symbol` and `public_symbols`: names used through imports.
pub fn symbols(config: &Config, map: &ComponentMap, uses: &[SymbolRef]) -> Vec<Violation> {
    let mut found = Vec::new();
    for used in uses {
        let file = slash(&used.file);
        let Some(from) = map.component_of(&file) else {
            continue;
        };
        let mut report = |message: String, target: String, to: &str, because: Option<&str>| {
            found.push(Violation {
                rule: RuleId::Symbol,
                evidence: vec![(file.clone(), used.line)],
                file: file.clone(),
                line: used.line,
                message,
                because: because.map(str::to_string),
                from: from.to_string(),
                to: to.to_string(),
                target,
                specifier: used.specifier.clone(),
            });
        };
        if let Some(rule) = config.rules.get(from) {
            for listed in &rule.forbid_symbol {
                if names_symbol(listed.name(), &used.specifier, &used.name) {
                    report(
                        format!("{from} must not use {}", listed.name()),
                        listed.name().to_string(),
                        "",
                        listed.because().or(rule.because.as_deref()),
                    );
                }
            }
        }
        if let Target::Internal(path) = &used.target
            && let Some(to) = map.component_of(&slash(path))
            && to != from
            && let Some(public) = &config.components[to].public_symbols
            && !public.contains(&used.name)
        {
            report(
                format!(
                    "{from} -> {to}: {} is not in the public symbols of {to} ({})",
                    used.name,
                    public.join(", ")
                ),
                format!("{}.{}", used.specifier, used.name),
                to,
                config.components[to].because.as_deref(),
            );
        }
    }
    found
}

/// Whether `pattern` (`pkg.Name` or `import/path.Name`) names the symbol
/// `name` used through the import `specifier`.
fn names_symbol(pattern: &str, specifier: &str, name: &str) -> bool {
    let Some((qualifier, wanted)) = pattern.rsplit_once('.') else {
        return false;
    };
    wanted == name
        && (qualifier == specifier
            || specifier
                .strip_suffix(qualifier)
                .is_some_and(|rest| rest.ends_with('/')))
}

/// `forbid_file`: files of a component whose name or path matches a forbidden glob.
pub fn forbidden_files(config: &Config, map: &ComponentMap, files: &[String]) -> Vec<Violation> {
    let mut found = Vec::new();
    for (component, rule) in &config.rules {
        if rule.forbid_file.is_empty() {
            continue;
        }
        let matchers: Vec<(&Listed, globset::GlobMatcher)> = rule
            .forbid_file
            .iter()
            .filter_map(|l| Some((l, globset::Glob::new(l.name()).ok()?.compile_matcher())))
            .collect();
        for file in files {
            if map.component_of(file) != Some(component.as_str()) {
                continue;
            }
            let name = file.rsplit_once('/').map_or(file.as_str(), |(_, n)| n);
            let Some((listed, _)) = matchers
                .iter()
                .find(|(_, m)| m.is_match(name) || m.is_match(file))
            else {
                continue;
            };
            found.push(Violation {
                rule: RuleId::File,
                file: file.clone(),
                line: 1,
                message: format!(
                    "{component} must not contain {file} (forbid_file {})",
                    listed.name()
                ),
                because: listed
                    .because()
                    .or(rule.because.as_deref())
                    .map(str::to_string),
                from: component.clone(),
                to: String::new(),
                target: file.clone(),
                specifier: String::new(),
                evidence: vec![(file.clone(), 1)],
            });
        }
    }
    found
}

/// In strict mode, every checked file must belong to a component.
pub fn orphans(config: &Config, map: &ComponentMap, files: &[String]) -> Vec<Violation> {
    if !config.strict {
        return Vec::new();
    }
    files
        .iter()
        .filter(|f| map.component_of(f).is_none() && !map.is_unowned(f))
        .map(|file| Violation {
            rule: RuleId::Orphan,
            file: file.clone(),
            line: 1,
            message: "file belongs to no component (strict mode)".to_string(),
            because: None,
            from: String::new(),
            to: String::new(),
            target: file.clone(),
            specifier: String::new(),
            evidence: vec![(file.clone(), 1)],
        })
        .collect()
}

/// One violation per use: the same key at the same line once, every other line
/// kept, sorted by key and line. The baseline still matches by key alone.
pub fn dedupe(violations: Vec<Violation>) -> Vec<Violation> {
    let mut unique: BTreeMap<(Key, usize), Violation> = BTreeMap::new();
    for v in violations {
        unique.entry((v.key(), v.line)).or_insert(v);
    }
    unique.into_values().collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dedupe_keeps_every_line_and_drops_repeats() {
        let at = |line: usize| Violation {
            rule: RuleId::Symbol,
            file: "f".into(),
            line,
            message: String::new(),
            because: None,
            from: "a".into(),
            to: String::new(),
            target: "db.Client".into(),
            specifier: String::new(),
            evidence: Vec::new(),
        };
        let lines: Vec<usize> = dedupe(vec![at(9), at(3), at(9)])
            .iter()
            .map(|v| v.line)
            .collect();
        assert_eq!(lines, [3, 9]);
    }

    fn edge(from: &str, to: &str) -> Edge {
        Edge {
            from: from.into(),
            to: to.into(),
            file: format!("{from}/x"),
            line: 1,
        }
    }

    fn config(no_cycles: &str) -> Config {
        serde_norway::from_str(&format!(
            "version: 1
components:
  a: {{ in: a }}
  b: {{ in: b }}
  c: {{ in: c }}
  d: {{ in: d }}
no_cycles: {no_cycles}
"
        ))
        .unwrap()
    }

    #[test]
    fn reports_each_cycle_group_once_with_shortest_path() {
        let edges = [
            edge("a", "b"),
            edge("b", "c"),
            edge("c", "a"),
            edge("b", "a"),
            edge("c", "d"),
        ];
        let found = cycles(&config("true"), &edges);
        assert_eq!(found.len(), 1);
        assert_eq!(
            found[0].message,
            "component dependency cycle among 3 components: a, b, c (shortest: a -> b -> a)"
        );
        assert_eq!(found[0].from, "a,b,c");
        assert_eq!(found[0].evidence.len(), 4);
    }

    fn limits(rule: &str) -> Config {
        serde_norway::from_str(&format!(
            "version: 1
components:
  a: {{ in: a }}
  b: {{ in: b }}
  c: {{ in: c }}
rules:
  a: {{ {rule} }}
"
        ))
        .unwrap()
    }

    #[test]
    fn metrics_report_fan_out_and_instability() {
        let edges = [edge("a", "b"), edge("a", "c"), edge("b", "a")];
        // a: out 2, in 1 -> instability 0.67
        let found = metrics(&limits("max_fan_out: 1, max_instability: 0.5"), &edges);
        let targets: Vec<_> = found.iter().map(|v| v.target.as_str()).collect();
        assert_eq!(targets, ["max_fan_out", "max_instability"]);
        assert!(found[0].message.contains("depends on 2 components"));
        assert!(found[1].message.contains("instability 0.67"));
        assert!(metrics(&limits("max_fan_out: 2, max_instability: 0.7"), &edges).is_empty());
    }

    #[test]
    fn a_dependency_is_new_only_when_all_its_imports_changed() {
        let edges = [
            Edge {
                line: 1,
                ..edge("a", "b")
            },
            Edge {
                line: 2,
                ..edge("a", "b")
            },
            Edge {
                line: 3,
                ..edge("a", "c")
            },
        ];
        // Line 1 of a/x is old, so a -> b existed before; only a -> c is new.
        let got = new_dependencies(&edges, |_, line| line != 1);
        assert_eq!(got, ["a -> c"]);
    }

    #[test]
    fn orphans_only_in_strict_mode() {
        let yaml = |strict: bool| -> Config {
            serde_norway::from_str(&format!(
                "version: 1\ncomponents:\n  a: {{ in: a }}\nstrict: {strict}\n"
            ))
            .unwrap()
        };
        let files = ["a/x.go".to_string(), "b/y.go".to_string()];
        let strict = yaml(true);
        let map = ComponentMap::new(&strict).unwrap();
        let found = orphans(&strict, &map, &files);
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].file, "b/y.go");
        assert!(orphans(&yaml(false), &map, &files).is_empty());
    }

    #[test]
    fn simple_cycle_and_scoping() {
        let edges = [edge("a", "b"), edge("b", "c"), edge("c", "a")];
        let found = cycles(&config("true"), &edges);
        assert_eq!(
            found[0].message,
            "component dependency cycle: a -> b -> c -> a"
        );
        assert!(cycles(&config("[a, b]"), &edges).is_empty());
        assert!(cycles(&config("false"), &edges).is_empty());
    }
}