Skip to main content

fallow_engine/resolved_run/
mod.rs

1//! The decisions of one run, each with the input that gave it.
2//!
3//! [`resolve_run`] takes the raw
4//! [`fallow_config::RunInputs`] of one surface, loads and validates the
5//! config, and decides the selection and the production mode of each analysis
6//! and each run setting. The result is one [`ResolvedRun`] with a resolved
7//! config per production mode.
8
9mod audit_base;
10mod env_policy;
11mod notices;
12#[cfg(any(test, feature = "testing"))]
13pub mod parity;
14mod pick;
15mod resolve;
16pub mod steps;
17#[cfg(any(test, feature = "testing"))]
18pub mod testing;
19mod type_aware;
20mod view;
21
22pub use audit_base::{AuditBaseDecision, decide_audit_base};
23pub use resolve::{
24    BaseConfig, BaseSide, EmptyCause, InputField, InputProblem, ResolveError, resolve_base_run,
25    resolve_base_run_with_head_decisions, resolve_run,
26};
27pub use type_aware::{TypeAwareConfigInput, TypeAwareSettings, decide_type_aware};
28
29use std::path::{Path, PathBuf};
30
31use fallow_config::{
32    AnalysisSelection, CommandKind, ConfigKey, EnvSnapshot, EnvVar, FallowConfig, PlannedAnalysis,
33    ResolvedConfig, SkipReason, Surface, WorkspaceInfo,
34};
35use fallow_types::output_format::OutputFormat;
36use fallow_types::sourced::Sourced;
37
38pub use pick::{PerAnalysis, ProductionInputs, decide_production};
39
40use crate::project_config::{
41    ConfigChainSnapshot, DuplicationScope, ProductionModes, ResolveOptions,
42};
43use crate::session::AnalysisSession;
44use crate::{EngineError, EngineResult};
45use steps::{GivenSettings, ModeEntry};
46
47/// Every decision of one run, with its cause. The fields are private and the
48/// type has no `Default`, no `Clone` and no `&mut self` method, so a run
49/// stays as the resolver made it.
50#[derive(Debug)]
51pub struct ResolvedRun {
52    surface: Surface,
53    command: CommandKind,
54    root: Sourced<PathBuf>,
55    config_file: Sourced<Option<PathBuf>>,
56    /// The bytes of the config file and its local `extends` chain at the load.
57    config_snapshot: ConfigChainSnapshot,
58    /// The validated config, before the production mode is flattened.
59    file: FallowConfig,
60    dead_code: AnalysisDecision,
61    duplication: AnalysisDecision,
62    health: AnalysisDecision,
63    /// The mode entry of the analyses that run without production mode.
64    off: Option<ModeEntry>,
65    /// The mode entry of the analyses that run in production mode.
66    on: Option<ModeEntry>,
67    settings: RunSettings,
68    /// The type-aware settings, or the variable whose value the run cannot
69    /// use.
70    type_aware: type_aware::TypeAwareDecision,
71    /// The settings that the surface gives and that win over the environment.
72    given: GivenSettings,
73    /// The environment snapshot of the run, without the variables that the
74    /// run does not read.
75    env: EnvSnapshot,
76    env_read: Vec<EnvVar>,
77    env_ignored: Vec<EnvVar>,
78    /// The config error that made the run use the default config.
79    fallback: Option<ResolveError>,
80    /// The notices of the run, as diagnostics at the root.
81    notices: Vec<fallow_config::WorkspaceDiagnostic>,
82    /// The raw inputs of the run, for the base side of a comparison.
83    inputs: Box<fallow_config::RunInputs>,
84}
85
86/// The decisions of one analysis.
87#[derive(Debug)]
88struct AnalysisDecision {
89    selection: Sourced<AnalysisSelection>,
90    production: Sourced<bool>,
91}
92
93/// The settings of one run. Every mode entry of the run has these values.
94#[derive(Debug)]
95pub struct RunSettings {
96    /// The number of worker threads.
97    pub threads: Sourced<usize>,
98    /// Whether the run bypasses the parse cache.
99    pub no_cache: Sourced<bool>,
100    /// Whether the `extends` chain of the config may name `https://` entries.
101    pub allow_remote_extends: Sourced<bool>,
102    /// The largest file to analyze, in bytes. `None` means no limit.
103    pub max_file_size_bytes: Sourced<Option<u64>>,
104    /// The cache directory.
105    pub cache_dir: Sourced<PathBuf>,
106    /// The size limit of the parse cache, in megabytes.
107    pub cache_max_size_mb: Sourced<Option<u32>>,
108    /// Whether the run reads `workspaces.changedSince`.
109    pub package_baselines: Sourced<bool>,
110    /// Whether dead code reports the unused exports of entry files.
111    pub include_entry_exports: Sourced<bool>,
112    /// The output format.
113    pub output: OutputFormat,
114    /// Whether the run suppresses progress output.
115    pub quiet: bool,
116}
117
118impl RunSettings {
119    const fn resolve_options(&self) -> ResolveOptions {
120        ResolveOptions {
121            output: self.output,
122            threads: *self.threads.value(),
123            no_cache: *self.no_cache.value(),
124            quiet: self.quiet,
125        }
126    }
127}
128
129/// One analysis of a run: it runs, or the run skips it with a reason.
130pub enum AnalysisSlot<'run> {
131    /// The analysis runs.
132    Runs(Runnable<'run>),
133    /// The run skips the analysis.
134    Skipped {
135        /// Why the run skips the analysis.
136        reason: &'run Sourced<AnalysisSelection>,
137    },
138}
139
140/// An analysis that runs. Only [`ResolvedRun::analysis`] makes one, so a
141/// skipped analysis has no config and no session.
142#[derive(Clone, Copy)]
143pub struct Runnable<'run> {
144    run: &'run ResolvedRun,
145    analysis: PlannedAnalysis,
146}
147
148/// The config key of a skip reason, as the config file spells it.
149const fn config_key_name(key: ConfigKey) -> &'static str {
150    match key {
151        ConfigKey::AuditDeadCode => "audit.deadCode",
152        ConfigKey::AuditHealth => "audit.health",
153        ConfigKey::AuditDupes => "audit.dupes",
154        ConfigKey::DuplicatesEnabled => "duplicates.enabled",
155    }
156}
157
158/// The config key that skips an analysis, if a config key skips it.
159fn skip_key(selection: AnalysisSelection) -> Option<ConfigKey> {
160    match selection {
161        AnalysisSelection::Skipped(SkipReason::Config(key)) => Some(key),
162        AnalysisSelection::Run | AnalysisSelection::Skipped(SkipReason::NotRequested) => None,
163    }
164}
165
166impl ResolvedRun {
167    /// The surface that started the run.
168    pub const fn surface(&self) -> Surface {
169        self.surface
170    }
171
172    /// The command of the run.
173    pub const fn command(&self) -> CommandKind {
174        self.command
175    }
176
177    /// The project root.
178    pub const fn root(&self) -> &Sourced<PathBuf> {
179        &self.root
180    }
181
182    /// The config file. `None` when the run uses the default config.
183    pub const fn config_file(&self) -> &Sourced<Option<PathBuf>> {
184        &self.config_file
185    }
186
187    /// The validated config, before the production mode is flattened.
188    pub const fn config(&self) -> &FallowConfig {
189        &self.file
190    }
191
192    const fn decision(&self, analysis: PlannedAnalysis) -> &AnalysisDecision {
193        match analysis {
194            PlannedAnalysis::DeadCode => &self.dead_code,
195            PlannedAnalysis::Duplication => &self.duplication,
196            PlannedAnalysis::Health => &self.health,
197        }
198    }
199
200    /// The analysis, when it runs, or the reason why the run skips it.
201    pub fn analysis(&self, analysis: PlannedAnalysis) -> AnalysisSlot<'_> {
202        let decision = self.decision(analysis);
203        if decision.selection.value().runs() {
204            AnalysisSlot::Runs(Runnable {
205                run: self,
206                analysis,
207            })
208        } else {
209            AnalysisSlot::Skipped {
210                reason: &decision.selection,
211            }
212        }
213    }
214
215    /// The production mode of the analysis.
216    pub const fn production(&self, analysis: PlannedAnalysis) -> &Sourced<bool> {
217        &self.decision(analysis).production
218    }
219
220    /// The production mode of each analysis.
221    pub fn production_modes(&self) -> ProductionModes {
222        ProductionModes {
223            dead_code: *self.dead_code.production.value(),
224            health: *self.health.production.value(),
225            dupes: *self.duplication.production.value(),
226        }
227    }
228
229    /// The settings of the run.
230    pub const fn settings(&self) -> &RunSettings {
231        &self.settings
232    }
233
234    /// The type-aware settings of the run.
235    ///
236    /// # Errors
237    ///
238    /// Returns [`ResolveError::Input`] with [`InputField::Env`] when
239    /// `FALLOW_TYPE_AWARE` or `FALLOW_TYPE_AWARE_REQUIRE` has a value that the
240    /// run cannot use. The run itself resolves, so a command that reads no
241    /// type-aware setting does not fail.
242    pub fn type_aware(&self) -> Result<&TypeAwareSettings, ResolveError> {
243        self.type_aware.result()
244    }
245
246    /// The base ref candidates of an audit run. A run of another command
247    /// has none.
248    #[must_use]
249    fn audit_base(&self) -> AuditBaseDecision {
250        decide_audit_base(&self.inputs)
251    }
252
253    /// The environment snapshot of the run. It holds only the variables that
254    /// the run reads on its surface and command.
255    pub const fn env(&self) -> &EnvSnapshot {
256        &self.env
257    }
258
259    /// The set variables that the run reads.
260    #[cfg(test)]
261    fn env_read(&self) -> &[EnvVar] {
262        &self.env_read
263    }
264
265    /// The set variables that the run ignores on its surface and command.
266    pub fn env_ignored(&self) -> &[EnvVar] {
267        &self.env_ignored
268    }
269
270    /// Whether the run uses the default config because the discovered config
271    /// failed to load, to validate or to give workspace metadata.
272    #[cfg(test)]
273    const fn fell_back(&self) -> bool {
274        self.fallback.is_some()
275    }
276
277    /// The error of the discovered config when the run uses the default
278    /// config because that config failed to load, to validate or to give
279    /// workspace metadata.
280    pub const fn fallback_error(&self) -> Option<&ResolveError> {
281        self.fallback.as_ref()
282    }
283
284    /// The notices of the run: the decisions of the resolver that a surface
285    /// shows as one note each, such as an environment variable whose value
286    /// the run ignores. Each session of the run also carries them in its
287    /// workspace diagnostics.
288    pub fn notices(&self) -> &[fallow_config::WorkspaceDiagnostic] {
289        &self.notices
290    }
291
292    /// Whether a config input changed since the load or during the load: the
293    /// bytes of the config file or of a file of its local `extends` chain, or
294    /// a plugin file, a rule pack or an `autoDiscover` directory that config
295    /// resolution read. A long-lived caller then resolves the run again.
296    pub fn sources_changed(&self) -> bool {
297        self.config_snapshot.changed()
298            || [self.off.as_ref(), self.on.as_ref()]
299                .into_iter()
300                .flatten()
301                .any(|entry| entry.inputs.snapshot() != entry.inputs_before_resolve)
302    }
303
304    /// The resources that the `plugins` config field names and that do not
305    /// resolve.
306    pub fn plugin_readiness(&self) -> Vec<fallow_config::ConfiguredPluginDiagnostic> {
307        fallow_config::diagnose_configured_external_plugins(self.root.value(), &self.file.plugins)
308    }
309
310    /// The mode entry of a production mode.
311    fn entry(&self, production: bool) -> Option<&ModeEntry> {
312        if production {
313            self.on.as_ref()
314        } else {
315            self.off.as_ref()
316        }
317    }
318}
319
320impl<'run> Runnable<'run> {
321    /// The analysis.
322    pub const fn analysis(&self) -> PlannedAnalysis {
323        self.analysis
324    }
325
326    /// The production mode of the analysis.
327    pub const fn production(&self) -> &'run Sourced<bool> {
328        self.run.production(self.analysis)
329    }
330
331    /// The run of the analysis.
332    pub const fn run(&self) -> &'run ResolvedRun {
333        self.run
334    }
335
336    fn entry(&self) -> &'run ModeEntry {
337        let Some(entry) = self.run.entry(*self.production().value()) else {
338            unreachable!("the resolver makes a mode entry for each analysis that runs");
339        };
340        entry
341    }
342
343    /// The resolved config of the production mode of the analysis.
344    pub fn config(&self) -> &'run ResolvedConfig {
345        &self.entry().config
346    }
347
348    /// The workspaces under the root.
349    pub fn workspaces(&self) -> &'run [WorkspaceInfo] {
350        &self.entry().workspaces
351    }
352
353    /// The diagnostics of the workspace discovery.
354    pub fn workspace_diagnostics(&self) -> &'run [fallow_config::WorkspaceDiagnostic] {
355        &self.entry().workspace_diagnostics
356    }
357
358    /// Whether the two analyses analyze the same files: both run in the same
359    /// production mode.
360    #[cfg(test)]
361    fn shares_files_with(&self, other: Runnable<'_>) -> bool {
362        self.production().value() == other.production().value()
363    }
364
365    /// A session of the analysis.
366    pub fn open_session(&self) -> AnalysisSession {
367        self.session_from(self.entry().config.clone())
368    }
369
370    /// A session of the analysis, with the rule settings of one command.
371    ///
372    /// # Errors
373    ///
374    /// Returns an error when `adjust` changes a decided field: the root, the
375    /// production mode, the ignore or workspace patterns, the max file size,
376    /// the cache directory or size, `no_cache`, the thread count or
377    /// `include_entry_exports`.
378    pub fn open_session_adjusted(
379        &self,
380        adjust: impl FnOnce(&mut ResolvedConfig),
381    ) -> EngineResult<AnalysisSession> {
382        let decided = &self.entry().config;
383        let mut config = decided.clone();
384        adjust(&mut config);
385        if let Some(field) = changed_decided_field(decided, &config) {
386            return Err(EngineError::new(format!(
387                "a command adjustment changed the resolved field `{field}`"
388            )));
389        }
390        Ok(self.session_from(config))
391    }
392
393    fn session_from(&self, config: ResolvedConfig) -> AnalysisSession {
394        let entry = self.entry();
395        let project = ModeEntry {
396            config,
397            inputs: entry.inputs.clone(),
398            inputs_before_resolve: entry.inputs_before_resolve.clone(),
399            workspaces: entry.workspaces.clone(),
400            workspace_diagnostics: entry.workspace_diagnostics.clone(),
401            workspace_discovery_ms: entry.workspace_discovery_ms,
402        }
403        .into_project_config(
404            self.run.config_file.value().clone(),
405            self.duplication_scope(),
406        );
407        AnalysisSession::from_config(project)
408    }
409
410    /// The duplication files of a session of this analysis: the session files
411    /// when duplication runs in the same production mode, else the files of
412    /// the config of the duplication mode.
413    fn duplication_scope(&self) -> DuplicationScope {
414        let dupes = *self.run.duplication.production.value();
415        if dupes == *self.production().value() {
416            return DuplicationScope::SameAsSession;
417        }
418        let mut config = self.run.file.clone();
419        steps::flatten_production(&mut config, self.run.config_file.value().is_some(), dupes);
420        DuplicationScope::Own {
421            config: Box::new(config),
422            options: self.run.settings.resolve_options(),
423            env: Box::new(self.run.given.env_for_steps(&self.run.env)),
424            given: Box::new(self.run.given.clone()),
425        }
426    }
427}
428
429/// The name of the first decided field that differs between the two configs.
430fn changed_decided_field(
431    decided: &ResolvedConfig,
432    adjusted: &ResolvedConfig,
433) -> Option<&'static str> {
434    let checks: [(&'static str, bool); 12] = [
435        ("root", decided.root == adjusted.root),
436        ("production", decided.production == adjusted.production),
437        (
438            "production_ignore",
439            decided.production_ignore == adjusted.production_ignore,
440        ),
441        (
442            "ignore_patterns",
443            decided
444                .ignore_patterns
445                .same_globs(&adjusted.ignore_patterns),
446        ),
447        (
448            "workspace_patterns",
449            decided.workspace_patterns == adjusted.workspace_patterns,
450        ),
451        (
452            "max_file_size_bytes",
453            decided.max_file_size_bytes == adjusted.max_file_size_bytes,
454        ),
455        ("cache_dir", decided.cache_dir == adjusted.cache_dir),
456        (
457            "cache_max_size_mb",
458            decided.cache_max_size_mb == adjusted.cache_max_size_mb,
459        ),
460        ("no_cache", decided.no_cache == adjusted.no_cache),
461        ("threads", decided.threads == adjusted.threads),
462        (
463            "include_entry_exports",
464            decided.include_entry_exports == adjusted.include_entry_exports,
465        ),
466        (
467            "workspace_changed_since",
468            decided.workspace_changed_since == adjusted.workspace_changed_since,
469        ),
470    ];
471    checks
472        .into_iter()
473        .find_map(|(field, same)| (!same).then_some(field))
474}
475
476/// The default thread count of a run: the available parallelism of the host,
477/// else 1.
478#[must_use]
479pub fn available_threads() -> usize {
480    threads_or_one(std::thread::available_parallelism())
481}
482
483/// The thread count of an `available_parallelism` result. One thread when the
484/// host cannot tell, so a run never starts more workers than it can prove.
485fn threads_or_one(parallelism: std::io::Result<std::num::NonZeroUsize>) -> usize {
486    parallelism.map_or(1, std::num::NonZeroUsize::get)
487}
488
489/// The root of a path input: absolute paths stay, relative paths join `cwd`.
490fn join_cwd(path: &Path, cwd: Option<&Path>) -> Option<PathBuf> {
491    if path.is_absolute() {
492        Some(path.to_path_buf())
493    } else {
494        cwd.map(|cwd| cwd.join(path))
495    }
496}
497
498#[cfg(test)]
499#[path = "resolve_tests.rs"]
500mod resolve_tests;
501
502#[cfg(test)]
503#[path = "run_tests.rs"]
504mod run_tests;
505
506#[cfg(test)]
507#[path = "base_tests.rs"]
508mod base_tests;