Skip to main content

fallow_api/runtime/
duplication.rs

1use std::time::Instant;
2
3use fallow_config::{DetectionMode, DuplicatesConfig, PlannedAnalysis};
4use fallow_engine::{change_scope::ChangeScope, session::AnalysisSession};
5use fallow_output::{
6    DUPES_PROGRAMMATIC_SCHEMA_VERSION, DupesNextStepsInput, DupesOutput, DupesOutputInput,
7    build_dupes_next_steps, build_dupes_output, dupes_meta,
8};
9use rustc_hash::FxHashSet;
10
11use crate::{
12    DupesReportPayload, DuplicationGroup, DuplicationMode, DuplicationOptions,
13    DuplicationProgrammaticOutput,
14    analysis_context::{
15        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
16        workspace_roots_for_session,
17    },
18    next_steps::{audit_changed_applicable, setup_pointer_applicable, suggestions_enabled},
19    run::{ProgrammaticEntry, ResolvedRun, resolve_programmatic_run},
20};
21
22use super::ProgrammaticResult;
23
24/// Run duplication analysis and return typed API output before serialization.
25///
26/// # Errors
27///
28/// Returns a structured programmatic error for invalid options, config load
29/// failures, or git changed-file failures.
30pub fn run_duplication(
31    options: &DuplicationOptions,
32) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
33    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
34    resolved.install(|| {
35        resolved.ensure_not_cancelled("config load and file discovery")?;
36        let run = resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::Duplication)?;
37        run_duplication_inner(options, &resolved, &run, true)
38    })
39}
40
41/// Run duplication analysis in a context and a run that the caller resolved.
42/// Audit uses this to hand the change scope of every section to itself.
43pub(super) fn run_duplication_in_context(
44    options: &DuplicationOptions,
45    resolved: &ProgrammaticAnalysisContext,
46    run: &ResolvedRun,
47) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
48    resolved.install(|| run_duplication_inner(options, resolved, run, false))
49}
50
51/// With `standalone`, the output also states each `duplicates.ignore` glob
52/// that matches no file. In an audit run, the dead-code section states them.
53fn run_duplication_inner(
54    options: &DuplicationOptions,
55    resolved: &ProgrammaticAnalysisContext,
56    run: &ResolvedRun,
57    standalone: bool,
58) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
59    let start = Instant::now();
60    resolved.ensure_not_cancelled("config load and file discovery")?;
61    let session = load_duplication_session(options, resolved, run)?;
62    super::dead_code::resolve_package_map_before_analysis(resolved, &session)?;
63    let mut result = run_duplication_with_session(options, resolved, &session, None, start)?;
64    if standalone {
65        result.output.workspace_diagnostics.extend(
66            fallow_engine::ignore_list_notes::duplicates_ignore_diagnostics(
67                session.config(),
68                session.files(),
69            ),
70        );
71    }
72    Ok(result)
73}
74
75pub(super) fn run_duplication_with_session(
76    options: &DuplicationOptions,
77    resolved: &ProgrammaticAnalysisContext,
78    session: &AnalysisSession,
79    changed_files: Option<&FxHashSet<std::path::PathBuf>>,
80    start: Instant,
81) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
82    resolved.ensure_not_cancelled("duplication detection")?;
83    let dupes_config = build_dupes_config(options, &session.config().duplicates);
84    let resolved_changed_files = if changed_files.is_some() {
85        None
86    } else {
87        changed_files_for_run(resolved)?
88    };
89    let global_files = changed_files.or(resolved_changed_files.as_ref());
90    let change_scope =
91        resolved.change_scope(global_files, session.config(), session.workspaces())?;
92    let cache_dir = (!resolved.no_cache).then_some(session.config().cache_dir.as_path());
93    let analysis = if let Some(changed_files) = global_files {
94        resolved
95            .measure_changed_since_scope(session.files().iter().map(|file| file.path.as_path()));
96        let changed_files = changed_files.iter().cloned().collect::<Vec<_>>();
97        session.find_duplicates_touching_files_with_defaults(
98            &dupes_config,
99            &changed_files,
100            cache_dir,
101        )
102    } else {
103        session.find_duplicates_with_defaults(&dupes_config, cache_dir)
104    };
105
106    // Duplication detection cannot fail, so a token set while it ran has to be
107    // reported here rather than dressed up as a complete report.
108    resolved.ensure_not_cancelled("the duplication report")?;
109    run_duplication_report_with_session(
110        options,
111        resolved,
112        session,
113        DuplicationRunReport {
114            report: analysis.report,
115            ignored_clone_groups: analysis.ignored_clone_groups,
116        },
117        &change_scope,
118        start,
119    )
120}
121
122/// The detector result that one duplication run reports.
123pub(super) struct DuplicationRunReport {
124    /// The clone groups after every filter.
125    pub report: fallow_engine::duplicates::DuplicationReport,
126    /// The clone groups that `duplicates.ignoredClones` hid.
127    pub ignored_clone_groups: Vec<fallow_engine::duplicates::IgnoredCloneGroup>,
128}
129
130pub(super) fn run_duplication_report_with_session(
131    options: &DuplicationOptions,
132    resolved: &ProgrammaticAnalysisContext,
133    session: &AnalysisSession,
134    run_report: DuplicationRunReport,
135    change_scope: &ChangeScope,
136    start: Instant,
137) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
138    let DuplicationRunReport {
139        mut report,
140        ignored_clone_groups,
141    } = run_report;
142    let dupes_config = build_dupes_config(options, &session.config().duplicates);
143    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
144    fallow_engine::duplicates::apply_scope(
145        &mut report,
146        &fallow_engine::duplicates::DuplicationScope {
147            changes: Some(change_scope),
148            diff: resolved.diff.as_ref(),
149            workspace_roots: workspace_roots.as_ref(),
150        },
151        session.root(),
152    );
153    if let Some(top) = options.top {
154        fallow_engine::duplicates::apply_top(&mut report, top, session.root());
155    }
156
157    let root = session.root();
158    let payload = DupesReportPayload::from_report_with_fragments(
159        &report,
160        options.include_fragments.unwrap_or(true),
161    );
162    let clone_fingerprints = payload
163        .clone_groups
164        .iter()
165        .map(|group| group.fingerprint.as_str())
166        .collect::<Vec<_>>();
167    let next_steps = build_dupes_next_steps(DupesNextStepsInput {
168        suggestions_enabled: suggestions_enabled(),
169        clone_fingerprints: &clone_fingerprints,
170        offer_setup: setup_pointer_applicable(root),
171        impact_digest: None,
172        audit_changed: audit_changed_applicable(root),
173        baseline_recheck: None,
174    });
175    let mut output: DupesOutput<DupesReportPayload, DuplicationGroup> =
176        build_dupes_output(DupesOutputInput {
177            gate_outcomes: None,
178            request_outcomes: resolved.request_outcomes(),
179            schema_version: DUPES_PROGRAMMATIC_SCHEMA_VERSION,
180            version: env!("CARGO_PKG_VERSION").to_string(),
181            elapsed: start.elapsed(),
182            report: payload,
183            clone_groups_shown: report.clone_groups_shown(),
184            clone_groups_omitted: report.clone_groups_omitted(),
185            clone_families_shown: report.clone_families_shown(),
186            clone_families_omitted: report.clone_families_omitted(),
187            grouped_by: None,
188            total_issues: None,
189            groups: None,
190            // The programmatic duplication route loads no baseline, so there is
191            // no staleness to report.
192            baseline_staleness: None,
193            meta: resolved.explain_enabled().then(dupes_meta),
194            workspace_diagnostics: session.workspace_diagnostics().to_vec(),
195            next_steps,
196        });
197    output.package_baselines = change_scope.package_baselines();
198    Ok(DuplicationProgrammaticOutput {
199        output,
200        root: session.root().to_path_buf(),
201        threshold: dupes_config.threshold,
202        ignored_clone_groups,
203        telemetry_analysis_run_id: None,
204    })
205}
206
207/// Open the duplication session of `run`, with the detector options of
208/// `options`.
209pub(super) fn load_duplication_session(
210    options: &DuplicationOptions,
211    resolved: &ProgrammaticAnalysisContext,
212    run: &ResolvedRun,
213) -> ProgrammaticResult<AnalysisSession> {
214    let duplication = crate::run::runnable(run, PlannedAnalysis::Duplication)?;
215    let session = crate::run::open_session_adjusted(&duplication, |config| {
216        config.duplicates = build_dupes_config(options, &config.duplicates);
217    })?;
218    Ok(super::dead_code::attach_cancellation(session, resolved))
219}
220
221/// The duplication config of a programmatic run: each option over the
222/// config, through [`DuplicatesConfig::merged_for_selected_run`].
223pub(super) fn build_dupes_config(
224    options: &DuplicationOptions,
225    config: &DuplicatesConfig,
226) -> DuplicatesConfig {
227    config.merged_for_selected_run(&fallow_config::DupesInputs {
228        mode: options.mode.map(duplication_mode_to_config),
229        near: options.near,
230        min_tokens: options.min_tokens,
231        min_lines: options.min_lines,
232        min_occurrences: options.min_occurrences,
233        threshold: options.threshold,
234        skip_local: options.skip_local,
235        cross_language: options.cross_language,
236        ignore_imports: options.ignore_imports,
237        ignore_symlinks: options.ignore_symlinks,
238    })
239}
240
241const fn duplication_mode_to_config(mode: DuplicationMode) -> DetectionMode {
242    match mode {
243        DuplicationMode::Strict => DetectionMode::Strict,
244        DuplicationMode::Mild => DetectionMode::Mild,
245        DuplicationMode::Weak => DetectionMode::Weak,
246        DuplicationMode::Semantic => DetectionMode::Semantic,
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn duplication_options_override_near_and_preserve_reviewed_clones() {
256        let config = DuplicatesConfig {
257            near: true,
258            ignored_clones: vec!["dup:12345678:2".to_string()],
259            ..DuplicatesConfig::default()
260        };
261        let options = DuplicationOptions {
262            near: Some(false),
263            ..DuplicationOptions::default()
264        };
265
266        let merged = build_dupes_config(&options, &config);
267
268        assert!(!merged.near);
269        assert_eq!(merged.ignored_clones, config.ignored_clones);
270    }
271}