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_in_context(options, &resolved, &run)
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))
49}
50
51fn run_duplication_inner(
52    options: &DuplicationOptions,
53    resolved: &ProgrammaticAnalysisContext,
54    run: &ResolvedRun,
55) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
56    let start = Instant::now();
57    resolved.ensure_not_cancelled("config load and file discovery")?;
58    let session = load_duplication_session(options, resolved, run)?;
59    super::dead_code::resolve_package_map_before_analysis(resolved, &session)?;
60    run_duplication_with_session(options, resolved, &session, None, start)
61}
62
63pub(super) fn run_duplication_with_session(
64    options: &DuplicationOptions,
65    resolved: &ProgrammaticAnalysisContext,
66    session: &AnalysisSession,
67    changed_files: Option<&FxHashSet<std::path::PathBuf>>,
68    start: Instant,
69) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
70    resolved.ensure_not_cancelled("duplication detection")?;
71    let dupes_config = build_dupes_config(options, &session.config().duplicates);
72    let resolved_changed_files = if changed_files.is_some() {
73        None
74    } else {
75        changed_files_for_run(resolved)?
76    };
77    let global_files = changed_files.or(resolved_changed_files.as_ref());
78    let change_scope =
79        resolved.change_scope(global_files, session.config(), session.workspaces())?;
80    let cache_dir = (!resolved.no_cache).then_some(session.config().cache_dir.as_path());
81    let report = if let Some(changed_files) = global_files {
82        resolved
83            .measure_changed_since_scope(session.files().iter().map(|file| file.path.as_path()));
84        let changed_files = changed_files.iter().cloned().collect::<Vec<_>>();
85        session
86            .find_duplicates_touching_files_with_defaults(&dupes_config, &changed_files, cache_dir)
87            .report
88    } else {
89        session
90            .find_duplicates_with_defaults(&dupes_config, cache_dir)
91            .report
92    };
93
94    // Duplication detection cannot fail, so a token set while it ran has to be
95    // reported here rather than dressed up as a complete report.
96    resolved.ensure_not_cancelled("the duplication report")?;
97    run_duplication_report_with_session(options, resolved, session, report, &change_scope, start)
98}
99
100pub(super) fn run_duplication_report_with_session(
101    options: &DuplicationOptions,
102    resolved: &ProgrammaticAnalysisContext,
103    session: &AnalysisSession,
104    mut report: fallow_engine::duplicates::DuplicationReport,
105    change_scope: &ChangeScope,
106    start: Instant,
107) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
108    let dupes_config = build_dupes_config(options, &session.config().duplicates);
109    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
110    fallow_engine::duplicates::apply_scope(
111        &mut report,
112        &fallow_engine::duplicates::DuplicationScope {
113            changes: Some(change_scope),
114            diff: resolved.diff.as_ref(),
115            workspace_roots: workspace_roots.as_deref(),
116        },
117        session.root(),
118    );
119    if let Some(top) = options.top {
120        fallow_engine::duplicates::apply_top(&mut report, top, session.root());
121    }
122
123    let root = session.root();
124    let payload = DupesReportPayload::from_report_with_fragments(
125        &report,
126        options.include_fragments.unwrap_or(true),
127    );
128    let clone_fingerprints = payload
129        .clone_groups
130        .iter()
131        .map(|group| group.fingerprint.as_str())
132        .collect::<Vec<_>>();
133    let next_steps = build_dupes_next_steps(DupesNextStepsInput {
134        suggestions_enabled: suggestions_enabled(),
135        clone_fingerprints: &clone_fingerprints,
136        offer_setup: setup_pointer_applicable(root),
137        impact_digest: None,
138        audit_changed: audit_changed_applicable(root),
139        baseline_recheck: None,
140    });
141    let mut output: DupesOutput<DupesReportPayload, DuplicationGroup> =
142        build_dupes_output(DupesOutputInput {
143            gate_outcomes: None,
144            request_outcomes: resolved.request_outcomes(),
145            schema_version: DUPES_PROGRAMMATIC_SCHEMA_VERSION,
146            version: env!("CARGO_PKG_VERSION").to_string(),
147            elapsed: start.elapsed(),
148            report: payload,
149            clone_groups_shown: report.clone_groups_shown(),
150            clone_groups_omitted: report.clone_groups_omitted(),
151            clone_families_shown: report.clone_families_shown(),
152            clone_families_omitted: report.clone_families_omitted(),
153            grouped_by: None,
154            total_issues: None,
155            groups: None,
156            // The programmatic duplication route loads no baseline, so there is
157            // no staleness to report.
158            baseline_staleness: None,
159            meta: resolved.explain_enabled().then(dupes_meta),
160            workspace_diagnostics: session.workspace_diagnostics().to_vec(),
161            next_steps,
162        });
163    output.package_baselines = change_scope.package_baselines();
164    Ok(DuplicationProgrammaticOutput {
165        output,
166        root: session.root().to_path_buf(),
167        threshold: dupes_config.threshold,
168        telemetry_analysis_run_id: None,
169    })
170}
171
172/// Open the duplication session of `run`, with the detector options of
173/// `options`.
174pub(super) fn load_duplication_session(
175    options: &DuplicationOptions,
176    resolved: &ProgrammaticAnalysisContext,
177    run: &ResolvedRun,
178) -> ProgrammaticResult<AnalysisSession> {
179    let duplication = crate::run::runnable(run, PlannedAnalysis::Duplication)?;
180    let session = crate::run::open_session_adjusted(&duplication, |config| {
181        config.duplicates = build_dupes_config(options, &config.duplicates);
182    })?;
183    Ok(super::dead_code::attach_cancellation(session, resolved))
184}
185
186/// The duplication config of a programmatic run: each option over the
187/// config, through [`DuplicatesConfig::merged_for_selected_run`].
188pub(super) fn build_dupes_config(
189    options: &DuplicationOptions,
190    config: &DuplicatesConfig,
191) -> DuplicatesConfig {
192    config.merged_for_selected_run(&fallow_config::DupesInputs {
193        mode: options.mode.map(duplication_mode_to_config),
194        near: options.near,
195        min_tokens: options.min_tokens,
196        min_lines: options.min_lines,
197        min_occurrences: options.min_occurrences,
198        threshold: options.threshold,
199        skip_local: options.skip_local,
200        cross_language: options.cross_language,
201        ignore_imports: options.ignore_imports,
202        ignore_symlinks: options.ignore_symlinks,
203    })
204}
205
206const fn duplication_mode_to_config(mode: DuplicationMode) -> DetectionMode {
207    match mode {
208        DuplicationMode::Strict => DetectionMode::Strict,
209        DuplicationMode::Mild => DetectionMode::Mild,
210        DuplicationMode::Weak => DetectionMode::Weak,
211        DuplicationMode::Semantic => DetectionMode::Semantic,
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    #[test]
220    fn duplication_options_override_near_and_preserve_reviewed_clones() {
221        let config = DuplicatesConfig {
222            near: true,
223            ignored_clones: vec!["dup:12345678:2".to_string()],
224            ..DuplicatesConfig::default()
225        };
226        let options = DuplicationOptions {
227            near: Some(false),
228            ..DuplicationOptions::default()
229        };
230
231        let merged = build_dupes_config(&options, &config);
232
233        assert!(!merged.near);
234        assert_eq!(merged.ignored_clones, config.ignored_clones);
235    }
236}