Skip to main content

fallow_api/
dupes_output.rs

1//! Shared duplication JSON payload contracts for programmatic consumers.
2
3use std::path::{Path, PathBuf};
4
5use fallow_engine::duplicates::{CloneFingerprintSet, dominant_identifier};
6use fallow_output::{
7    CloneFamilyAction, CloneGroupAction, CodeClimateIssue, CodeClimateIssueInput,
8    CodeClimateSeverity, clone_family_actions, clone_group_actions, codeclimate_fingerprint_hash,
9    normalize_uri,
10};
11use fallow_types::duplicates::{
12    CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats, MirroredDirectory,
13    RangeMarkerFinding, RefactoringSuggestion, clone_location_spread,
14};
15use fallow_types::envelope::AuditIntroduced;
16use fallow_types::serde_path;
17use serde::Serialize;
18
19/// A clone instance plus its per-instance owner key (for inline JSON / SARIF
20/// rendering).
21///
22/// Each instance carries its own `owner` field alongside the standard
23/// `CloneInstance` shape (file / start_line / end_line / start_col / end_col /
24/// fragment), so consumers can attribute instances to resolver keys without
25/// re-resolving paths.
26#[derive(Debug, Clone, Serialize)]
27#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
28pub struct AttributedInstance {
29    /// The original clone instance.
30    #[serde(flatten)]
31    pub instance: CloneInstance,
32    /// Resolver key for this specific instance (per-instance, not the
33    /// group-level largest-owner).
34    pub owner: String,
35}
36
37/// A clone group annotated with largest-owner attribution and per-instance
38/// owner keys.
39#[derive(Debug, Clone, Serialize)]
40#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
41pub struct AttributedCloneGroup {
42    /// Largest-owner attribution: the resolver key with the most instances in
43    /// this clone group. Ties broken alphabetically (smallest key wins).
44    pub primary_owner: String,
45    /// Number of tokens in the clone group.
46    pub token_count: usize,
47    /// Number of source lines in the clone group.
48    pub line_count: usize,
49    /// Lowest all-pairs similarity for a near-miss clone group.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
52    pub similarity: Option<f64>,
53    /// Each instance carries its own `owner` field alongside the standard
54    /// CloneInstance shape.
55    pub instances: Vec<AttributedInstance>,
56}
57
58impl AttributedCloneGroup {
59    /// Return the report-scoped fingerprint for this attributed group.
60    #[must_use]
61    pub fn fingerprint(&self, fingerprints: &CloneFingerprintSet) -> String {
62        let instances: Vec<_> = self
63            .instances
64            .iter()
65            .map(|instance| instance.instance.clone())
66            .collect();
67        fingerprints.fingerprint_for_parts(&instances, self.token_count, self.line_count)
68    }
69}
70
71/// Wire-shape envelope for an [`AttributedCloneGroup`] finding (per-bucket
72/// duplication attribution emitted under `fallow dupes --group-by`).
73/// Flattens the attributed group and carries the same typed
74/// `CloneGroupAction` array as `CloneGroupFinding`; no `introduced`
75/// field because `fallow audit` does not run on grouped output.
76#[derive(Debug, Clone, Serialize)]
77#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
78pub struct AttributedCloneGroupFinding {
79    /// The underlying attributed clone group.
80    #[serde(flatten)]
81    pub group: AttributedCloneGroup,
82    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
83    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>`.
84    /// Computed from the group's instances, so it matches the top-level
85    /// `clone_groups[].fingerprint` for the same clone.
86    pub fingerprint: String,
87    /// Maximum directory-tree or same-file line distance between instances.
88    pub spread: usize,
89    /// Suggested next steps. Always emitted.
90    pub actions: Vec<CloneGroupAction>,
91}
92
93impl AttributedCloneGroupFinding {
94    /// Build the wrapper with a precomputed report-scoped fingerprint.
95    #[must_use]
96    pub fn with_fingerprint(group: AttributedCloneGroup, fingerprint: String) -> Self {
97        let spread = clone_location_spread(group.instances.iter().map(|instance| {
98            (
99                instance.instance.file.as_path(),
100                instance.instance.start_line,
101                instance.instance.end_line,
102            )
103        }));
104        let actions = clone_group_actions(group.line_count, group.instances.len());
105        Self {
106            group,
107            fingerprint,
108            spread,
109            actions,
110        }
111    }
112}
113
114/// A single grouped duplication bucket. Per-group `stats` are dedup-aware and
115/// computed over the full group before any `--top` truncation.
116#[derive(Debug, Clone, Serialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118pub struct DuplicationGroup {
119    /// Group label (owner / directory / package / section). `(unowned)` for
120    /// files with no CODEOWNERS rule, `(no section)` for pre-section rules in
121    /// section mode.
122    pub key: String,
123    /// Dedup-aware aggregate stats for the group.
124    pub stats: DuplicationStats,
125    /// Clone groups attributed to this owner, each wrapped with the typed
126    /// `actions[]` array. Each group's `primary_owner` is its largest-owner
127    /// key; per-instance `owner` lets consumers see cross-bucket fan-out
128    /// without re-resolving paths.
129    pub clone_groups: Vec<AttributedCloneGroupFinding>,
130    /// Clone families overlapping this bucket, each wrapped with the typed
131    /// `actions[]` array.
132    pub clone_families: Vec<CloneFamilyFinding>,
133}
134
135impl DuplicationGroup {
136    /// Drop the verbatim source text from every clone instance in this bucket,
137    /// including the copies nested in `clone_families[].groups[]`.
138    pub fn strip_fragments(&mut self) {
139        for finding in &mut self.clone_groups {
140            for instance in &mut finding.group.instances {
141                instance.instance.fragment.clear();
142            }
143        }
144        for family in &mut self.clone_families {
145            for finding in &mut family.groups {
146                finding.group.strip_fragments();
147            }
148        }
149    }
150}
151
152/// Wrapper carrying the resolver mode label and grouped buckets.
153#[derive(Debug, Clone, Serialize)]
154pub struct DuplicationGrouping {
155    /// Resolver mode label (`"owner"`, `"directory"`, `"package"`, `"section"`).
156    pub mode: &'static str,
157    /// One bucket per resolver key.
158    pub groups: Vec<DuplicationGroup>,
159}
160
161/// Why the audit new-only gate demoted an introduced clone group to
162/// inherited. Serializes as a kebab-case string on the wire (for example
163/// `"no-added-lines"`).
164///
165/// Further variants may be added in later releases; consumers should treat an
166/// unknown value as "some demotion reason" rather than failing.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
168#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
169#[serde(rename_all = "kebab-case")]
170pub enum CloneDemotionReason {
171    /// No instance of the group overlaps an added line in the run's diff: the
172    /// group was re-shaped by removals elsewhere in the changeset, not written
173    /// by it (issue #2164).
174    NoAddedLines,
175}
176
177impl CloneDemotionReason {
178    /// The kebab-case wire literal, obtained from the serde representation so
179    /// human output and JSON cannot diverge.
180    #[must_use]
181    pub fn wire_name(self) -> String {
182        match serde_json::to_value(self) {
183            Ok(serde_json::Value::String(name)) => name,
184            _ => String::new(),
185        }
186    }
187}
188
189/// The audit grade of a clone region.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
191#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
192#[serde(rename_all = "kebab-case")]
193pub enum CloneRegionGrade {
194    /// A member group has a copy that the base does not have, or the change
195    /// made two different pieces of old code equal. The region fails the
196    /// `introduced-clone-group` gate unless `accepted_by` names the
197    /// `ignoredClones` entries that accept each new copy.
198    Introduced,
199    /// Each member group is a base group, or the change wrote no line of it.
200    Inherited,
201    /// Each member group lies inside a base group, at the same place of each
202    /// base copy, and the change edited one or more of its copies. Each copy
203    /// grows by fewer lines than `duplicates.minLines`. A rewrite that keeps
204    /// the size of every copy counts as an edit. The region does not fail the
205    /// gate.
206    InheritedEdited,
207}
208
209/// One file span of a clone region.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
211#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
212pub struct CloneRegionSpan {
213    /// Project-root-relative path, with forward slashes.
214    pub file: String,
215    /// 1-based first line.
216    pub start_line: u32,
217    /// 1-based last line, inclusive.
218    pub end_line: u32,
219}
220
221/// A clone region of `fallow audit`: the clone groups whose instances
222/// overlap, graded as one finding. One paste can give a long group with
223/// fewer copies and a short group with more copies; both are members of one
224/// region (issue #4967).
225#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
226#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
227pub struct CloneRegionFinding {
228    /// The grade of the region against the base.
229    pub grade: CloneRegionGrade,
230    /// Whether the region fails the new-only gate. Each member group in
231    /// `clone_groups[]` carries the same `introduced` value.
232    pub introduced: bool,
233    /// Indices of the member groups in `clone_groups[]`.
234    pub groups: Vec<usize>,
235    /// The union of the member instance lines in each file.
236    pub instances: Vec<CloneRegionSpan>,
237    /// The `duplicates.ignoredClones` entries that accept the region. An
238    /// entry accepts an `inherited-edited` region when it matched the base
239    /// clone, and an `introduced` region when it hid the head group of each
240    /// new copy.
241    #[serde(default, skip_serializing_if = "Vec::is_empty")]
242    pub accepted_by: Vec<String>,
243    /// The keys to put in `duplicates.ignoredClones` in place of
244    /// `accepted_by`, so that `fallow dupes` also hides the edited clone.
245    /// Present only for an accepted `inherited-edited` region.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub ignore_hint: Vec<String>,
248    /// Set when the region does not fail the gate because the change wrote
249    /// no line of a member group whose key is new (issue #2164).
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub demotion_reason: Option<CloneDemotionReason>,
252}
253
254/// Wire-shape envelope for a [`CloneGroup`] finding. Flattens the bare
255/// group via `#[serde(flatten)]` and carries a typed `actions` array plus
256/// the optional audit-mode `introduced` flag. The typed envelope replaced
257/// the legacy JSON post-pass injection; a guard test in
258/// `crates/cli/src/report/json.rs` rejects any reintroduced post-pass.
259#[derive(Debug, Clone, Serialize)]
260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
261pub struct CloneGroupFinding {
262    /// The underlying clone group.
263    #[serde(flatten)]
264    pub group: CloneGroup,
265    /// Stable content fingerprint, usually `dup:<8hex>` and widened on rare
266    /// report collisions. Addressable via `fallow dupes --trace dup:<fp>` (and
267    /// the `trace_clone` MCP tool) to deep-dive this group; shown alongside
268    /// each group in the human listing.
269    pub fingerprint: String,
270    /// Maximum directory-tree or same-file line distance between instances.
271    pub spread: usize,
272    /// Best-effort human-readable name for the clone: the dominant repeated
273    /// identifier across the duplicated fragment (e.g. a shared `parseCsv`
274    /// function). `None` when the clone has no clear dominant name (generic or
275    /// tied identifiers); consumers then fall back to a file-based label. Lets
276    /// editors and agents label a clone by what it is rather than an opaque
277    /// ordinal.
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub suggested_name: Option<String>,
280    /// Suggested next steps: an `extract-shared` primary and a
281    /// `suppress-line` secondary. Always emitted (possibly empty for
282    /// forward-compat).
283    pub actions: Vec<CloneGroupAction>,
284    /// Set by the audit pass when this clone group is introduced relative
285    /// to the merge-base. `None` when serialized directly from Rust.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub introduced: Option<AuditIntroduced>,
288    /// Set only by `fallow audit` under `--gate new-only`, on groups whose
289    /// `introduced` flag the gate demoted to `false`: why the demotion
290    /// happened. `None` everywhere else, including `fallow dupes
291    /// --format json` (issue #2220).
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub demotion_reason: Option<CloneDemotionReason>,
294    /// Set only by `fallow audit` with a base: the index of the region of
295    /// this group in `clone_regions[]`.
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub region: Option<usize>,
298}
299
300impl CloneGroupFinding {
301    /// Build the wrapper with a precomputed report-scoped fingerprint.
302    #[must_use]
303    pub fn with_fingerprint(group: CloneGroup, fingerprint: String) -> Self {
304        let spread = group.spread();
305        let suggested_name = dominant_identifier(&group);
306        let actions = clone_group_actions(group.line_count, group.instances.len());
307        Self {
308            fingerprint,
309            spread,
310            suggested_name,
311            group,
312            actions,
313            introduced: None,
314            demotion_reason: None,
315            region: None,
316        }
317    }
318}
319
320/// Wire-shape envelope for a [`CloneFamily`] finding.
321///
322/// Unlike most `*Finding` wrappers this one is NOT `#[serde(flatten)]` over
323/// the bare [`CloneFamily`], because the family's nested
324/// `groups: Vec<CloneGroup>` field needs to carry the typed
325/// `CloneGroupFinding` wrapper too (so every nested clone group gets its
326/// own `actions[]` array, matching the legacy post-pass behavior; see issue
327/// #393 regression test). The wire shape stays byte-identical to the
328/// previous post-pass output. No `introduced` field because `fallow audit`
329/// attributes clone groups (not families) when running against a base ref.
330#[derive(Debug, Clone, Serialize)]
331#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
332pub struct CloneFamilyFinding {
333    /// The files involved in this family.
334    #[serde(serialize_with = "serde_path::serialize_vec")]
335    pub files: Vec<PathBuf>,
336    /// Clone groups belonging to this family, each wrapped with typed
337    /// `actions[]` so consumers that read `clone_families[].groups[]`
338    /// directly see the same shape as the top-level `clone_groups[]`.
339    pub groups: Vec<CloneGroupFinding>,
340    /// Total number of duplicated lines across all groups.
341    pub total_duplicated_lines: usize,
342    /// Total number of duplicated tokens across all groups.
343    pub total_duplicated_tokens: usize,
344    /// Refactoring suggestions for this family.
345    pub suggestions: Vec<RefactoringSuggestion>,
346    /// Suggested next steps: an `extract-shared` primary, one
347    /// `apply-suggestion` per `RefactoringSuggestion` on the family, and
348    /// a trailing `suppress-line`. Always emitted (possibly empty for
349    /// forward-compat).
350    pub actions: Vec<CloneFamilyAction>,
351}
352
353impl CloneFamilyFinding {
354    /// Build the wrapper using the report-scoped fingerprint assignment shared
355    /// by all duplication output surfaces.
356    #[must_use]
357    pub fn with_fingerprints(family: CloneFamily, fingerprints: &CloneFingerprintSet) -> Self {
358        let actions = build_clone_family_actions(
359            &family.groups,
360            family.total_duplicated_lines,
361            &family.suggestions,
362        );
363        Self {
364            files: family.files,
365            groups: family
366                .groups
367                .into_iter()
368                .map(|group| {
369                    let fingerprint = fingerprints.fingerprint_for_group(&group);
370                    CloneGroupFinding::with_fingerprint(group, fingerprint)
371                })
372                .collect(),
373            total_duplicated_lines: family.total_duplicated_lines,
374            total_duplicated_tokens: family.total_duplicated_tokens,
375            suggestions: family.suggestions,
376            actions,
377        }
378    }
379}
380
381fn build_clone_family_actions(
382    groups: &[CloneGroup],
383    total_duplicated_lines: usize,
384    suggestions: &[RefactoringSuggestion],
385) -> Vec<CloneFamilyAction> {
386    clone_family_actions(
387        groups.len(),
388        total_duplicated_lines,
389        suggestions
390            .iter()
391            .map(|suggestion| suggestion.description.as_str()),
392    )
393}
394
395/// Wire-shape payload for `fallow dupes --format json` (the body that
396/// flattens into the `DupesOutput` envelope and is also
397/// emitted under the `dupes` / `duplication` key inside the combined and
398/// audit envelopes).
399///
400/// Mirrors [`DuplicationReport`] field-for-field, except `clone_groups`
401/// and `clone_families` carry the typed wrapper envelopes instead of bare
402/// findings, so the schema (and any TS / agent consumer) sees the typed
403/// `actions[]` natively.
404#[derive(Debug, Clone, Serialize)]
405#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
406pub struct DupesReportPayload {
407    /// All detected clone groups, each wrapped with typed actions.
408    pub clone_groups: Vec<CloneGroupFinding>,
409    /// Clone families, each wrapped with typed actions. Inner `groups`
410    /// inside each `CloneFamilyFinding` are themselves wrapped as
411    /// `CloneGroupFinding` entries carrying their own `actions[]` (and
412    /// optional audit-mode `introduced` flag), so JSON-Schema strict
413    /// consumers and TS consumers reading `clone_families[].groups[]` see
414    /// the same shape as the top-level `clone_groups[]` array (preserves
415    /// the issue #393 regression contract).
416    pub clone_families: Vec<CloneFamilyFinding>,
417    /// Mirrored directory pairs.
418    #[serde(default, skip_serializing_if = "Vec::is_empty")]
419    pub mirrored_directories: Vec<MirroredDirectory>,
420    /// `fallow-ignore-start` and `fallow-ignore-end` markers with a problem.
421    /// A marker with a problem has no effect on clone detection.
422    #[serde(default, skip_serializing_if = "Vec::is_empty")]
423    pub range_marker_problems: Vec<RangeMarkerFinding>,
424    /// Aggregate duplication statistics.
425    pub stats: DuplicationStats,
426    /// Set only by `fallow audit` with a base: the clone groups whose
427    /// instances overlap, graded as one finding each. The new-only gate
428    /// counts these regions.
429    #[serde(default, skip_serializing_if = "Vec::is_empty")]
430    pub clone_regions: Vec<CloneRegionFinding>,
431}
432
433/// Wire shape of the `dupes` section inside the bare combined envelope.
434///
435/// The section is the standalone payload plus the view of the loaded
436/// duplication baseline. The standalone `dupes` envelope carries the same
437/// `baseline_staleness` key at its root.
438#[derive(Debug, Clone, Serialize)]
439#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
440pub struct CombinedDupesSection {
441    /// The duplication payload, flattened into the section.
442    #[serde(flatten)]
443    pub payload: DupesReportPayload,
444    /// This run's view of the loaded duplication baseline, present only when
445    /// `--dupes-baseline` loaded one. Read `change_scoped` before dividing
446    /// `matched_entries` by `baseline_entries`: a narrowed run can report
447    /// `matched_entries: 0` on a healthy baseline.
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub baseline_staleness: Option<fallow_output::BaselineStaleness>,
450}
451
452impl DupesReportPayload {
453    /// Build the payload from a bare [`DuplicationReport`].
454    #[must_use]
455    pub fn from_report(report: &DuplicationReport) -> Self {
456        let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
457        Self {
458            clone_groups: report
459                .clone_groups
460                .iter()
461                .map(|group| {
462                    CloneGroupFinding::with_fingerprint(
463                        group.clone(),
464                        fingerprints.fingerprint_for_group(group),
465                    )
466                })
467                .collect(),
468            clone_families: report
469                .clone_families
470                .iter()
471                .map(|family| CloneFamilyFinding::with_fingerprints(family.clone(), &fingerprints))
472                .collect(),
473            mirrored_directories: report.mirrored_directories.clone(),
474            range_marker_problems: report.range_marker_problems.clone(),
475            stats: report.stats.clone(),
476            clone_regions: Vec::new(),
477        }
478    }
479
480    /// Build the payload and drop the verbatim source text when the caller
481    /// asked for a location-only body.
482    ///
483    /// Fingerprints, suggested names and actions are computed by
484    /// [`Self::from_report`], so the text is only removed after every consumer
485    /// that reads it has run.
486    #[must_use]
487    pub fn from_report_with_fragments(report: &DuplicationReport, include_fragments: bool) -> Self {
488        let mut payload = Self::from_report(report);
489        if !include_fragments {
490            payload.strip_fragments();
491        }
492        payload
493    }
494
495    /// Drop the verbatim source text from every clone instance, including the
496    /// copies nested in `clone_families[].groups[]`.
497    pub fn strip_fragments(&mut self) {
498        for finding in &mut self.clone_groups {
499            finding.group.strip_fragments();
500        }
501        for family in &mut self.clone_families {
502            for finding in &mut family.groups {
503                finding.group.strip_fragments();
504            }
505        }
506    }
507}
508
509/// The number of fragment characters in the CodeClimate fingerprint of a
510/// clone instance. The count leaves out `\r`, so a CRLF checkout and an LF
511/// checkout of the same code give the same fingerprint.
512const CODECLIMATE_FRAGMENT_PREFIX_CHARS: usize = 64;
513
514/// Build CodeClimate issues from duplication analysis results.
515///
516/// `fallow-output` owns the CodeClimate wire DTOs. This API layer combines
517/// those DTOs with the engine-owned duplication report so CLI and future
518/// embedders can share the same issue construction policy.
519#[must_use]
520#[expect(
521    clippy::cast_possible_truncation,
522    reason = "line numbers are bounded by source size"
523)]
524pub fn build_duplication_codeclimate(
525    report: &DuplicationReport,
526    root: &Path,
527) -> Vec<CodeClimateIssue> {
528    let mut issues = Vec::new();
529
530    let fingerprints = CloneFingerprintSet::from_groups(&report.clone_groups);
531    for group in &report.clone_groups {
532        let clone_fingerprint = fingerprints.fingerprint_for_group(group);
533        let token_str = group.token_count.to_string();
534        let line_count_str = group.line_count.to_string();
535        let fragment_prefix: String = group
536            .instances
537            .first()
538            .map(|inst| {
539                inst.fragment
540                    .chars()
541                    .filter(|&c| c != '\r')
542                    .take(CODECLIMATE_FRAGMENT_PREFIX_CHARS)
543                    .collect()
544            })
545            .unwrap_or_default();
546
547        for (instance_index, instance) in group.instances.iter().enumerate() {
548            let path = codeclimate_path(&instance.file, root);
549            let start_str = instance.start_line.to_string();
550            let fp = codeclimate_fingerprint_hash(&[
551                "fallow/code-duplication",
552                &path,
553                &start_str,
554                &token_str,
555                &line_count_str,
556                &fragment_prefix,
557            ]);
558            let mut issue = fallow_output::build_codeclimate_issue(CodeClimateIssueInput {
559                check_name: "fallow/code-duplication",
560                description: &format!(
561                    "{} lines repeat in {} places (clone group {clone_fingerprint})",
562                    group.line_count,
563                    group.instances.len()
564                ),
565                severity: CodeClimateSeverity::Minor,
566                category: "Duplication",
567                path: &path,
568                begin_line: Some(instance.start_line as u32),
569                fingerprint: &fp,
570            });
571            issue.location.lines.end = Some(instance.end_line as u32);
572            issue.other_locations = group
573                .instances
574                .iter()
575                .enumerate()
576                .filter(|(peer_index, _)| *peer_index != instance_index)
577                .map(|(_, peer)| fallow_output::CodeClimateLocation {
578                    path: codeclimate_path(&peer.file, root),
579                    lines: fallow_output::CodeClimateLines {
580                        begin: peer.start_line as u32,
581                        end: Some(peer.end_line as u32),
582                    },
583                })
584                .collect();
585            issue.other_locations.sort_by(|a, b| {
586                (&a.path, a.lines.begin, a.lines.end).cmp(&(&b.path, b.lines.begin, b.lines.end))
587            });
588            issues.push(issue);
589        }
590    }
591
592    issues
593}
594
595/// Set the audit attribution on the issues of [`build_duplication_codeclimate`].
596///
597/// `introduced` holds one audit flag per clone group, in report order. Each
598/// group gives one issue per instance, so the instances of one group get the
599/// flag of that group. The inline review comment then states if the change
600/// introduced the clone group.
601pub fn set_duplication_audit_attribution(
602    issues: &mut [CodeClimateIssue],
603    report: &DuplicationReport,
604    introduced: impl IntoIterator<Item = bool>,
605) {
606    let mut remaining = issues;
607    for (group, introduced) in report.clone_groups.iter().zip(introduced) {
608        let count = group.instances.len().min(remaining.len());
609        let (group_issues, rest) = remaining.split_at_mut(count);
610        let context = crate::dead_code_codeclimate::audit_review_context(introduced);
611        for issue in group_issues {
612            issue.audit = Some(context);
613        }
614        remaining = rest;
615    }
616}
617
618fn codeclimate_path(path: &Path, root: &Path) -> String {
619    normalize_uri(
620        &path
621            .strip_prefix(root)
622            .unwrap_or(path)
623            .display()
624            .to_string(),
625    )
626}
627
628#[cfg(test)]
629mod tests {
630    use std::path::Path;
631
632    use fallow_output::{CloneFamilyActionType, CloneGroupActionType};
633    use fallow_types::duplicates::{
634        CloneInstance, DuplicationStats, RefactoringKind, RefactoringSuggestion,
635    };
636
637    use super::*;
638
639    const TEST_FINGERPRINT: &str = "dup:00000000";
640
641    fn instance(path: &str) -> CloneInstance {
642        CloneInstance {
643            is_symlink: false,
644            file: PathBuf::from(path),
645            start_line: 1,
646            end_line: 10,
647            start_col: 0,
648            end_col: 0,
649            fragment: String::new(),
650        }
651    }
652
653    fn group(instances: usize) -> CloneGroup {
654        CloneGroup {
655            instances: (0..instances)
656                .map(|i| instance(&format!("/root/file_{i}.ts")))
657                .collect(),
658            token_count: 100,
659            line_count: 20,
660            similarity: None,
661        }
662    }
663
664    fn report_with_fragment(fragment: &str) -> DuplicationReport {
665        let mut clones = group(2);
666        for instance in &mut clones.instances {
667            instance.fragment = fragment.to_owned();
668        }
669        DuplicationReport {
670            clone_groups: vec![clones],
671            clone_families: Vec::new(),
672            mirrored_directories: Vec::new(),
673            range_marker_problems: Vec::new(),
674            stats: DuplicationStats::default(),
675        }
676    }
677
678    fn codeclimate_fingerprints(fragment: &str) -> Vec<String> {
679        build_duplication_codeclimate(&report_with_fragment(fragment), Path::new("/root"))
680            .into_iter()
681            .map(|issue| issue.fingerprint)
682            .collect()
683    }
684
685    /// The prefix holds more than 64 characters, so each `\r` moves a later
686    /// character out of a raw 64-character prefix.
687    const LF_FRAGMENT: &str = "export function total(items) {\n  let sum = 0;\n  for (const item of items) {\n    sum += item.price;\n  }\n  return sum;\n}\n";
688
689    #[test]
690    fn codeclimate_clone_fingerprints_ignore_crlf_line_endings() {
691        let crlf = LF_FRAGMENT.replace('\n', "\r\n");
692        assert_eq!(
693            codeclimate_fingerprints(LF_FRAGMENT),
694            codeclimate_fingerprints(&crlf)
695        );
696    }
697
698    #[test]
699    fn codeclimate_clone_fingerprints_keep_the_lf_hash() {
700        let prefix: String = LF_FRAGMENT.chars().take(64).collect();
701        let expected: Vec<String> = ["/root/file_0.ts", "/root/file_1.ts"]
702            .iter()
703            .map(|path| {
704                codeclimate_fingerprint_hash(&[
705                    "fallow/code-duplication",
706                    &codeclimate_path(Path::new(path), Path::new("/root")),
707                    "1",
708                    "100",
709                    "20",
710                    &prefix,
711                ])
712            })
713            .collect();
714        assert_eq!(codeclimate_fingerprints(LF_FRAGMENT), expected);
715    }
716
717    #[test]
718    fn duplication_audit_attribution_follows_each_group() {
719        use fallow_output::AuditFindingAttribution as A;
720        let report = DuplicationReport {
721            clone_groups: vec![group(2), group(3)],
722            clone_families: Vec::new(),
723            mirrored_directories: Vec::new(),
724            range_marker_problems: Vec::new(),
725            stats: DuplicationStats::default(),
726        };
727        let root = Path::new("/root");
728        let plain = build_duplication_codeclimate(&report, root);
729        let mut issues = plain.clone();
730        set_duplication_audit_attribution(&mut issues, &report, [false, true]);
731        let attributions: Vec<_> = issues
732            .iter()
733            .map(|issue| issue.audit.map(|context| context.attribution))
734            .collect();
735        assert_eq!(
736            attributions,
737            [
738                Some(A::Inherited),
739                Some(A::Inherited),
740                Some(A::Introduced),
741                Some(A::Introduced),
742                Some(A::Introduced),
743            ]
744        );
745        for (with, without) in issues.iter().zip(&plain) {
746            assert_eq!(with.fingerprint, without.fingerprint);
747            assert_eq!(
748                serde_json::to_value(with).expect("issue serializes"),
749                serde_json::to_value(without).expect("issue serializes"),
750                "the wire shape does not carry the attribution"
751            );
752        }
753    }
754
755    #[test]
756    fn clone_group_finding_position_0_is_extract_shared() {
757        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
758        assert_eq!(finding.actions.len(), 3);
759        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
760        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
761        assert_eq!(finding.actions[2].kind, CloneGroupActionType::SuppressRange);
762        assert!(finding.introduced.is_none());
763        assert!(finding.demotion_reason.is_none());
764    }
765
766    #[test]
767    fn clone_group_finding_omits_audit_only_fields_outside_audit() {
768        // `fallow dupes --format json` serializes findings straight from Rust;
769        // the audit-only `introduced` / `demotion_reason` keys must not appear.
770        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
771        let value = serde_json::to_value(&finding).expect("finding serializes");
772        assert!(value.get("introduced").is_none());
773        assert!(value.get("demotion_reason").is_none());
774    }
775
776    #[test]
777    fn suppressed_fragments_leave_locations_and_fingerprints_intact() {
778        let mut with_text = group(2);
779        for (index, instance) in with_text.instances.iter_mut().enumerate() {
780            instance.fragment = format!("const shared{index} = compute(input);");
781        }
782        let family = CloneFamily {
783            files: vec![PathBuf::from("/root/file_0.ts")],
784            groups: vec![with_text.clone()],
785            total_duplicated_lines: 20,
786            total_duplicated_tokens: 100,
787            suggestions: Vec::new(),
788        };
789        let report = DuplicationReport {
790            clone_groups: vec![with_text],
791            clone_families: vec![family],
792            mirrored_directories: Vec::new(),
793            range_marker_problems: Vec::new(),
794            stats: DuplicationStats::default(),
795        };
796
797        let kept = DupesReportPayload::from_report_with_fragments(&report, true);
798        let dropped = DupesReportPayload::from_report_with_fragments(&report, false);
799
800        assert_eq!(
801            kept.clone_groups[0].fingerprint, dropped.clone_groups[0].fingerprint,
802            "fingerprints are computed before the text is dropped"
803        );
804
805        let kept_value = serde_json::to_value(&kept).expect("payload serializes");
806        assert!(kept_value["clone_groups"][0]["instances"][0]["fragment"].is_string());
807
808        let value = serde_json::to_value(&dropped).expect("payload serializes");
809        let instance = &value["clone_groups"][0]["instances"][0];
810        assert!(
811            instance.get("fragment").is_none(),
812            "the verbatim source text must be absent, not empty"
813        );
814        assert!(instance.get("file").is_some());
815        assert!(instance.get("start_line").is_some());
816        assert!(instance.get("end_col").is_some());
817        assert!(
818            value["clone_families"][0]["groups"][0]["instances"][0]
819                .get("fragment")
820                .is_none(),
821            "nested clone-family copies carry the same text and must be dropped too"
822        );
823    }
824
825    #[test]
826    fn clone_demotion_reason_wire_name_matches_serde_representation() {
827        let reason = CloneDemotionReason::NoAddedLines;
828        assert_eq!(
829            serde_json::to_value(reason).expect("reason serializes"),
830            serde_json::Value::String(reason.wire_name())
831        );
832        assert_eq!(reason.wire_name(), "no-added-lines");
833    }
834
835    #[test]
836    fn attributed_clone_group_finding_actions_match_clone_group_shape() {
837        let attributed = AttributedCloneGroup {
838            primary_owner: "src".to_string(),
839            token_count: 100,
840            line_count: 20,
841            similarity: None,
842            instances: vec![
843                AttributedInstance {
844                    instance: instance("/root/src/a.ts"),
845                    owner: "src".to_string(),
846                },
847                AttributedInstance {
848                    instance: instance("/root/src/b.ts"),
849                    owner: "src".to_string(),
850                },
851            ],
852        };
853        let finding =
854            AttributedCloneGroupFinding::with_fingerprint(attributed, TEST_FINGERPRINT.to_string());
855        assert_eq!(finding.actions.len(), 3);
856        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
857        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
858        assert_eq!(finding.actions[2].kind, CloneGroupActionType::SuppressRange);
859    }
860
861    #[test]
862    fn clone_group_finding_surfaces_dominant_identifier() {
863        let fragment = "function parseCsv() { parseCsv(); parseCsv(); return parseCsv; }";
864        let g = CloneGroup {
865            instances: vec![
866                CloneInstance {
867                    is_symlink: false,
868                    file: PathBuf::from("/root/a.ts"),
869                    start_line: 1,
870                    end_line: 3,
871                    start_col: 0,
872                    end_col: 0,
873                    fragment: fragment.to_string(),
874                },
875                CloneInstance {
876                    is_symlink: false,
877                    file: PathBuf::from("/root/b.ts"),
878                    start_line: 1,
879                    end_line: 3,
880                    start_col: 0,
881                    end_col: 0,
882                    fragment: fragment.to_string(),
883                },
884            ],
885            token_count: 100,
886            line_count: 3,
887            similarity: None,
888        };
889        let finding = CloneGroupFinding::with_fingerprint(g, TEST_FINGERPRINT.to_string());
890        assert_eq!(finding.suggested_name.as_deref(), Some("parseCsv"));
891    }
892
893    #[test]
894    fn clone_group_finding_suggested_name_none_for_unnamed_fragment() {
895        let finding = CloneGroupFinding::with_fingerprint(group(2), TEST_FINGERPRINT.to_string());
896        assert!(finding.suggested_name.is_none());
897    }
898
899    #[test]
900    fn clone_group_finding_description_pluralises_instance_count() {
901        let single = CloneGroupFinding::with_fingerprint(group(1), TEST_FINGERPRINT.to_string());
902        assert!(single.actions[0].description.contains("1 instance"));
903        assert!(!single.actions[0].description.contains("1 instances"));
904        let multi = CloneGroupFinding::with_fingerprint(group(3), TEST_FINGERPRINT.to_string());
905        assert!(multi.actions[0].description.contains("3 instances"));
906    }
907
908    #[test]
909    fn clone_family_finding_position_0_is_extract_shared_then_suggestions_then_suppress() {
910        let family = CloneFamily {
911            files: vec![PathBuf::from("/root/a.ts"), PathBuf::from("/root/b.ts")],
912            groups: vec![group(2), group(2)],
913            total_duplicated_lines: 40,
914            total_duplicated_tokens: 200,
915            suggestions: vec![
916                RefactoringSuggestion {
917                    kind: RefactoringKind::ExtractFunction,
918                    description: "Extract helper".to_string(),
919                    estimated_savings: 10,
920                },
921                RefactoringSuggestion {
922                    kind: RefactoringKind::ExtractModule,
923                    description: "Extract module".to_string(),
924                    estimated_savings: 30,
925                },
926            ],
927        };
928        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
929        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
930        assert_eq!(finding.actions.len(), 4);
931        assert_eq!(
932            finding.actions[0].kind,
933            CloneFamilyActionType::ExtractShared
934        );
935        assert_eq!(
936            finding.actions[1].kind,
937            CloneFamilyActionType::ApplySuggestion
938        );
939        assert_eq!(finding.actions[1].description, "Extract helper");
940        assert_eq!(
941            finding.actions[2].kind,
942            CloneFamilyActionType::ApplySuggestion
943        );
944        assert_eq!(finding.actions[2].description, "Extract module");
945        assert_eq!(finding.actions[3].kind, CloneFamilyActionType::SuppressLine);
946        assert_eq!(finding.groups.len(), 2);
947        for inner in &finding.groups {
948            assert_eq!(inner.actions.len(), 3);
949            assert_eq!(inner.actions[0].kind, CloneGroupActionType::ExtractShared);
950            assert_eq!(inner.actions[1].kind, CloneGroupActionType::SuppressLine);
951            assert_eq!(inner.actions[2].kind, CloneGroupActionType::SuppressRange);
952        }
953    }
954
955    #[test]
956    fn clone_family_finding_with_no_suggestions_emits_two_actions() {
957        let family = CloneFamily {
958            files: vec![PathBuf::from("/root/a.ts")],
959            groups: vec![group(2)],
960            total_duplicated_lines: 20,
961            total_duplicated_tokens: 100,
962            suggestions: Vec::new(),
963        };
964        let fingerprints = CloneFingerprintSet::from_groups(&family.groups);
965        let finding = CloneFamilyFinding::with_fingerprints(family, &fingerprints);
966        assert_eq!(finding.actions.len(), 2);
967        assert_eq!(
968            finding.actions[0].kind,
969            CloneFamilyActionType::ExtractShared
970        );
971        assert_eq!(finding.actions[1].kind, CloneFamilyActionType::SuppressLine);
972    }
973
974    #[test]
975    fn payload_from_report_wraps_all_findings() {
976        let report = DuplicationReport {
977            clone_groups: vec![group(2), group(3)],
978            clone_families: vec![CloneFamily {
979                files: vec![PathBuf::from("/root/a.ts")],
980                groups: vec![group(2)],
981                total_duplicated_lines: 20,
982                total_duplicated_tokens: 100,
983                suggestions: Vec::new(),
984            }],
985            mirrored_directories: Vec::new(),
986            range_marker_problems: Vec::new(),
987            stats: DuplicationStats::default(),
988        };
989        let payload = DupesReportPayload::from_report(&report);
990        assert_eq!(payload.clone_groups.len(), 2);
991        assert_eq!(payload.clone_families.len(), 1);
992        for finding in &payload.clone_groups {
993            assert_eq!(finding.actions.len(), 3);
994        }
995        assert_eq!(payload.clone_families[0].actions.len(), 2);
996    }
997
998    #[test]
999    fn duplication_codeclimate_uses_relative_normalized_paths() {
1000        let report = DuplicationReport {
1001            clone_groups: vec![CloneGroup {
1002                instances: vec![CloneInstance {
1003                    is_symlink: false,
1004                    file: PathBuf::from("/root/app/[id]/page.tsx"),
1005                    start_line: 4,
1006                    end_line: 8,
1007                    start_col: 0,
1008                    end_col: 0,
1009                    fragment: "const duplicate = 1;".to_string(),
1010                }],
1011                token_count: 42,
1012                line_count: 5,
1013                similarity: None,
1014            }],
1015            clone_families: Vec::new(),
1016            mirrored_directories: Vec::new(),
1017            range_marker_problems: Vec::new(),
1018            stats: DuplicationStats::default(),
1019        };
1020
1021        let issues = build_duplication_codeclimate(&report, Path::new("/root"));
1022
1023        assert_eq!(issues.len(), 1);
1024        let issue = &issues[0];
1025        assert_eq!(issue.check_name, "fallow/code-duplication");
1026        assert_eq!(issue.location.path, "app/%5Bid%5D/page.tsx");
1027        assert_eq!(issue.location.lines.begin, 4);
1028        assert_eq!(issue.categories, vec!["Duplication"]);
1029        assert!(
1030            issue.description.contains("(clone group dup:"),
1031            "{}",
1032            issue.description
1033        );
1034        assert_eq!(issue.location.lines.end, Some(8));
1035    }
1036}