Skip to main content

fallow_engine/
diff_scope.rs

1//! Diff line filters shared by every surface that accepts a unified diff.
2//!
3//! The CLI (`--diff-file`, `--diff-stdin` and the CI diff) and the programmatic
4//! API (`analysis.diffFile`) narrow a report to the lines a change added. Both
5//! call the functions in this module, so a finding cannot pass the filter on
6//! one surface and fail it on another.
7
8use std::path::Path;
9
10use fallow_output::DiffIndex;
11use fallow_types::duplicates::{CloneInstance, DuplicationReport};
12use fallow_types::results::{AnalysisResults, SecurityFinding, TraceHopRole};
13
14use crate::result_scope::{
15    Anchor, ComponentRule, OwnerRule, ProjectFinding, ResultScope, SiteRule,
16};
17
18/// Drop the dead-code findings whose source line is not on an added line of
19/// the diff.
20///
21/// Range-shaped findings (clone instances, complexity hotspots) have their own
22/// filters. This filter governs the per-file findings on [`AnalysisResults`].
23/// A finding with no real line (an unused file, a route file, an unzoned file,
24/// a member of a cycle) stays when the diff touches its file.
25///
26/// [`DiffIndex::key_for`] gives the diff key of a finding path, relative to the
27/// base of the diff and not to `root`. When a path has no key (a different
28/// drive, or a path outside the base), the finding stays: a path that the
29/// filter cannot judge is better shown than hidden.
30pub fn filter_dead_code_by_diff(results: &mut AnalysisResults, diff: &DiffIndex, root: &Path) {
31    crate::result_scope::retain_in_scope(results, &DiffLines { diff, root });
32}
33
34/// A unified diff as a result scope.
35struct DiffLines<'a> {
36    diff: &'a DiffIndex,
37    root: &'a Path,
38}
39
40impl DiffLines<'_> {
41    fn touches_file(&self, path: &Path) -> bool {
42        self.diff
43            .key_for(path, self.root)
44            .is_none_or(|rel| self.diff.touches_file(&rel))
45    }
46
47    fn line_in_diff(&self, path: &Path, line: u32) -> bool {
48        self.diff
49            .key_for(path, self.root)
50            .is_none_or(|rel| self.diff.line_is_added(&rel, u64::from(line)))
51    }
52}
53
54impl ResultScope for DiffLines<'_> {
55    fn keeps(&self, anchor: Anchor<'_>) -> bool {
56        match anchor {
57            Anchor::Line { path, line } => self.line_in_diff(path, line),
58            Anchor::File { path } => self.touches_file(path),
59        }
60    }
61
62    /// Project-level findings bypass the filter. A change that deletes the
63    /// last consumer of a package causes the `unused-dependency` finding, even
64    /// when the diff does not touch `package.json`. The same holds for catalog
65    /// entries, dependency overrides, type-only dependencies and test-only
66    /// dependencies. The line filter reduces noise for source-anchored
67    /// findings. CI must still fail on the project-level findings that the
68    /// change caused.
69    fn keeps_project_finding(&self, _finding: ProjectFinding<'_>) -> bool {
70        true
71    }
72
73    fn keeps_security_finding(&self, finding: &SecurityFinding) -> bool {
74        self.line_in_diff(&finding.path, finding.line)
75            || finding.trace.iter().any(|hop| {
76                self.line_in_diff(&hop.path, hop.line)
77                    || (matches!(hop.role, TraceHopRole::SecretSource)
78                        && self.touches_file(&hop.path))
79            })
80            || finding.reachability.as_ref().is_some_and(|reachability| {
81                // Any hop on an added line keeps the finding for display, whatever
82                // its role. Do not add a role check here: unlike the strict
83                // `--gate new` filter of `fallow security`, the display must show a
84                // finding whose module-level source sits on an added line.
85                reachability
86                    .untrusted_source_trace
87                    .iter()
88                    .any(|hop| self.line_in_diff(&hop.path, hop.line))
89            })
90    }
91
92    fn site_rule(&self) -> SiteRule {
93        SiteRule::TrimSites
94    }
95
96    fn owner_rule(&self) -> OwnerRule {
97        OwnerRule::AnyOwner
98    }
99
100    fn component_rule(&self) -> ComponentRule {
101        ComponentRule::EnforcedOnly
102    }
103}
104
105/// Keep only the clone groups with at least one instance whose line range
106/// overlaps an added line of the diff.
107///
108/// The filter keeps the whole group when one instance overlaps, so a reviewer
109/// sees the full clone family in the context of the change. Clone families,
110/// statistics and the order are rebuilt from the groups that stay, so the
111/// duplication percentage describes the scoped slice.
112pub fn filter_duplication_by_diff(report: &mut DuplicationReport, diff: &DiffIndex, root: &Path) {
113    let instance_overlaps = |instance: &CloneInstance| -> bool {
114        let Some(rel) = diff.key_for(&instance.file, root) else {
115            return true;
116        };
117        let start = u64::try_from(instance.start_line).unwrap_or(u64::MAX);
118        let end = u64::try_from(instance.end_line).unwrap_or(u64::MAX);
119        diff.range_overlaps_added(&rel, start, end)
120    };
121    report
122        .clone_groups
123        .retain(|group| group.instances.iter().any(instance_overlaps));
124    report.range_marker_problems.retain(|finding| {
125        diff.key_for(&finding.path, root).is_none_or(|rel| {
126            diff.range_overlaps_added(
127                &rel,
128                u64::from(finding.problem.line),
129                u64::from(finding.problem.line),
130            )
131        })
132    });
133    crate::duplicates::refresh_scoped_report(report, root);
134}
135
136#[cfg(test)]
137#[path = "diff_scope_tests.rs"]
138mod tests;