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
24pub 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
41pub(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 analysis = 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.find_duplicates_touching_files_with_defaults(
86 &dupes_config,
87 &changed_files,
88 cache_dir,
89 )
90 } else {
91 session.find_duplicates_with_defaults(&dupes_config, cache_dir)
92 };
93
94 resolved.ensure_not_cancelled("the duplication report")?;
97 run_duplication_report_with_session(
98 options,
99 resolved,
100 session,
101 DuplicationRunReport {
102 report: analysis.report,
103 ignored_clone_groups: analysis.ignored_clone_groups,
104 },
105 &change_scope,
106 start,
107 )
108}
109
110pub(super) struct DuplicationRunReport {
112 pub report: fallow_engine::duplicates::DuplicationReport,
114 pub ignored_clone_groups: Vec<fallow_engine::duplicates::IgnoredCloneGroup>,
116}
117
118pub(super) fn run_duplication_report_with_session(
119 options: &DuplicationOptions,
120 resolved: &ProgrammaticAnalysisContext,
121 session: &AnalysisSession,
122 run_report: DuplicationRunReport,
123 change_scope: &ChangeScope,
124 start: Instant,
125) -> ProgrammaticResult<DuplicationProgrammaticOutput> {
126 let DuplicationRunReport {
127 mut report,
128 ignored_clone_groups,
129 } = run_report;
130 let dupes_config = build_dupes_config(options, &session.config().duplicates);
131 let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
132 fallow_engine::duplicates::apply_scope(
133 &mut report,
134 &fallow_engine::duplicates::DuplicationScope {
135 changes: Some(change_scope),
136 diff: resolved.diff.as_ref(),
137 workspace_roots: workspace_roots.as_ref(),
138 },
139 session.root(),
140 );
141 if let Some(top) = options.top {
142 fallow_engine::duplicates::apply_top(&mut report, top, session.root());
143 }
144
145 let root = session.root();
146 let payload = DupesReportPayload::from_report_with_fragments(
147 &report,
148 options.include_fragments.unwrap_or(true),
149 );
150 let clone_fingerprints = payload
151 .clone_groups
152 .iter()
153 .map(|group| group.fingerprint.as_str())
154 .collect::<Vec<_>>();
155 let next_steps = build_dupes_next_steps(DupesNextStepsInput {
156 suggestions_enabled: suggestions_enabled(),
157 clone_fingerprints: &clone_fingerprints,
158 offer_setup: setup_pointer_applicable(root),
159 impact_digest: None,
160 audit_changed: audit_changed_applicable(root),
161 baseline_recheck: None,
162 });
163 let mut output: DupesOutput<DupesReportPayload, DuplicationGroup> =
164 build_dupes_output(DupesOutputInput {
165 gate_outcomes: None,
166 request_outcomes: resolved.request_outcomes(),
167 schema_version: DUPES_PROGRAMMATIC_SCHEMA_VERSION,
168 version: env!("CARGO_PKG_VERSION").to_string(),
169 elapsed: start.elapsed(),
170 report: payload,
171 clone_groups_shown: report.clone_groups_shown(),
172 clone_groups_omitted: report.clone_groups_omitted(),
173 clone_families_shown: report.clone_families_shown(),
174 clone_families_omitted: report.clone_families_omitted(),
175 grouped_by: None,
176 total_issues: None,
177 groups: None,
178 baseline_staleness: None,
181 meta: resolved.explain_enabled().then(dupes_meta),
182 workspace_diagnostics: session.workspace_diagnostics().to_vec(),
183 next_steps,
184 });
185 output.package_baselines = change_scope.package_baselines();
186 Ok(DuplicationProgrammaticOutput {
187 output,
188 root: session.root().to_path_buf(),
189 threshold: dupes_config.threshold,
190 ignored_clone_groups,
191 telemetry_analysis_run_id: None,
192 })
193}
194
195pub(super) fn load_duplication_session(
198 options: &DuplicationOptions,
199 resolved: &ProgrammaticAnalysisContext,
200 run: &ResolvedRun,
201) -> ProgrammaticResult<AnalysisSession> {
202 let duplication = crate::run::runnable(run, PlannedAnalysis::Duplication)?;
203 let session = crate::run::open_session_adjusted(&duplication, |config| {
204 config.duplicates = build_dupes_config(options, &config.duplicates);
205 })?;
206 Ok(super::dead_code::attach_cancellation(session, resolved))
207}
208
209pub(super) fn build_dupes_config(
212 options: &DuplicationOptions,
213 config: &DuplicatesConfig,
214) -> DuplicatesConfig {
215 config.merged_for_selected_run(&fallow_config::DupesInputs {
216 mode: options.mode.map(duplication_mode_to_config),
217 near: options.near,
218 min_tokens: options.min_tokens,
219 min_lines: options.min_lines,
220 min_occurrences: options.min_occurrences,
221 threshold: options.threshold,
222 skip_local: options.skip_local,
223 cross_language: options.cross_language,
224 ignore_imports: options.ignore_imports,
225 ignore_symlinks: options.ignore_symlinks,
226 })
227}
228
229const fn duplication_mode_to_config(mode: DuplicationMode) -> DetectionMode {
230 match mode {
231 DuplicationMode::Strict => DetectionMode::Strict,
232 DuplicationMode::Mild => DetectionMode::Mild,
233 DuplicationMode::Weak => DetectionMode::Weak,
234 DuplicationMode::Semantic => DetectionMode::Semantic,
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 #[test]
243 fn duplication_options_override_near_and_preserve_reviewed_clones() {
244 let config = DuplicatesConfig {
245 near: true,
246 ignored_clones: vec!["dup:12345678:2".to_string()],
247 ..DuplicatesConfig::default()
248 };
249 let options = DuplicationOptions {
250 near: Some(false),
251 ..DuplicationOptions::default()
252 };
253
254 let merged = build_dupes_config(&options, &config);
255
256 assert!(!merged.near);
257 assert_eq!(merged.ignored_clones, config.ignored_clones);
258 }
259}