fallow-cli 2.77.0

CLI for fallow, Rust-native codebase intelligence for TypeScript and JavaScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Typed envelope wrappers for the duplication findings emitted by `fallow
//! dupes --format json` (and the `dupes` block inside `fallow` and `fallow
//! audit`).
//!
//! Each wrapper flattens the bare finding via `#[serde(flatten)]` so the wire
//! shape matches the previous `actions`-grafted output byte-for-byte.
//! `actions` is populated at construction time via each wrapper's
//! `with_actions` constructor and replaces the legacy `inject_dupes_actions`
//! post-pass in `crates/cli/src/report/json.rs`. `introduced` on
//! `CloneGroupFinding` carries the optional audit breadcrumb that
//! `crates/cli/src/audit.rs::annotate_dupes_json` inserts into the JSON object
//! via `map.insert`; the wrapper-level field stays `None` when serialized
//! directly from Rust and is set by the audit pass only when the clone group
//! was introduced relative to the merge-base.
//!
//! Lives in `fallow-cli` rather than `fallow-types` because `CloneFamily`,
//! `CloneGroup`, and `MirroredDirectory` are defined in `fallow-core`
//! (`crates/core/src/duplicates/types.rs`) and `AttributedCloneGroup` is
//! defined in the CLI itself (`crates/cli/src/report/dupes_grouping.rs`);
//! `fallow-types` is the lower-level crate that neither of those reach.

use std::path::PathBuf;

use fallow_core::duplicates::{
    CloneFamily, CloneGroup, DuplicationReport, DuplicationStats, MirroredDirectory,
    RefactoringSuggestion,
};
use fallow_types::envelope::AuditIntroduced;
use fallow_types::serde_path;
use serde::Serialize;

use crate::report::dupes_grouping::AttributedCloneGroup;

/// Per-action wire shape attached to each [`CloneGroupFinding`] and
/// [`AttributedCloneGroupFinding`]. Mirrors the action types previously
/// emitted by `inject_dupes_actions::build_clone_group_actions` in
/// `crates/cli/src/report/json.rs`: `extract-shared` plus `suppress-line`.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CloneGroupAction {
    /// Action type identifier.
    #[serde(rename = "type")]
    pub kind: CloneGroupActionType,
    /// Whether `fallow fix` can auto-apply this action. Both variants are
    /// manual today; the field is non-singleton so a future auto-applier
    /// does not need a schema change.
    pub auto_fixable: bool,
    /// Human-readable description of the action.
    pub description: String,
    /// The inline comment to insert (e.g.,
    /// `// fallow-ignore-next-line code-duplication`). Present on
    /// `suppress-line`; absent on `extract-shared`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

/// Discriminant for [`CloneGroupAction::kind`]. Mirrors the action types
/// emitted by the legacy `build_clone_group_actions` walker.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum CloneGroupActionType {
    /// Extract the duplicated code into a shared function.
    ExtractShared,
    /// Suppress the finding with an inline `// fallow-ignore-next-line
    /// code-duplication` comment above the duplicated code.
    SuppressLine,
}

/// Per-action wire shape attached to each [`CloneFamilyFinding`]. Mirrors
/// the action types previously emitted by
/// `build_clone_family_actions`: `extract-shared`, one `apply-suggestion`
/// per [`RefactoringSuggestion`] on the family, and a trailing
/// `suppress-line`.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CloneFamilyAction {
    /// Action type identifier.
    #[serde(rename = "type")]
    pub kind: CloneFamilyActionType,
    /// Whether `fallow fix` can auto-apply this action. All three variants
    /// are manual today.
    pub auto_fixable: bool,
    /// Human-readable description of the action.
    pub description: String,
    /// Additional context. Present on `extract-shared` (explaining that
    /// the family's clone groups share the same files); absent otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// The inline comment to insert (e.g.,
    /// `// fallow-ignore-next-line code-duplication`). Present on
    /// `suppress-line` only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comment: Option<String>,
}

