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            .report
133        } else {
134            self.find_duplicates_with_defaults(duplicates_config, cache_dir)
135                .report
136        };
137        // Duplication detection is infallible, so a token set while it ran can
138        // only be reported here, before its report is handed on as a complete
139        // one.
140        self.ensure_not_cancelled("the dead-code half of project analysis")?;
141        let source_fingerprints = options
142            .collect_source_fingerprints
143            .then(|| self.source_fingerprints());
144        Ok(ProjectAnalysisArtifacts {
145            dead_code: self.analyze_dead_code_with_artifacts(
146                options.retain_complexity_artifacts,
147                options.retain_graph,
148            )?,
149            duplication,
150            changed_files: options.changed_files,
151            source_fingerprints,
152        })
153    }
154
155    /// Run duplication detection and return report sidecar metadata.
156    #[must_use]
157    pub fn find_duplicates_with_defaults(
158        &self,
159        config: &DuplicatesConfig,
160        cache_dir: Option<&Path>,
161    ) -> DuplicationAnalysis {
162        #[cfg(any(test, feature = "testing"))]
163        crate::resolved_run::testing::duplication_runs::record(&self.config.root);
164        duplicates::find_duplicates_with_defaults(
165            &self.config.root,
166            self.duplication_files(),
167            config,
168            cache_dir,
169        )
170    }
171
172    /// Run focused duplication detection for a changed-file set.
173    #[must_use]
174    pub fn find_duplicates_touching_files_with_defaults(
175        &self,
176        config: &DuplicatesConfig,
177        changed_files: &[PathBuf],
178        cache_dir: Option<&Path>,
179    ) -> DuplicationAnalysis {
180        #[cfg(any(test, feature = "testing"))]
181        crate::resolved_run::testing::duplication_runs::record(&self.config.root);
182        duplicates::find_duplicates_touching_files_with_defaults(
183            &self.config.root,
184            self.duplication_files(),
185            config,
186            changed_files,
187            cache_dir,
188        )
189    }
190}