Skip to main content

fallow_cli/report/
dupes_grouping.rs

1//! Per-group attribution for `fallow dupes --group-by`.
2//!
3//! For each `CloneGroup`, every instance is attributed to a group key (owner,
4//! directory, package, or section) via the same [`OwnershipResolver`] used by
5//! `check` and `health`. The group itself is then attributed to its
6//! **largest owner**: the key with the most instances in that clone group.
7//! Ties are broken alphabetically (lexicographic ascending).
8//!
9//! This mirrors jscpd's majority-owner attribution and avoids the
10//! positional non-determinism that a "first-instance-wins" rule would
11//! introduce, since `DuplicationReport::sort()` already orders instances
12//! deterministically by file path then line.
13
14use std::collections::BTreeMap;
15use std::path::Path;
16
17use fallow_core::duplicates::{
18    CloneFingerprintSet, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
19};
20use rustc_hash::FxHashSet;
21use serde::Serialize;
22
23use super::grouping::OwnershipResolver;
24use super::relative_path;
25use crate::baseline::recompute_stats;
26use crate::codeowners::UNOWNED_LABEL;
27use crate::output_dupes::{AttributedCloneGroupFinding, CloneFamilyFinding};
28
29/// Resolve the group key for a single instance file.
30fn key_for_instance(instance: &CloneInstance, root: &Path, resolver: &OwnershipResolver) -> String {
31    resolver.resolve(relative_path(&instance.file, root))
32}
33
34/// Pick the largest owner for a clone group: most instances wins, ties broken
35/// alphabetically (smallest key wins).
36///
37/// Iterates a `BTreeMap` so iteration order is alphabetical. The first key
38/// to reach the running maximum wins, which means equal counts resolve to the
39/// alphabetically-smallest key.
40pub fn largest_owner(group: &CloneGroup, root: &Path, resolver: &OwnershipResolver) -> String {
41    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
42    for instance in &group.instances {
43        let key = key_for_instance(instance, root, resolver);
44        *counts.entry(key).or_insert(0) += 1;
45    }
46    if counts.is_empty() {
47        return UNOWNED_LABEL.to_string();
48    }
49    let mut best_key: Option<String> = None;
50    let mut best_count: u32 = 0;
51    for (key, count) in counts {
52        if best_key.is_none() || count > best_count {
53            best_count = count;
54            best_key = Some(key);
55        }
56    }
57    best_key.unwrap_or_else(|| UNOWNED_LABEL.to_string())
58}
59
60/// A clone instance plus its per-instance owner key (for inline JSON / SARIF
61/// rendering).
62///
63/// Each instance carries its own `owner` field alongside the standard
64/// `CloneInstance` shape (file / start_line / end_line / start_col / end_col /
65/// fragment), so consumers can attribute instances to resolver keys without
66/// re-resolving paths.
67#[derive(Debug, Clone, Serialize)]
68#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
69pub struct AttributedInstance {
70    /// The original clone instance.
71    #[serde(flatten)]
72    pub instance: CloneInstance,
73    /// Resolver key for this specific instance (per-instance, not the
74    /// group-level largest-owner).
75    pub owner: String,
76}
77
78/// A clone group annotated with its largest-owner attribution and per-instance
79/// owner keys.
80#[derive(Debug, Clone, Serialize)]
81#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
82pub struct AttributedCloneGroup {
83    /// Largest-owner attribution: the resolver key with the most instances in
84    /// this clone group. Ties broken alphabetically (smallest key wins).
85    pub primary_owner: String,
86    pub token_count: usize,
87    pub line_count: usize,
88    /// Each instance carries its own `owner` field alongside the standard
89    /// CloneInstance shape.
90    pub instances: Vec<AttributedInstance>,
91}
92
93impl AttributedCloneGroup {
94    fn from_group(group: &CloneGroup, root: &Path, resolver: &OwnershipResolver) -> Self {
95        let primary_owner = largest_owner(group, root, resolver);
96        let instances = group
97            .instances
98            .iter()
99            .map(|instance| AttributedInstance {
100                owner: key_for_instance(instance, root, resolver),
101                instance: instance.clone(),
102            })
103            .collect();
104        Self {
105            primary_owner,
106            token_count: group.token_count,
107            line_count: group.line_count,
108            instances,
109        }
110    }
111
112    fn fingerprint(&self, fingerprints: &CloneFingerprintSet) -> String {
113        let instances: Vec<_> = self
114            .instances
115            .iter()
116            .map(|instance| instance.instance.clone())
117            .collect();
118        fingerprints.fingerprint_for_parts(&instances, self.token_count, self.line_count)
119    }
120}
121
122/// A single grouped duplication bucket. Per-group `stats` are dedup-aware and
123/// computed over the FULL group BEFORE any `--top` truncation.
124#[derive(Debug, Clone, Serialize)]
125#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
126pub struct DuplicationGroup {
127    /// Group label (owner / directory / package / section). `(unowned)` for
128    /// files with no CODEOWNERS rule, `(no section)` for pre-section rules in
129    /// section mode.
130    pub key: String,
131    pub stats: DuplicationStats,
132    /// Clone groups attributed to this owner, each wrapped with the typed
133    /// `actions[]` array. Each group's `primary_owner` is its largest-owner
134    /// key; per-instance `owner` lets consumers see cross-bucket fan-out
135    /// without re-resolving paths.
136    pub clone_groups: Vec<AttributedCloneGroupFinding>,
137    /// Clone families overlapping this bucket, each wrapped with the typed
138    /// `actions[]` array.
139    pub clone_families: Vec<CloneFamilyFinding>,
140}
141
142/// Wrapper carrying the resolver mode label and grouped buckets.
143#[derive(Debug, Clone, Serialize)]
144pub struct DuplicationGrouping {
145    /// Resolver mode label (`"owner"`, `"directory"`, `"package"`, `"section"`).
146    pub mode: &'static str,
147    /// One bucket per resolver key, sorted most clone groups first with
148    /// `(unowned)` pinned last.
149    pub groups: Vec<DuplicationGroup>,
150}
151
152/// Build the grouped duplication payload from a project-level report.
153///
154/// Aggregation is performed BEFORE any `--top` truncation so per-group stats
155/// reflect the full group, not just the rendered top-N.
156pub fn build_duplication_grouping(
157    report: &DuplicationReport,
158    root: &Path,
159    resolver: &OwnershipResolver,
160) -> DuplicationGrouping {
161    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
162    // Bucket clone groups by largest owner.
163    let mut buckets: BTreeMap<String, Vec<AttributedCloneGroup>> = BTreeMap::new();
164    for group in &report.clone_groups {
165        let attributed = AttributedCloneGroup::from_group(group, root, resolver);
166        buckets
167            .entry(attributed.primary_owner.clone())
168            .or_default()
169            .push(attributed);
170    }
171
172    // For each bucket, recompute stats from its clone groups by reusing
173    // `recompute_stats`. Use the original (non-attributed) clone groups to
174    // feed the helper so we share the dedup logic with the project report.
175    let mut groups: Vec<DuplicationGroup> = buckets
176        .into_iter()
177        .map(|(key, attributed_groups)| {
178            // Reconstruct a partial DuplicationReport for stats recomputation.
179            let original_groups: Vec<CloneGroup> = attributed_groups
180                .iter()
181                .map(|ag| CloneGroup {
182                    instances: ag.instances.iter().map(|i| i.instance.clone()).collect(),
183                    token_count: ag.token_count,
184                    line_count: ag.line_count,
185                })
186                .collect();
187            let mut subset = DuplicationReport {
188                clone_groups: original_groups,
189                clone_families: Vec::new(),
190                mirrored_directories: Vec::new(),
191                stats: DuplicationStats {
192                    total_files: report.stats.total_files,
193                    files_with_clones: 0,
194                    total_lines: report.stats.total_lines,
195                    duplicated_lines: 0,
196                    total_tokens: report.stats.total_tokens,
197                    duplicated_tokens: 0,
198                    clone_groups: 0,
199                    clone_instances: 0,
200                    duplication_percentage: 0.0,
201                    clone_groups_below_min_occurrences: report
202                        .stats
203                        .clone_groups_below_min_occurrences,
204                },
205            };
206            subset.stats = recompute_stats(&subset);
207
208            // Restrict clone families to those whose group memberships overlap
209            // this bucket. Using a file-set membership check matches how the
210            // project-level report treats families: a family's groups must all
211            // share its file set.
212            let bucket_files: FxHashSet<&Path> = attributed_groups
213                .iter()
214                .flat_map(|ag| ag.instances.iter().map(|i| i.instance.file.as_path()))
215                .collect();
216            let clone_families: Vec<CloneFamilyFinding> = report
217                .clone_families
218                .iter()
219                .filter(|f| f.files.iter().any(|fp| bucket_files.contains(fp.as_path())))
220                .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), &fingerprints))
221                .collect();
222
223            let clone_groups: Vec<AttributedCloneGroupFinding> = attributed_groups
224                .into_iter()
225                .map(|group| {
226                    let fingerprint = group.fingerprint(&fingerprints);
227                    AttributedCloneGroupFinding::with_fingerprint(group, fingerprint)
228                })
229                .collect();
230
231            DuplicationGroup {
232                key,
233                stats: subset.stats,
234                clone_groups,
235                clone_families,
236            }
237        })
238        .collect();
239
240    // Sort: most clone groups first, alphabetical tiebreak, (unowned) last.
241    groups.sort_by(|a, b| {
242        let a_unowned = a.key == UNOWNED_LABEL;
243        let b_unowned = b.key == UNOWNED_LABEL;
244        match (a_unowned, b_unowned) {
245            (true, false) => std::cmp::Ordering::Greater,
246            (false, true) => std::cmp::Ordering::Less,
247            _ => b
248                .clone_groups
249                .len()
250                .cmp(&a.clone_groups.len())
251                .then_with(|| a.key.cmp(&b.key)),
252        }
253    });
254
255    DuplicationGrouping {
256        mode: resolver.mode_label(),
257        groups,
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use std::path::PathBuf;
264
265    use fallow_core::duplicates::{CloneInstance, DuplicationStats};
266
267    use super::*;
268    use crate::codeowners::CodeOwners;
269
270    fn instance(path: &str, start: usize, end: usize) -> CloneInstance {
271        CloneInstance {
272            file: PathBuf::from(path),
273            start_line: start,
274            end_line: end,
275            start_col: 0,
276            end_col: 0,
277            fragment: String::new(),
278        }
279    }
280
281    fn group(instances: Vec<CloneInstance>) -> CloneGroup {
282        CloneGroup {
283            instances,
284            token_count: 50,
285            line_count: 10,
286        }
287    }
288
289    fn report(groups: Vec<CloneGroup>) -> DuplicationReport {
290        DuplicationReport {
291            clone_groups: groups,
292            clone_families: vec![],
293            mirrored_directories: vec![],
294            stats: DuplicationStats {
295                total_files: 10,
296                total_lines: 1000,
297                ..Default::default()
298            },
299        }
300    }
301
302    #[test]
303    fn largest_owner_majority_wins() {
304        let r = group(vec![
305            instance("/root/src/a.ts", 1, 10),
306            instance("/root/src/b.ts", 1, 10),
307            instance("/root/lib/c.ts", 1, 10),
308        ]);
309        let key = largest_owner(&r, Path::new("/root"), &OwnershipResolver::Directory);
310        assert_eq!(key, "src", "src has 2 instances vs lib's 1");
311    }
312
313    #[test]
314    fn largest_owner_alphabetical_tiebreak() {
315        let r = group(vec![
316            instance("/root/src/a.ts", 1, 10),
317            instance("/root/lib/b.ts", 1, 10),
318        ]);
319        // 1 vs 1 -- alphabetical: lib < src
320        let key = largest_owner(&r, Path::new("/root"), &OwnershipResolver::Directory);
321        assert_eq!(key, "lib");
322    }
323
324    #[test]
325    fn largest_owner_three_way_tie_alphabetical() {
326        let r = group(vec![
327            instance("/root/zeta/a.ts", 1, 10),
328            instance("/root/alpha/b.ts", 1, 10),
329            instance("/root/beta/c.ts", 1, 10),
330        ]);
331        let key = largest_owner(&r, Path::new("/root"), &OwnershipResolver::Directory);
332        assert_eq!(key, "alpha");
333    }
334
335    #[test]
336    fn build_grouping_partitions_clone_groups() {
337        let g1 = group(vec![
338            instance("/root/src/a.ts", 1, 10),
339            instance("/root/src/b.ts", 1, 10),
340        ]);
341        let g2 = group(vec![
342            instance("/root/lib/x.ts", 1, 10),
343            instance("/root/lib/y.ts", 1, 10),
344        ]);
345        let r = report(vec![g1, g2]);
346        let grouping =
347            build_duplication_grouping(&r, Path::new("/root"), &OwnershipResolver::Directory);
348        assert_eq!(grouping.groups.len(), 2);
349        let lib = grouping.groups.iter().find(|g| g.key == "lib").unwrap();
350        let src = grouping.groups.iter().find(|g| g.key == "src").unwrap();
351        assert_eq!(lib.clone_groups.len(), 1);
352        assert_eq!(src.clone_groups.len(), 1);
353    }
354
355    #[test]
356    fn build_grouping_unowned_pinned_last() {
357        let co = CodeOwners::parse("/src/ @frontend\n").unwrap();
358        let resolver = OwnershipResolver::Owner(co);
359        // src group attributed to @frontend; docs group has no rule -> unowned
360        let g_src = group(vec![
361            instance("/root/src/a.ts", 1, 10),
362            instance("/root/src/b.ts", 1, 10),
363        ]);
364        let g_docs = group(vec![
365            instance("/root/docs/a.md", 1, 10),
366            instance("/root/docs/b.md", 1, 10),
367        ]);
368        let r = report(vec![g_src, g_docs]);
369        let grouping = build_duplication_grouping(&r, Path::new("/root"), &resolver);
370        assert_eq!(grouping.groups.len(), 2);
371        // unowned must be last
372        assert_eq!(grouping.groups.last().unwrap().key, UNOWNED_LABEL);
373    }
374
375    #[test]
376    fn build_grouping_per_instance_owner_inline() {
377        let g = group(vec![
378            instance("/root/src/a.ts", 1, 10),
379            instance("/root/src/b.ts", 1, 10),
380            instance("/root/lib/c.ts", 1, 10),
381        ]);
382        let r = report(vec![g]);
383        let grouping =
384            build_duplication_grouping(&r, Path::new("/root"), &OwnershipResolver::Directory);
385        // Group has src=2, lib=1 -> primary src; instances carry their own owner.
386        assert_eq!(grouping.groups.len(), 1);
387        let bucket = &grouping.groups[0];
388        assert_eq!(bucket.key, "src");
389        assert_eq!(bucket.clone_groups.len(), 1);
390        let finding = &bucket.clone_groups[0];
391        let cg = &finding.group;
392        assert_eq!(cg.primary_owner, "src");
393        assert_eq!(cg.instances.len(), 3);
394        let owners: Vec<&str> = cg.instances.iter().map(|i| i.owner.as_str()).collect();
395        assert!(owners.contains(&"src"));
396        assert!(owners.contains(&"lib"));
397        // Each AttributedCloneGroupFinding carries the canonical 2-action array
398        // (extract-shared + suppress-line).
399        assert_eq!(finding.actions.len(), 2);
400    }
401
402    #[test]
403    fn empty_report_produces_empty_grouping() {
404        let r = DuplicationReport::default();
405        let grouping =
406            build_duplication_grouping(&r, Path::new("/root"), &OwnershipResolver::Directory);
407        assert!(grouping.groups.is_empty());
408    }
409}