/// Discriminant for [`CloneFamilyAction::kind`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum CloneFamilyActionType {
    /// Extract the duplicated code blocks into a shared module.
    ExtractShared,
    /// Apply one of the family's [`RefactoringSuggestion`]s. One action
    /// per suggestion entry on the bare family.
    ApplySuggestion,
    /// Suppress with an inline `// fallow-ignore-next-line code-duplication`
    /// comment above the duplicated code.
    SuppressLine,
}

const SUPPRESS_COMMENT: &str = "// fallow-ignore-next-line code-duplication";
const SUPPRESS_DESCRIPTION: &str = "Suppress with an inline comment above the duplicated code";

/// Wire-shape envelope for a [`CloneGroup`] finding. Flattens the bare
/// group via `#[serde(flatten)]` and carries a typed `actions` array plus
/// the optional audit-mode `introduced` flag. Replaces the legacy
/// post-pass injection in `crates/cli/src/report/json.rs::inject_dupes_actions`.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CloneGroupFinding {
    /// The underlying clone group.
    #[serde(flatten)]
    pub group: CloneGroup,
    /// Suggested next steps: an `extract-shared` primary and a
    /// `suppress-line` secondary. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<CloneGroupAction>,
    /// Set by the audit pass when this clone group is introduced relative
    /// to the merge-base. `None` when serialized directly from Rust.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl CloneGroupFinding {
    /// Build the wrapper from a raw [`CloneGroup`], computing the typed
    /// `actions` array inline. `introduced` stays `None` and is set later
    /// by `annotate_dupes_json` if the audit pass runs.
    #[must_use]
    pub fn with_actions(group: CloneGroup) -> Self {
        let line_count = group.line_count;
        let instance_count = group.instances.len();
        let actions = vec![
            CloneGroupAction {
                kind: CloneGroupActionType::ExtractShared,
                auto_fixable: false,
                description: format!(
                    "Extract duplicated code ({line_count} lines, {instance_count} instance{}) into a shared function",
                    if instance_count == 1 { "" } else { "s" },
                ),
                comment: None,
            },
            CloneGroupAction {
                kind: CloneGroupActionType::SuppressLine,
                auto_fixable: false,
                description: SUPPRESS_DESCRIPTION.to_string(),
                comment: Some(SUPPRESS_COMMENT.to_string()),
            },
        ];
        Self {
            group,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`CloneFamily`] finding.
///
/// Unlike most `*Finding` wrappers this one is NOT `#[serde(flatten)]` over
/// the bare [`CloneFamily`], because the family's nested
/// `groups: Vec<CloneGroup>` field needs to carry the typed
/// [`CloneGroupFinding`] wrapper too (so every nested clone group gets its
/// own `actions[]` array, matching the legacy post-pass behavior; see issue
/// #393 regression test). The wire shape stays byte-identical to the
/// previous post-pass output. No `introduced` field because `fallow audit`
/// attributes clone groups (not families) when running against a base ref.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CloneFamilyFinding {
    /// The files involved in this family (sorted for stable output).
    #[serde(serialize_with = "serde_path::serialize_vec")]
    pub files: Vec<PathBuf>,
    /// Clone groups belonging to this family, each wrapped with typed
    /// `actions[]` so consumers that read `clone_families[].groups[]`
    /// directly see the same shape as the top-level `clone_groups[]`.
    pub groups: Vec<CloneGroupFinding>,
    /// Total number of duplicated lines across all groups.
    pub total_duplicated_lines: usize,
    /// Total number of duplicated tokens across all groups.
    pub total_duplicated_tokens: usize,
    /// Refactoring suggestions for this family.
    pub suggestions: Vec<RefactoringSuggestion>,
    /// Suggested next steps: an `extract-shared` primary, one
    /// `apply-suggestion` per [`RefactoringSuggestion`] on the family, and
    /// a trailing `suppress-line`. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<CloneFamilyAction>,
}

