Skip to main content

fallow_engine/
session_duplication.rs

1//! Duplication runs of an [`AnalysisSession`].
2//!
3//! Duplication analyzes the files of its own production mode, as `fallow
4//! dupes` does. A config can give dead code and duplication different modes,
5//! for example `{"production": {"deadCode": true, "dupes": false}}`. The
6//! session config then holds the dead-code mode, and the session walks the
7//! files of the duplication mode on the first duplication call.
8
9use std::path::{Path, PathBuf};
10use std::sync::OnceLock;
11
12use fallow_config::{DuplicatesConfig, ResolvedConfig};
13use fallow_types::discover::DiscoveredFile;
14
15use super::AnalysisSession;
16use crate::project_analysis::{
17    ProjectAnalysisArtifactOptions, ProjectAnalysisArtifacts, ProjectAnalysisOutput,
18};
19use crate::project_config::{DuplicationScope, resolve_with_env_from};
20use crate::results::DuplicationAnalysis;
21use crate::{EngineResult, duplicates};
22
23/// The files that duplication analyzes for one session.
24#[derive(Debug)]
25pub(super) struct DuplicationFiles {
26    scope: DuplicationScope,
27    /// The resolved config of [`DuplicationScope::Own`]. A discovery refresh
28    /// keeps it, because the config file did not change.
29    config: OnceLock<ResolvedConfig>,
30    /// The walked files of [`DuplicationScope::Own`].
31    files: OnceLock<Vec<DiscoveredFile>>,
32}
33
34impl DuplicationFiles {
35    pub(super) const fn new(scope: DuplicationScope) -> Self {
36        Self {
37            scope,
38            config: OnceLock::new(),
39            files: OnceLock::new(),
40        }
41    }
42
43    /// Drop the walked files, so that the next duplication call walks the
44    /// project again.
45    pub(super) fn forget_files(&mut self) {
46        self.files.take();
47    }
48}
49
50impl AnalysisSession {
51    /// The resolved config of the duplication mode, when it differs from the
52    /// mode of the session config.
53    pub(crate) fn own_duplication_config(&self) -> Option<&ResolvedConfig> {
54        let DuplicationScope::Own {
55            config,
56            options,
57            env,
58            given,
59        } = &self.duplication.scope
60        else {
61            return None;
62        };
63        Some(self.duplication.config.get_or_init(|| {
64            let mut resolved =
65                resolve_with_env_from((**config).clone(), &self.config.root, *options, env);
66            given.apply(&mut resolved);
67            resolved
68        }))
69    }
70
71    /// The files of the production mode of duplication.
72    fn duplication_files(&self) -> &[DiscoveredFile] {
73        let Some(resolved) = self.own_duplication_config() else {
74            return self.files();
75        };
76        self.duplication.files.get_or_init(|| {
77            crate::discover::prepare_analysis_discovery_with_workspaces(
78                resolved,
79                &self.workspaces,
80                0.0,
81            )
82            .into_files()
83        })
84    }
85
86    /// Run dead-code and duplication analysis for this session.
87    ///
88    /// When `retain_complexity_artifacts` is true, the dead-code result keeps
89    /// parser artifacts needed by editor overlays such as inline complexity.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if dead-code parsing or analysis fails.
94    pub fn analyze_project_with(
95        &self,
96        duplicates_config: &DuplicatesConfig,
97        retain_complexity_artifacts: bool,
98    ) -> EngineResult<ProjectAnalysisOutput> {
99        self.analyze_project_with_artifacts(
100            duplicates_config,
101            ProjectAnalysisArtifactOptions {
102                retain_complexity_artifacts,
103                ..ProjectAnalysisArtifactOptions::default()
104            },
105        )
106        .map(ProjectAnalysisArtifacts::into_output)
107    }
108
109    /// Run dead-code and duplication analysis with retained session reuse data.
110    ///
111    /// This is the engine-owned project artifact boundary for callers that need
112    /// to hand one analysis result across audit, decision, editor, or follow-up
113    /// analysis surfaces without rediscovering session metadata.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error if dead-code parsing or analysis fails.
118    pub fn analyze_project_with_artifacts(
119        &self,
120        duplicates_config: &DuplicatesConfig,
121        options: ProjectAnalysisArtifactOptions,
122    ) -> EngineResult<ProjectAnalysisArtifacts> {
123        self.ensure_not_cancelled("duplication detection")?;
124        let cache_dir = (!self.config.no_cache).then_some(self.config.cache_dir.as_path());
125        let duplication = if let Some(changed_files) = options.changed_files.as_ref() {
126            let changed_files = changed_files.iter().cloned().collect::<Vec<_>>();
127            self.find_duplicates_touching_files_with_defaults(
128                duplicates_config,
129                &changed_files,
130                cache_dir,
131            )
132        } else {
133            self.find_duplicates_with_defaults(duplicates_config, cache_dir)
134        };
135        // Duplication detection is infallible, so a token set while it ran can
136        // only be reported here, before its report is handed on as a complete
137        // one.
138        self.ensure_not_cancelled("the dead-code half of project analysis")?;
139        let source_fingerprints = options
140            .collect_source_fingerprints
141            .then(|| self.source_fingerprints());
142        Ok(ProjectAnalysisArtifacts {
143            dead_code: self.analyze_dead_code_with_artifacts(
144                options.retain_complexity_artifacts,
145                options.retain_graph,
146            )?,
147            duplication: duplication.report,
148            ignored_clone_groups: duplication.ignored_clone_groups,
149            changed_files: options.changed_files,
150            source_fingerprints,
151        })
152    }
153
154    /// Run duplication detection and return report sidecar metadata.
155    #[must_use]
156    pub fn find_duplicates_with_defaults(
157        &self,
158        config: &DuplicatesConfig,
159        cache_dir: Option<&Path>,
160    ) -> DuplicationAnalysis {
161        #[cfg(any(test, feature = "testing"))]
162        crate::resolved_run::testing::duplication_runs::record(&self.config.root);
163        duplicates::find_duplicates_with_defaults(
164            &self.config.root,
165            self.duplication_files(),
166            config,
167            cache_dir,
168        )
169    }
170
171    /// Run focused duplication detection for a changed-file set.
172    #[must_use]
173    pub fn find_duplicates_touching_files_with_defaults(
174        &self,
175        config: &DuplicatesConfig,
176        changed_files: &[PathBuf],
177        cache_dir: Option<&Path>,
178    ) -> DuplicationAnalysis {
179        #[cfg(any(test, feature = "testing"))]
180        crate::resolved_run::testing::duplication_runs::record(&self.config.root);
181        duplicates::find_duplicates_touching_files_with_defaults(
182            &self.config.root,
183            self.duplication_files(),
184            config,
185            changed_files,
186            cache_dir,
187        )
188    }
189}