Skip to main content

fallow_engine/resolved_run/
resolve.rs

1//! The resolver: raw run inputs to one [`ResolvedRun`].
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{
6    AnalysisRequest, AnalysisSelection, AnalysisSnapshot, CommandKind, ConfigFallback, EnvSnapshot,
7    EnvVar, FallowConfig, PlannedAnalysis, RunCommand, RunInputs, RunPlan, RunRequest,
8    SelectionInput, Surface,
9};
10use fallow_types::sourced::{Given, Origin, Scope, Source, Sourced};
11
12use super::env_policy::applies;
13use super::pick::{PerAnalysis, ProductionInputs, decide_production};
14use super::steps::{self, GivenSettings, ModeEntry};
15use super::type_aware::{TypeAwareConfigInput, TypeAwareDecision};
16use super::{AnalysisDecision, ResolvedRun, RunSettings, config_key_name, join_cwd, skip_key};
17use crate::project_config::{
18    ConfigChainSnapshot, ConfigFile, ConfigFileOptions, ConfigLoadError, load_config_file,
19};
20
21/// The field of the run inputs that an input error names.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum InputField {
24    /// The project root.
25    Root,
26    /// The explicit config path.
27    ConfigPath,
28    /// The thread count.
29    Threads,
30    /// An environment variable.
31    Env(EnvVar),
32}
33
34/// What is wrong with an input.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum InputProblem {
37    /// The input is relative or missing, and the process has no current
38    /// directory.
39    CwdUnavailable,
40    /// The input names no usable directory or file.
41    Invalid,
42    /// The input is zero.
43    Zero,
44    /// The value is not one of the values that the input takes.
45    InvalidValue,
46    /// The value is not valid UTF-8.
47    NotUnicode,
48}
49
50/// What a run plan leaves out when it selects no analysis.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum EmptyCause {
53    /// The request excludes every analysis.
54    Request,
55    /// The config turns off each analysis that the request leaves in.
56    Config,
57}
58
59/// The error of [`resolve_run`].
60#[derive(Debug)]
61#[non_exhaustive]
62pub enum ResolveError {
63    /// An input of the run is not valid.
64    Input {
65        /// The input.
66        field: InputField,
67        /// What is wrong with it.
68        problem: InputProblem,
69        /// The message for the user.
70        message: String,
71    },
72    /// The config file cannot be read or parsed.
73    ConfigLoad(ConfigLoadError),
74    /// The config file has an invalid plugin, boundary or rule pack.
75    ConfigInvalid {
76        /// The config file.
77        file: Option<PathBuf>,
78        /// The message for the user.
79        message: String,
80    },
81    /// The workspace discovery failed.
82    Workspace {
83        /// The message for the user.
84        message: String,
85    },
86    /// The run selects no analysis.
87    NothingSelected {
88        /// The command of the run.
89        command: CommandKind,
90        /// What left each analysis out.
91        cause: EmptyCause,
92    },
93}
94
95impl ResolveError {
96    /// The config file that the error names, when it names one.
97    #[must_use]
98    pub fn config_file(&self) -> Option<&Path> {
99        match self {
100            Self::ConfigLoad(ConfigLoadError::Parse { path, .. })
101            | Self::ConfigInvalid { file: path, .. } => path.as_deref(),
102            Self::Input { .. } | Self::Workspace { .. } | Self::NothingSelected { .. } => None,
103        }
104    }
105
106    /// Whether the config failed to load, to validate or to give workspace
107    /// metadata. Only such an error can fall back to the defaults.
108    const fn is_config_error(&self) -> bool {
109        matches!(
110            self,
111            Self::ConfigLoad(_) | Self::ConfigInvalid { .. } | Self::Workspace { .. }
112        )
113    }
114
115    /// The message for the user. A config error has the text of the
116    /// `config_for_project*` entry points.
117    pub fn message(&self) -> String {
118        match self {
119            Self::Input { message, .. }
120            | Self::ConfigInvalid { message, .. }
121            | Self::Workspace { message } => message.clone(),
122            Self::ConfigLoad(err) => format!("invalid config: {}", err.chain()),
123            Self::NothingSelected { command, cause } => {
124                let by = match cause {
125                    EmptyCause::Request => "the request",
126                    EmptyCause::Config => "the config",
127                };
128                format!("{by} leaves no analysis for the `{command:?}` run")
129            }
130        }
131    }
132
133    const fn input(field: InputField, problem: InputProblem, message: String) -> Self {
134        Self::Input {
135            field,
136            problem,
137            message,
138        }
139    }
140}
141
142const fn given_source<T>(given: &Given<T>) -> Source {
143    Source::Given {
144        origin: given.origin,
145    }
146}
147
148fn given_value<T: Clone>(given: &Given<T>, scope: Scope) -> Sourced<T> {
149    Sourced::new(given.value.clone(), given_source(given), scope)
150}
151
152/// Resolve the raw inputs of one run.
153///
154/// The steps are: the root, the config path, the load, the validation, the
155/// plan, the production mode of each analysis, the run settings, and one
156/// resolved config for each production mode that a planned analysis uses.
157/// With [`ConfigFallback::DefaultsOnDiscoveredError`], a discovered config
158/// that fails to load, to validate or to give workspace metadata gives the
159/// default config, and [`ResolvedRun::fallback_error`] keeps the error. A run
160/// of [`Surface::Lsp`] scopes a shared cache directory to the root, so two
161/// editor roots do not write the same cache files.
162///
163/// # Errors
164///
165/// Returns a [`ResolveError`] for an invalid input, a config error, a
166/// workspace error, or a run that selects no analysis.
167pub fn resolve_run(inputs: &RunInputs) -> Result<ResolvedRun, ResolveError> {
168    resolve_with(inputs, |ctx, config_path| {
169        ctx.load(config_path.map(|given| (given.value.as_path(), given_source(given))))
170    })
171}
172
173/// Which config file the base side of a comparison with a base ref reads.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum BaseConfig {
176    /// The config file of the head run. A head run without a config file
177    /// gives discovery from the base root.
178    Head,
179    /// The base copy of the config file. An explicit config file under the
180    /// head root gives the file at the same path under the base root. A file
181    /// that the base does not have, and a discovered head config, give
182    /// discovery from the base root. An explicit file outside the head root
183    /// has no base copy, so the base side reads that file.
184    BaseCopy,
185}
186
187/// The base side of a comparison with a base ref.
188#[derive(Debug, Clone)]
189pub struct BaseSide {
190    /// The analysis root in the base checkout.
191    pub root: Given<PathBuf>,
192    /// The config file rule of the base side.
193    pub config: BaseConfig,
194    /// The cache directory of the base side. `None` keeps the cache input of
195    /// the head run.
196    pub cache_dir: Option<Given<PathBuf>>,
197    /// The revision that the side holds. A base revision skips the config
198    /// validation that needs a folder of the change. The staged side of
199    /// `audit --staged` holds the change, so it is the current revision.
200    pub snapshot: AnalysisSnapshot,
201}
202
203impl BaseSide {
204    /// The side of a base revision.
205    #[must_use]
206    pub const fn base(
207        root: Given<PathBuf>,
208        config: BaseConfig,
209        cache_dir: Option<Given<PathBuf>>,
210    ) -> Self {
211        Self {
212            root,
213            config,
214            cache_dir,
215            snapshot: AnalysisSnapshot::Base,
216        }
217    }
218}
219
220/// Resolve the base side of a comparison with a base ref: the inputs of
221/// `head` on the base root, with the config file of the [`BaseConfig`] rule.
222/// The base run prints no progress.
223///
224/// # Errors
225///
226/// Returns a [`ResolveError`] as [`resolve_run`] does.
227pub fn resolve_base_run(head: &ResolvedRun, base: BaseSide) -> Result<ResolvedRun, ResolveError> {
228    resolve_base_side(head, base, false)
229}
230
231/// Resolve the base side of a comparison with a base ref as
232/// [`resolve_base_run`] does, with the decisions of `head` for the analyses:
233/// the base side runs each analysis that the head run runs, and no other,
234/// with the production mode of the head run. The config of the base side
235/// then cannot turn an analysis off or change a production mode, so the
236/// findings of the two sides compare.
237///
238/// # Errors
239///
240/// Returns a [`ResolveError`] as [`resolve_run`] does.
241pub fn resolve_base_run_with_head_decisions(
242    head: &ResolvedRun,
243    base: BaseSide,
244) -> Result<ResolvedRun, ResolveError> {
245    resolve_base_side(head, base, true)
246}
247
248fn resolve_base_side(
249    head: &ResolvedRun,
250    base: BaseSide,
251    head_decisions: bool,
252) -> Result<ResolvedRun, ResolveError> {
253    let BaseSide {
254        root,
255        config,
256        cache_dir,
257        snapshot,
258    } = base;
259    let file = base_config_file(head, &root.value, config);
260    let mut inputs = (*head.inputs).clone();
261    if head_decisions {
262        keep_head_decisions(&mut inputs, head, root.origin);
263    }
264    inputs.root = Some(root);
265    inputs.config_path = None;
266    inputs.config_fallback = ConfigFallback::Fail;
267    if cache_dir.is_some() {
268        inputs.cache_dir = cache_dir;
269    }
270    inputs.quiet = true;
271    resolve_with(&inputs, |ctx, _| {
272        ctx.load_snapshot(
273            file.as_ref()
274                .map(|(path, source)| (path.as_path(), source.clone())),
275            snapshot,
276        )
277    })
278}
279
280/// Give `inputs` the plan and the production modes of `head` as inputs of
281/// `origin`.
282fn keep_head_decisions(inputs: &mut RunInputs, head: &ResolvedRun, origin: Origin) {
283    let runs = |analysis| Some(head.decision(analysis).selection.value().runs());
284    inputs.selection = SelectionInput::Options {
285        dead_code: runs(PlannedAnalysis::DeadCode),
286        duplication: runs(PlannedAnalysis::Duplication),
287        health: runs(PlannedAnalysis::Health),
288        origin,
289    };
290    let production = |analysis| {
291        Some(Given {
292            value: *head.production(analysis).value(),
293            origin,
294        })
295    };
296    inputs.production = None;
297    inputs.production_dead_code = production(PlannedAnalysis::DeadCode);
298    inputs.production_health = production(PlannedAnalysis::Health);
299    inputs.production_dupes = production(PlannedAnalysis::Duplication);
300}
301
302/// The config file of a base side with its source, or `None` for discovery
303/// from the base root.
304fn base_config_file(
305    head: &ResolvedRun,
306    base_root: &Path,
307    rule: BaseConfig,
308) -> Option<(PathBuf, Source)> {
309    let path = head.config_file.value().as_ref()?;
310    let source = head.config_file.source();
311    let explicit = matches!(source, Source::Given { .. });
312    match rule {
313        BaseConfig::Head if explicit => Some((path.clone(), source.clone())),
314        BaseConfig::Head => Some((
315            path.clone(),
316            Source::Derived {
317                from: "head-config",
318            },
319        )),
320        BaseConfig::BaseCopy if !explicit => None,
321        BaseConfig::BaseCopy => {
322            let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.clone());
323            match canonical.strip_prefix(head.root.value()) {
324                Ok(relative) => {
325                    let copy = base_root.join(relative);
326                    copy.is_file()
327                        .then_some((copy, Source::Derived { from: "base-copy" }))
328                }
329                Err(_) => Some((path.clone(), source.clone())),
330            }
331        }
332    }
333}
334
335/// Resolve the raw inputs of one run with `config` in place of a config file.
336/// The config is validated, and the run has no config file.
337///
338/// # Errors
339///
340/// Returns a [`ResolveError`] as [`resolve_run`] does.
341#[cfg(any(test, feature = "testing"))]
342pub fn resolve_run_inline(
343    inputs: &RunInputs,
344    config: FallowConfig,
345) -> Result<ResolvedRun, ResolveError> {
346    resolve_with(inputs, |ctx, _| ctx.inline(config))
347}
348
349/// The steps of [`resolve_run`], with `load` in place of the load step.
350fn resolve_with(
351    inputs: &RunInputs,
352    load: impl FnOnce(&Context<'_>, Option<&Given<PathBuf>>) -> Result<Loaded, ResolveError>,
353) -> Result<ResolvedRun, ResolveError> {
354    let surface = inputs.surface();
355    let (env, env_read, env_ignored) = split_env(inputs.env(), surface, inputs.command);
356    if inputs
357        .threads
358        .as_ref()
359        .is_some_and(|given| given.value == 0)
360    {
361        return Err(ResolveError::input(
362            InputField::Threads,
363            InputProblem::Zero,
364            "the thread count must be at least 1".to_owned(),
365        ));
366    }
367    let root = resolve_root(inputs)?;
368    let config_path = resolve_config_path(inputs)?;
369    let ctx = Context {
370        inputs,
371        env: &env,
372        root: root.value(),
373    };
374    let given = ctx.given_settings();
375    let (loaded, fallback) = match load(&ctx, config_path.as_ref()) {
376        Ok(loaded) => (loaded, None),
377        Err(err) if err.is_config_error() && ctx.falls_back(config_path.as_ref()) => {
378            tracing::debug!("config fell back to the defaults: {}", err.message());
379            (ctx.defaults()?, Some(err))
380        }
381        Err(err) => return Err(err),
382    };
383    let Loaded {
384        file,
385        config_file,
386        config_snapshot,
387        decisions,
388        settings,
389        type_aware,
390        mut off,
391        mut on,
392    } = loaded;
393    let notices = super::notices::run_notices(&super::notices::NoticeInput {
394        root: root.value(),
395        env: &env,
396        file: &file,
397        config_file: &config_file,
398        fallback: fallback.as_ref(),
399    });
400    // Each session of the run carries the notices with the diagnostics of
401    // workspace discovery, so every output of the run holds them.
402    for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
403        entry.workspace_diagnostics = fallow_types::workspace::merge_workspace_diagnostics(
404            std::mem::take(&mut entry.workspace_diagnostics),
405            notices.clone(),
406        );
407    }
408    Ok(ResolvedRun {
409        surface,
410        command: inputs.command,
411        root,
412        config_file,
413        config_snapshot,
414        file,
415        dead_code: decisions.dead_code,
416        duplication: decisions.dupes,
417        health: decisions.health,
418        off,
419        on,
420        settings,
421        type_aware,
422        given,
423        env,
424        env_read,
425        env_ignored,
426        fallback,
427        notices,
428        inputs: Box::new(inputs.clone()),
429    })
430}
431
432/// The snapshot without the variables that the run does not read, and the
433/// set variables that the run reads and ignores.
434fn split_env(
435    env: &EnvSnapshot,
436    surface: Surface,
437    command: CommandKind,
438) -> (EnvSnapshot, Vec<EnvVar>, Vec<EnvVar>) {
439    let (read, ignored) = env
440        .set_vars()
441        .partition(|var| applies(*var, surface, command));
442    let kept = env.clone().retain(|var| applies(var, surface, command));
443    (kept, read, ignored)
444}
445
446fn resolve_root(inputs: &RunInputs) -> Result<Sourced<PathBuf>, ResolveError> {
447    let candidate = match &inputs.root {
448        Some(given) => Some(given_value(given, Scope::Global)),
449        None => inputs.env().cwd().map(|cwd| {
450            Sourced::new(
451                cwd.to_path_buf(),
452                Source::Default {
453                    rule: "current-dir",
454                },
455                Scope::Global,
456            )
457        }),
458    };
459    let Some(candidate) = candidate else {
460        return Err(ResolveError::input(
461            InputField::Root,
462            InputProblem::CwdUnavailable,
463            "no root is given and the current directory is not available".to_owned(),
464        ));
465    };
466    let path = join_cwd(candidate.value(), inputs.env().cwd()).ok_or_else(|| {
467        ResolveError::input(
468            InputField::Root,
469            InputProblem::CwdUnavailable,
470            format!(
471                "the relative root '{}' needs a current directory",
472                candidate.value().display()
473            ),
474        )
475    })?;
476    // A relative root is validated as the user gave it, so the check also
477    // covers its spelling from `PWD`.
478    let validated = match (inputs.root.is_some(), inputs.env().cwd()) {
479        (true, Some(cwd)) => crate::validate::validate_root_in(candidate.value(), cwd),
480        (true, None) => crate::validate::validate_root(&path),
481        (false, _) => crate::validate::validate_current_dir_root(&path),
482    };
483    let canonical = validated
484        .map_err(|message| ResolveError::input(InputField::Root, InputProblem::Invalid, message))?;
485    Ok(candidate.map(|_| canonical))
486}
487
488fn resolve_config_path(inputs: &RunInputs) -> Result<Option<Given<PathBuf>>, ResolveError> {
489    let Some(given) = &inputs.config_path else {
490        return Ok(None);
491    };
492    let path = join_cwd(&given.value, inputs.env().cwd()).ok_or_else(|| {
493        ResolveError::input(
494            InputField::ConfigPath,
495            InputProblem::CwdUnavailable,
496            format!(
497                "the relative config path '{}' needs a current directory",
498                given.value.display()
499            ),
500        )
501    })?;
502    Ok(Some(Given {
503        value: path,
504        origin: given.origin,
505    }))
506}
507
508/// The inputs that every step of one resolve reads.
509struct Context<'a> {
510    inputs: &'a RunInputs,
511    /// The snapshot without the variables that the run does not read.
512    env: &'a EnvSnapshot,
513    root: &'a Path,
514}
515
516/// The result of the steps after the root and the config path.
517struct Loaded {
518    file: FallowConfig,
519    config_file: Sourced<Option<PathBuf>>,
520    config_snapshot: ConfigChainSnapshot,
521    decisions: PerAnalysis<AnalysisDecision>,
522    settings: RunSettings,
523    type_aware: TypeAwareDecision,
524    off: Option<ModeEntry>,
525    on: Option<ModeEntry>,
526}
527
528impl Context<'_> {
529    fn falls_back(&self, config_path: Option<&Given<PathBuf>>) -> bool {
530        config_path.is_none()
531            && self.inputs.config_fallback == ConfigFallback::DefaultsOnDiscoveredError
532    }
533
534    fn allow_remote_extends(&self) -> Sourced<bool> {
535        self.inputs.allow_remote_extends.as_ref().map_or_else(
536            || {
537                Sourced::new(
538                    false,
539                    Source::Default {
540                        rule: "remote-extends-off",
541                    },
542                    Scope::Global,
543                )
544            },
545            |given| given_value(given, Scope::Global),
546        )
547    }
548
549    /// Load, validate, plan, decide and resolve the config of the run.
550    /// `explicit` is a config file with its source; `None` discovers the
551    /// config from the root.
552    fn load(&self, explicit: Option<(&Path, Source)>) -> Result<Loaded, ResolveError> {
553        self.load_snapshot(explicit, AnalysisSnapshot::Current)
554    }
555
556    /// [`Self::load`] for the given revision. The base revision of
557    /// `audit --base` skips the validation that needs a folder of the
558    /// change, such as the module folder of the `deep-modules` preset.
559    fn load_snapshot(
560        &self,
561        explicit: Option<(&Path, Source)>,
562        snapshot: AnalysisSnapshot,
563    ) -> Result<Loaded, ResolveError> {
564        let options = ConfigFileOptions::new(*self.allow_remote_extends().value(), self.env);
565        let ConfigFile {
566            config,
567            path,
568            chain,
569        } = load_config_file(self.root, explicit.as_ref().map(|(path, _)| *path), options)
570            .map_err(ResolveError::ConfigLoad)?;
571        steps::validate_command_config(self.inputs.command, self.root, &config, snapshot).map_err(
572            |err| ResolveError::ConfigInvalid {
573                file: path.clone(),
574                message: err.to_string(),
575            },
576        )?;
577        let config_file = match (explicit, path) {
578            (Some((_, source)), Some(path)) => Sourced::new(Some(path), source, Scope::Global),
579            (None, Some(path)) => Sourced::new(
580                Some(path),
581                Source::Derived { from: "discovery" },
582                Scope::Global,
583            ),
584            (_, None) => Sourced::new(None, Source::Default { rule: "no-config" }, Scope::Global),
585        };
586        Ok(Loaded {
587            config_snapshot: chain,
588            ..self.decide(config, config_file, false)?
589        })
590    }
591
592    /// The steps of [`Self::load`] with a config that the caller built.
593    #[cfg(any(test, feature = "testing"))]
594    fn inline(&self, config: FallowConfig) -> Result<Loaded, ResolveError> {
595        steps::validate_config(self.root, &config).map_err(|err| ResolveError::ConfigInvalid {
596            file: None,
597            message: err.to_string(),
598        })?;
599        let config_file = Sourced::new(
600            None,
601            Source::Derived {
602                from: "inline-config",
603            },
604            Scope::Global,
605        );
606        self.decide(config, config_file, false)
607    }
608
609    /// The steps of [`Self::load`] with the default config.
610    fn defaults(&self) -> Result<Loaded, ResolveError> {
611        let config_file = Sourced::new(
612            None,
613            Source::Derived {
614                from: "config-fallback",
615            },
616            Scope::Global,
617        );
618        self.decide(FallowConfig::default(), config_file, true)
619    }
620
621    fn decide(
622        &self,
623        file: FallowConfig,
624        config_file: Sourced<Option<PathBuf>>,
625        fell_back: bool,
626    ) -> Result<Loaded, ResolveError> {
627        let path = config_file.value().clone();
628        let plan = self.plan(&file)?;
629        let production =
630            decide_production(&self.production_inputs(), &file.production, path.as_deref());
631        let selection = plan_selections(plan, self.inputs, path.as_deref());
632        let decisions = PerAnalysis {
633            dead_code: AnalysisDecision {
634                selection: selection.dead_code,
635                production: production.dead_code,
636            },
637            health: AnalysisDecision {
638                selection: selection.health,
639                production: production.health,
640            },
641            dupes: AnalysisDecision {
642                selection: selection.dupes,
643                production: production.dupes,
644            },
645        };
646        let mut settings = self.settings(&file, path.as_deref());
647        let (mut off, mut on) =
648            self.mode_entries(&file, path.is_some(), &decisions, &settings, fell_back)?;
649        if self.inputs.surface() == Surface::Lsp {
650            let mut scoped = false;
651            for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
652                scoped |= steps::scope_cache_dir_to_root(&mut entry.config);
653            }
654            if scoped {
655                settings.cache_dir = Sourced::new(
656                    PathBuf::new(),
657                    Source::Derived {
658                        from: "editor-cache-per-root",
659                    },
660                    Scope::Global,
661                );
662            }
663        }
664        let cache_dir = off.as_ref().or(on.as_ref()).map_or_else(
665            || self.cache_dir_without_entry(file.cache.dir.clone()),
666            |entry| entry.config.cache_dir.clone(),
667        );
668        settings.cache_dir = settings.cache_dir.map(|_| cache_dir);
669        let type_aware = super::type_aware::decision(
670            self.inputs.command,
671            &self.inputs.type_aware,
672            self.env,
673            TypeAwareConfigInput {
674                section: &file.type_aware,
675                audit: file.audit.type_aware,
676                file: path.as_deref(),
677            },
678        );
679        Ok(Loaded {
680            file,
681            config_file,
682            config_snapshot: ConfigChainSnapshot::default(),
683            decisions,
684            settings,
685            type_aware,
686            off,
687            on,
688        })
689    }
690
691    fn plan(&self, file: &FallowConfig) -> Result<RunPlan, ResolveError> {
692        let request = run_request(self.inputs.command, &self.inputs.selection);
693        let plan = fallow_config::plan_run(file.plan_sections(), request);
694        if plan.runs_any() {
695            return Ok(plan);
696        }
697        let cause = if [request.dead_code, request.duplication, request.health]
698            .iter()
699            .all(|request| *request == AnalysisRequest::Excluded)
700        {
701            EmptyCause::Request
702        } else if self.inputs.surface() == Surface::Cli {
703            EmptyCause::Config
704        } else {
705            return Ok(plan);
706        };
707        Err(ResolveError::NothingSelected {
708            command: self.inputs.command,
709            cause,
710        })
711    }
712
713    /// The production inputs of the run: the given values, and the variables
714    /// that the env policy lets the run read.
715    fn production_inputs(&self) -> ProductionInputs {
716        let env = |var| self.env.bool(var).set();
717        ProductionInputs {
718            global_flag: self.inputs.production,
719            own_flag: PerAnalysis {
720                dead_code: self.inputs.production_dead_code,
721                health: self.inputs.production_health,
722                dupes: self.inputs.production_dupes,
723            },
724            global_env: env(EnvVar::Production),
725            own_env: PerAnalysis {
726                dead_code: env(EnvVar::ProductionDeadCode),
727                health: env(EnvVar::ProductionHealth),
728                dupes: env(EnvVar::ProductionDupes),
729            },
730        }
731    }
732
733    /// One resolved config for each production mode that a planned analysis
734    /// uses.
735    fn mode_entries(
736        &self,
737        file: &FallowConfig,
738        from_file: bool,
739        decisions: &PerAnalysis<AnalysisDecision>,
740        settings: &RunSettings,
741        lossy: bool,
742    ) -> Result<(Option<ModeEntry>, Option<ModeEntry>), ResolveError> {
743        let needs = |on: bool| {
744            [&decisions.dead_code, &decisions.dupes, &decisions.health]
745                .iter()
746                .any(|decision| {
747                    decision.selection.value().runs() && *decision.production.value() == on
748                })
749        };
750        let entry = |on: bool| -> Result<Option<ModeEntry>, ResolveError> {
751            if !needs(on) {
752                return Ok(None);
753            }
754            let mut config = file.clone();
755            steps::flatten_production(&mut config, from_file, on);
756            let options = settings.resolve_options();
757            let given = self.given_settings();
758            let env = given.env_for_steps(self.env);
759            let mut entry = if lossy {
760                steps::mode_entry_lossy(self.root, config, options, &env)
761            } else {
762                steps::mode_entry(self.root, config, options, &env).map_err(|err| {
763                    ResolveError::Workspace {
764                        message: err.to_string(),
765                    }
766                })?
767            };
768            given.apply(&mut entry.config);
769            Ok(Some(entry))
770        };
771        Ok((entry(false)?, entry(true)?))
772    }
773
774    /// The given settings that win over the environment.
775    fn given_settings(&self) -> GivenSettings {
776        let inputs = self.inputs;
777        GivenSettings {
778            max_file_size_mb: inputs.max_file_size_mb.as_ref().map(|given| given.value),
779            cache_dir: inputs.cache_dir.as_ref().map(|given| given.value.clone()),
780            include_entry_exports: inputs
781                .include_entry_exports
782                .as_ref()
783                .map(|given| given.value),
784            package_baselines: inputs.package_baselines.as_ref().map(|given| given.value),
785        }
786    }
787}
788
789/// The run request of a command and its selection input.
790fn run_request(command: CommandKind, selection: &SelectionInput) -> RunRequest {
791    let run_command = if command == CommandKind::Audit {
792        RunCommand::Audit
793    } else {
794        RunCommand::Combined
795    };
796    match selection {
797        SelectionInput::Lists { only, skip, .. } => RunRequest::from_lists(run_command, only, skip),
798        SelectionInput::Booleans {
799            dead_code,
800            duplication,
801            health,
802            ..
803        } => RunRequest::from_booleans(run_command, *dead_code, *duplication, *health),
804        SelectionInput::Options {
805            dead_code,
806            duplication,
807            health,
808            ..
809        } => RunRequest::from_options(run_command, *dead_code, *duplication, *health),
810        SelectionInput::Single(analysis) => {
811            let request = |candidate| {
812                if candidate == *analysis {
813                    AnalysisRequest::Named
814                } else {
815                    AnalysisRequest::Excluded
816                }
817            };
818            RunRequest {
819                command: run_command,
820                dead_code: request(PlannedAnalysis::DeadCode),
821                duplication: request(PlannedAnalysis::Duplication),
822                health: request(PlannedAnalysis::Health),
823            }
824        }
825    }
826}
827
828/// The selection of each analysis with its source.
829fn plan_selections(
830    plan: RunPlan,
831    inputs: &RunInputs,
832    file: Option<&Path>,
833) -> PerAnalysis<Sourced<AnalysisSelection>> {
834    let request_source = match &inputs.selection {
835        SelectionInput::Lists { origin, .. }
836        | SelectionInput::Booleans { origin, .. }
837        | SelectionInput::Options { origin, .. } => Source::Given { origin: *origin },
838        SelectionInput::Single(_) => Source::Derived { from: "command" },
839    };
840    let request = run_request(inputs.command, &inputs.selection);
841    let sourced = |selection: AnalysisSelection, analysis: PlannedAnalysis| {
842        let source = if let Some(key) = skip_key(selection) {
843            file.map_or(Source::Derived { from: "config" }, |file| {
844                Source::ConfigFile {
845                    file: file.to_path_buf(),
846                    key: config_key_name(key),
847                }
848            })
849        } else if request_is_default(request, analysis) {
850            Source::Default {
851                rule: "runs-by-default",
852            }
853        } else {
854            request_source.clone()
855        };
856        Sourced::new(selection, source, Scope::Analysis)
857    };
858    PerAnalysis {
859        dead_code: sourced(plan.dead_code, PlannedAnalysis::DeadCode),
860        health: sourced(plan.health, PlannedAnalysis::Health),
861        dupes: sourced(plan.duplication, PlannedAnalysis::Duplication),
862    }
863}
864
865fn request_is_default(request: RunRequest, analysis: PlannedAnalysis) -> bool {
866    let value = match analysis {
867        PlannedAnalysis::DeadCode => request.dead_code,
868        PlannedAnalysis::Duplication => request.duplication,
869        PlannedAnalysis::Health => request.health,
870    };
871    value == AnalysisRequest::Default
872}
873
874impl Context<'_> {
875    /// The settings of the run with their sources. The values equal the
876    /// values that the steps write on each resolved config.
877    fn settings(&self, file: &FallowConfig, path: Option<&Path>) -> RunSettings {
878        let inputs = self.inputs;
879        let default = |rule| Source::Default { rule };
880        let environment = |var: EnvVar| Source::Environment { name: var.name() };
881        let config_key = |key| {
882            path.map_or(Source::Derived { from: "config" }, |file| {
883                Source::ConfigFile {
884                    file: file.to_path_buf(),
885                    key,
886                }
887            })
888        };
889        let pick_given = |given: Option<&Given<bool>>, fallback: Sourced<bool>| {
890            given.map_or(fallback, |given| given_value(given, Scope::Global))
891        };
892        let threads = inputs.threads.as_ref().map_or_else(
893            || {
894                Sourced::new(
895                    super::available_threads(),
896                    default("available-parallelism"),
897                    Scope::Global,
898                )
899            },
900            |given| given_value(given, Scope::Global),
901        );
902        let no_cache = pick_given(
903            inputs.no_cache.as_ref(),
904            Sourced::new(false, default("cache-on"), Scope::Global),
905        );
906        let max_file_size_bytes =
907            match (&inputs.max_file_size_mb, steps::max_file_size_env(self.env)) {
908                (Some(given), _) => Sourced::new(
909                    fallow_config::resolve_max_file_size_bytes(Some(given.value)),
910                    given_source(given),
911                    Scope::Global,
912                ),
913                (None, Some(mb)) => Sourced::new(
914                    fallow_config::resolve_max_file_size_bytes(Some(mb)),
915                    environment(EnvVar::MaxFileSize),
916                    Scope::Global,
917                ),
918                (None, None) => Sourced::new(
919                    fallow_config::resolve_max_file_size_bytes(None),
920                    default("max-file-size"),
921                    Scope::Global,
922                ),
923            };
924        let cache_max_size_mb = match self
925            .env
926            .get(EnvVar::CacheMaxSize)
927            .and_then(fallow_config::cache_max_size_from_env_value)
928        {
929            Some(mb) => Sourced::new(Some(mb), environment(EnvVar::CacheMaxSize), Scope::Global),
930            None if file.cache.max_size_mb.is_some() => Sourced::new(
931                file.cache.max_size_mb,
932                config_key("cache.maxSizeMb"),
933                Scope::Global,
934            ),
935            None => Sourced::new(None, default("cache-size"), Scope::Global),
936        };
937        let package_baselines = pick_given(
938            inputs.package_baselines.as_ref(),
939            match self.env.get(EnvVar::PackageBaselines) {
940                Some(raw) if fallow_config::package_baselines_disabled_by_env_value(raw) => {
941                    Sourced::new(false, environment(EnvVar::PackageBaselines), Scope::Global)
942                }
943                _ => Sourced::new(true, default("package-baselines-on"), Scope::Global),
944            },
945        );
946        let include_entry_exports = pick_given(
947            inputs.include_entry_exports.as_ref(),
948            if file.include_entry_exports {
949                Sourced::new(true, config_key("includeEntryExports"), Scope::Global)
950            } else {
951                Sourced::new(false, default("entry-exports-off"), Scope::Global)
952            },
953        );
954        RunSettings {
955            threads,
956            no_cache,
957            allow_remote_extends: self.allow_remote_extends(),
958            max_file_size_bytes,
959            cache_dir: self.cache_dir_source(file, path),
960            cache_max_size_mb,
961            package_baselines,
962            include_entry_exports,
963            output: inputs.output,
964            quiet: inputs.quiet,
965        }
966    }
967
968    /// The source of the cache directory. [`Context::decide`] sets the value.
969    fn cache_dir_source(&self, file: &FallowConfig, path: Option<&Path>) -> Sourced<PathBuf> {
970        let source = if let Some(given) = &self.inputs.cache_dir {
971            given_source(given)
972        } else if self.cache_dir_env().is_some() {
973            Source::Environment {
974                name: EnvVar::CacheDir.name(),
975            }
976        } else {
977            match (path, &file.cache.dir) {
978                (Some(path), Some(_)) => Source::ConfigFile {
979                    file: path.to_path_buf(),
980                    key: "cache.dir",
981                },
982                _ => Source::Default { rule: "cache-dir" },
983            }
984        };
985        Sourced::new(PathBuf::new(), source, Scope::Global)
986    }
987
988    fn cache_dir_env(&self) -> Option<PathBuf> {
989        self.env
990            .get(EnvVar::CacheDir)
991            .map(std::ffi::OsStr::to_os_string)
992            .and_then(fallow_config::cache_dir_from_env_value)
993    }
994
995    /// The cache directory of a run that resolves no config, by the rules of
996    /// a resolved config.
997    fn cache_dir_without_entry(&self, configured: Option<PathBuf>) -> PathBuf {
998        let host = self
999            .inputs
1000            .cache_dir
1001            .as_ref()
1002            .map(|given| given.value.clone())
1003            .or_else(|| self.cache_dir_env());
1004        host.map_or_else(
1005            || fallow_config::config_cache_dir(self.root, configured),
1006            |dir| join_cwd(&dir, Some(self.root)).unwrap_or(dir),
1007        )
1008    }
1009}