impl CloneFamilyFinding {
    /// Build the wrapper from a raw [`CloneFamily`], computing the typed
    /// `actions` array inline and wrapping each inner clone group with its
    /// own typed actions.
    #[must_use]
    pub fn with_actions(family: CloneFamily) -> Self {
        let actions = build_clone_family_actions(
            &family.groups,
            family.total_duplicated_lines,
            &family.suggestions,
        );
        Self {
            files: family.files,
            groups: family
                .groups
                .into_iter()
                .map(CloneGroupFinding::with_actions)
                .collect(),
            total_duplicated_lines: family.total_duplicated_lines,
            total_duplicated_tokens: family.total_duplicated_tokens,
            suggestions: family.suggestions,
            actions,
        }
    }
}

fn build_clone_family_actions(
    groups: &[CloneGroup],
    total_duplicated_lines: usize,
    suggestions: &[RefactoringSuggestion],
) -> Vec<CloneFamilyAction> {
    let group_count = groups.len();
    let mut actions = Vec::with_capacity(2 + suggestions.len());
    actions.push(CloneFamilyAction {
        kind: CloneFamilyActionType::ExtractShared,
        auto_fixable: false,
        description: format!(
            "Extract {group_count} duplicated code block{} ({total_duplicated_lines} lines) into a shared module",
            if group_count == 1 { "" } else { "s" },
        ),
        note: Some(
            "These clone groups share the same files, indicating a structural relationship; refactor together"
                .to_string(),
        ),
        comment: None,
    });
    for suggestion in suggestions {
        actions.push(CloneFamilyAction {
            kind: CloneFamilyActionType::ApplySuggestion,
            auto_fixable: false,
            description: suggestion.description.clone(),
            note: None,
            comment: None,
        });
    }
    actions.push(CloneFamilyAction {
        kind: CloneFamilyActionType::SuppressLine,
        auto_fixable: false,
        description: SUPPRESS_DESCRIPTION.to_string(),
        note: None,
        comment: Some(SUPPRESS_COMMENT.to_string()),
    });
    actions
}

/// Wire-shape envelope for an [`AttributedCloneGroup`] finding (per-bucket
/// duplication attribution emitted under `fallow dupes --group-by`).
/// Flattens the attributed group and carries the same typed
/// `CloneGroupAction` array as [`CloneGroupFinding`]; no `introduced`
/// field because `fallow audit` does not run on grouped output.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AttributedCloneGroupFinding {
    /// The underlying attributed clone group.
    #[serde(flatten)]
    pub group: AttributedCloneGroup,
    /// Suggested next steps. Always emitted.
    pub actions: Vec<CloneGroupAction>,
}

impl AttributedCloneGroupFinding {
    /// Build the wrapper from an [`AttributedCloneGroup`], computing the
    /// typed `actions` array inline from the attributed group's
    /// `line_count` and instance count.
    #[must_use]
    pub fn with_actions(group: AttributedCloneGroup) -> Self {
        let line_count = group.line_count;
        let instance_count = group.instances.len();
        let actions = vec![
            CloneGroupAction {
                kind: CloneGroupActionType::ExtractShared,
                auto_fixable: false,
                description: format!(
                    "Extract duplicated code ({line_count} lines, {instance_count} instance{}) into a shared function",
                    if instance_count == 1 { "" } else { "s" },
                ),
                comment: None,
            },
            CloneGroupAction {
                kind: CloneGroupActionType::SuppressLine,
                auto_fixable: false,
                description: SUPPRESS_DESCRIPTION.to_string(),
                comment: Some(SUPPRESS_COMMENT.to_string()),
            },
        ];
        Self { group, actions }
    }
}

/// Wire-shape payload for `fallow dupes --format json` (the body that
/// flattens into [`crate::output_envelope::DupesOutput`] and is also
/// emitted under the `dupes` / `duplication` key inside the combined and
/// audit envelopes).
///
/// Mirrors [`DuplicationReport`] field-for-field, except `clone_groups`
/// and `clone_families` carry the typed wrapper envelopes instead of bare
/// findings, so the schema (and any TS / agent consumer) sees the typed
/// `actions[]` natively.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DupesReportPayload {
    /// All detected clone groups, each wrapped with typed actions.
    pub clone_groups: Vec<CloneGroupFinding>,
    /// Clone families, each wrapped with typed actions. Inner `groups`
    /// inside each [`CloneFamilyFinding`] are themselves wrapped as
    /// [`CloneGroupFinding`] entries carrying their own `actions[]` (and
    /// optional audit-mode `introduced` flag), so JSON-Schema strict
    /// consumers and TS consumers reading `clone_families[].groups[]` see
    /// the same shape as the top-level `clone_groups[]` array (preserves
    /// the issue #393 regression contract).
    pub clone_families: Vec<CloneFamilyFinding>,
    /// Mirrored directory pairs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mirrored_directories: Vec<MirroredDirectory>,
    /// Aggregate duplication statistics.
    pub stats: DuplicationStats,
}

impl DupesReportPayload {
    /// Build the payload from a bare [`DuplicationReport`]. Wraps each
    /// clone group and family with its typed actions; clones the
    /// `mirrored_directories` and `stats` through unchanged.
    #[must_use]
    pub fn from_report(report: &DuplicationReport) -> Self {
        Self {
            clone_groups: report
                .clone_groups
                .iter()
                .cloned()
                .map(CloneGroupFinding::with_actions)
                .collect(),
            clone_families: report
                .clone_families
                .iter()
                .cloned()
                .map(CloneFamilyFinding::with_actions)
                .collect(),
            mirrored_directories: report.mirrored_directories.clone(),
            stats: report.stats.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use fallow_core::duplicates::{
        CloneInstance, DuplicationStats, RefactoringKind, RefactoringSuggestion,
    };

    use super::*;

    fn instance(path: &str) -> CloneInstance {
        CloneInstance {
            file: PathBuf::from(path),
            start_line: 1,
            end_line: 10,
            start_col: 0,
            end_col: 0,
            fragment: String::new(),
        }
    }

    fn group(instances: usize) -> CloneGroup {
        CloneGroup {
            instances: (0..instances)
                .map(|i| instance(&format!("/root/file_{i}.ts")))
                .collect(),
            token_count: 100,
            line_count: 20,
        }
    }

    #[test]
    fn clone_group_finding_position_0_is_extract_shared() {
        let finding = CloneGroupFinding::with_actions(group(2));
        assert_eq!(finding.actions.len(), 2);
        assert_eq!(
            finding.actions[0].kind,
            CloneGroupActionType::ExtractShared,
            "position 0 of a clone group must be `extract-shared` (jq scripts read .actions[0].type)",
        );
        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
        assert!(finding.introduced.is_none());
    }

    #[test]
    fn clone_group_finding_description_pluralises_instance_count() {
        let single = CloneGroupFinding::with_actions(group(1));
        assert!(
            single.actions[0].description.contains("1 instance"),
            "single instance should be singular: {}",
            single.actions[0].description
        );
        assert!(
            !single.actions[0].description.contains("1 instances"),
            "single instance must not pluralise: {}",
            single.actions[0].description
        );
        let multi = CloneGroupFinding::with_actions(group(3));
        assert!(
            multi.actions[0].description.contains("3 instances"),
            "multiple instances must pluralise: {}",
            multi.actions[0].description
        );
    }

    #[test]
    fn clone_family_finding_position_0_is_extract_shared_then_suggestions_then_suppress() {
        let family = CloneFamily {
            files: vec![PathBuf::from("/root/a.ts"), PathBuf::from("/root/b.ts")],
            groups: vec![group(2), group(2)],
            total_duplicated_lines: 40,
            total_duplicated_tokens: 200,
            suggestions: vec![
                RefactoringSuggestion {
                    kind: RefactoringKind::ExtractFunction,
                    description: "Extract helper".to_string(),
                    estimated_savings: 10,
                },
                RefactoringSuggestion {
                    kind: RefactoringKind::ExtractModule,
                    description: "Extract module".to_string(),
                    estimated_savings: 30,
                },
            ],
        };
        let finding = CloneFamilyFinding::with_actions(family);
        // 1 extract-shared + 2 apply-suggestion + 1 suppress-line = 4
        assert_eq!(finding.actions.len(), 4);
        assert_eq!(
            finding.actions[0].kind,
            CloneFamilyActionType::ExtractShared,
            "position 0 of a clone family must be `extract-shared`",
        );
        assert_eq!(
            finding.actions[1].kind,
            CloneFamilyActionType::ApplySuggestion
        );
        assert_eq!(finding.actions[1].description, "Extract helper");
        assert_eq!(
            finding.actions[2].kind,
            CloneFamilyActionType::ApplySuggestion
        );
        assert_eq!(finding.actions[2].description, "Extract module");
        assert_eq!(finding.actions[3].kind, CloneFamilyActionType::SuppressLine);
        // Issue #393 regression: every nested clone group inside a family
        // must also carry its own typed actions array.
        assert_eq!(finding.groups.len(), 2);
        for inner in &finding.groups {
            assert_eq!(inner.actions.len(), 2);
            assert_eq!(inner.actions[0].kind, CloneGroupActionType::ExtractShared);
            assert_eq!(inner.actions[1].kind, CloneGroupActionType::SuppressLine);
        }
    }

    #[test]
    fn clone_family_finding_with_no_suggestions_emits_two_actions() {
        let family = CloneFamily {
            files: vec![PathBuf::from("/root/a.ts")],
            groups: vec![group(2)],
            total_duplicated_lines: 20,
            total_duplicated_tokens: 100,
            suggestions: Vec::new(),
        };
        let finding = CloneFamilyFinding::with_actions(family);
        assert_eq!(finding.actions.len(), 2);
        assert_eq!(
            finding.actions[0].kind,
            CloneFamilyActionType::ExtractShared
        );
        assert_eq!(finding.actions[1].kind, CloneFamilyActionType::SuppressLine);
    }

    #[test]
    fn payload_from_report_wraps_all_findings() {
        let report = DuplicationReport {
            clone_groups: vec![group(2), group(3)],
            clone_families: vec![CloneFamily {
                files: vec![PathBuf::from("/root/a.ts")],
                groups: vec![group(2)],
                total_duplicated_lines: 20,
                total_duplicated_tokens: 100,
                suggestions: Vec::new(),
            }],
            mirrored_directories: Vec::new(),
            stats: DuplicationStats::default(),
        };
        let payload = DupesReportPayload::from_report(&report);
        assert_eq!(payload.clone_groups.len(), 2);
        assert_eq!(payload.clone_families.len(), 1);
        // Sanity check: every group has the canonical 2-action array.
        for finding in &payload.clone_groups {
            assert_eq!(finding.actions.len(), 2);
        }
        // Sanity check: family with zero suggestions has 2 actions.
        assert_eq!(payload.clone_families[0].actions.len(), 2);
    }

    #[test]
    fn attributed_clone_group_finding_actions_match_clone_group_shape() {
        use crate::report::dupes_grouping::AttributedInstance;
        let attributed = AttributedCloneGroup {
            primary_owner: "src".to_string(),
            token_count: 100,
            line_count: 20,
            instances: vec![
                AttributedInstance {
                    instance: instance("/root/src/a.ts"),
                    owner: "src".to_string(),
                },
                AttributedInstance {
                    instance: instance("/root/src/b.ts"),
                    owner: "src".to_string(),
                },
            ],
        };
        let finding = AttributedCloneGroupFinding::with_actions(attributed);
        assert_eq!(finding.actions.len(), 2);
        assert_eq!(finding.actions[0].kind, CloneGroupActionType::ExtractShared);
        assert_eq!(finding.actions[1].kind, CloneGroupActionType::SuppressLine);
    }
}