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, CommandKind, ConfigFallback, EnvSnapshot, EnvVar,
7    FallowConfig, PlannedAnalysis, RunCommand, RunInputs, RunPlan, RunRequest, SelectionInput,
8    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}
198
199/// Resolve the base side of a comparison with a base ref: the inputs of
200/// `head` on the base root, with the config file of the [`BaseConfig`] rule.
201/// The base run prints no progress.
202///
203/// # Errors
204///
205/// Returns a [`ResolveError`] as [`resolve_run`] does.
206pub fn resolve_base_run(head: &ResolvedRun, base: BaseSide) -> Result<ResolvedRun, ResolveError> {
207    resolve_base_side(head, base, false)
208}
209
210/// Resolve the base side of a comparison with a base ref as
211/// [`resolve_base_run`] does, with the decisions of `head` for the analyses:
212/// the base side runs each analysis that the head run runs, and no other,
213/// with the production mode of the head run. The config of the base side
214/// then cannot turn an analysis off or change a production mode, so the
215/// findings of the two sides compare.
216///
217/// # Errors
218///
219/// Returns a [`ResolveError`] as [`resolve_run`] does.
220pub fn resolve_base_run_with_head_decisions(
221    head: &ResolvedRun,
222    base: BaseSide,
223) -> Result<ResolvedRun, ResolveError> {
224    resolve_base_side(head, base, true)
225}
226
227fn resolve_base_side(
228    head: &ResolvedRun,
229    base: BaseSide,
230    head_decisions: bool,
231) -> Result<ResolvedRun, ResolveError> {
232    let BaseSide {
233        root,
234        config,
235        cache_dir,
236    } = base;
237    let file = base_config_file(head, &root.value, config);
238    let mut inputs = (*head.inputs).clone();
239    if head_decisions {
240        keep_head_decisions(&mut inputs, head, root.origin);
241    }
242    inputs.root = Some(root);
243    inputs.config_path = None;
244    inputs.config_fallback = ConfigFallback::Fail;
245    if cache_dir.is_some() {
246        inputs.cache_dir = cache_dir;
247    }
248    inputs.quiet = true;
249    resolve_with(&inputs, |ctx, _| {
250        ctx.load(
251            file.as_ref()
252                .map(|(path, source)| (path.as_path(), source.clone())),
253        )
254    })
255}
256
257/// Give `inputs` the plan and the production modes of `head` as inputs of
258/// `origin`.
259fn keep_head_decisions(inputs: &mut RunInputs, head: &ResolvedRun, origin: Origin) {
260    let runs = |analysis| Some(head.decision(analysis).selection.value().runs());
261    inputs.selection = SelectionInput::Options {
262        dead_code: runs(PlannedAnalysis::DeadCode),
263        duplication: runs(PlannedAnalysis::Duplication),
264        health: runs(PlannedAnalysis::Health),
265        origin,
266    };
267    let production = |analysis| {
268        Some(Given {
269            value: *head.production(analysis).value(),
270            origin,
271        })
272    };
273    inputs.production = None;
274    inputs.production_dead_code = production(PlannedAnalysis::DeadCode);
275    inputs.production_health = production(PlannedAnalysis::Health);
276    inputs.production_dupes = production(PlannedAnalysis::Duplication);
277}
278
279/// The config file of a base side with its source, or `None` for discovery
280/// from the base root.
281fn base_config_file(
282    head: &ResolvedRun,
283    base_root: &Path,
284    rule: BaseConfig,
285) -> Option<(PathBuf, Source)> {
286    let path = head.config_file.value().as_ref()?;
287    let source = head.config_file.source();
288    let explicit = matches!(source, Source::Given { .. });
289    match rule {
290        BaseConfig::Head if explicit => Some((path.clone(), source.clone())),
291        BaseConfig::Head => Some((
292            path.clone(),
293            Source::Derived {
294                from: "head-config",
295            },
296        )),
297        BaseConfig::BaseCopy if !explicit => None,
298        BaseConfig::BaseCopy => {
299            let canonical = dunce::canonicalize(path).unwrap_or_else(|_| path.clone());
300            match canonical.strip_prefix(head.root.value()) {
301                Ok(relative) => {
302                    let copy = base_root.join(relative);
303                    copy.is_file()
304                        .then_some((copy, Source::Derived { from: "base-copy" }))
305                }
306                Err(_) => Some((path.clone(), source.clone())),
307            }
308        }
309    }
310}
311
312/// Resolve the raw inputs of one run with `config` in place of a config file.
313/// The config is validated, and the run has no config file.
314///
315/// # Errors
316///
317/// Returns a [`ResolveError`] as [`resolve_run`] does.
318#[cfg(any(test, feature = "testing"))]
319pub fn resolve_run_inline(
320    inputs: &RunInputs,
321    config: FallowConfig,
322) -> Result<ResolvedRun, ResolveError> {
323    resolve_with(inputs, |ctx, _| ctx.inline(config))
324}
325
326/// The steps of [`resolve_run`], with `load` in place of the load step.
327fn resolve_with(
328    inputs: &RunInputs,
329    load: impl FnOnce(&Context<'_>, Option<&Given<PathBuf>>) -> Result<Loaded, ResolveError>,
330) -> Result<ResolvedRun, ResolveError> {
331    let surface = inputs.surface();
332    let (env, env_read, env_ignored) = split_env(inputs.env(), surface, inputs.command);
333    if inputs
334        .threads
335        .as_ref()
336        .is_some_and(|given| given.value == 0)
337    {
338        return Err(ResolveError::input(
339            InputField::Threads,
340            InputProblem::Zero,
341            "the thread count must be at least 1".to_owned(),
342        ));
343    }
344    let root = resolve_root(inputs)?;
345    let config_path = resolve_config_path(inputs)?;
346    let ctx = Context {
347        inputs,
348        env: &env,
349        root: root.value(),
350    };
351    let given = ctx.given_settings();
352    let (loaded, fallback) = match load(&ctx, config_path.as_ref()) {
353        Ok(loaded) => (loaded, None),
354        Err(err) if err.is_config_error() && ctx.falls_back(config_path.as_ref()) => {
355            tracing::debug!("config fell back to the defaults: {}", err.message());
356            (ctx.defaults()?, Some(err))
357        }
358        Err(err) => return Err(err),
359    };
360    let Loaded {
361        file,
362        config_file,
363        config_snapshot,
364        decisions,
365        settings,
366        type_aware,
367        mut off,
368        mut on,
369    } = loaded;
370    let notices = super::notices::run_notices(&super::notices::NoticeInput {
371        root: root.value(),
372        env: &env,
373        file: &file,
374        config_file: &config_file,
375        fallback: fallback.as_ref(),
376    });
377    // Each session of the run carries the notices with the diagnostics of
378    // workspace discovery, so every output of the run holds them.
379    for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
380        entry.workspace_diagnostics = fallow_types::workspace::merge_workspace_diagnostics(
381            std::mem::take(&mut entry.workspace_diagnostics),
382            notices.clone(),
383        );
384    }
385    Ok(ResolvedRun {
386        surface,
387        command: inputs.command,
388        root,
389        config_file,
390        config_snapshot,
391        file,
392        dead_code: decisions.dead_code,
393        duplication: decisions.dupes,
394        health: decisions.health,
395        off,
396        on,
397        settings,
398        type_aware,
399        given,
400        env,
401        env_read,
402        env_ignored,
403        fallback,
404        notices,
405        inputs: Box::new(inputs.clone()),
406    })
407}
408
409/// The snapshot without the variables that the run does not read, and the
410/// set variables that the run reads and ignores.
411fn split_env(
412    env: &EnvSnapshot,
413    surface: Surface,
414    command: CommandKind,
415) -> (EnvSnapshot, Vec<EnvVar>, Vec<EnvVar>) {
416    let (read, ignored) = env
417        .set_vars()
418        .partition(|var| applies(*var, surface, command));
419    let kept = env.clone().retain(|var| applies(var, surface, command));
420    (kept, read, ignored)
421}
422
423fn resolve_root(inputs: &RunInputs) -> Result<Sourced<PathBuf>, ResolveError> {
424    let candidate = match &inputs.root {
425        Some(given) => Some(given_value(given, Scope::Global)),
426        None => inputs.env().cwd().map(|cwd| {
427            Sourced::new(
428                cwd.to_path_buf(),
429                Source::Default {
430                    rule: "current-dir",
431                },
432                Scope::Global,
433            )
434        }),
435    };
436    let Some(candidate) = candidate else {
437        return Err(ResolveError::input(
438            InputField::Root,
439            InputProblem::CwdUnavailable,
440            "no root is given and the current directory is not available".to_owned(),
441        ));
442    };
443    let path = join_cwd(candidate.value(), inputs.env().cwd()).ok_or_else(|| {
444        ResolveError::input(
445            InputField::Root,
446            InputProblem::CwdUnavailable,
447            format!(
448                "the relative root '{}' needs a current directory",
449                candidate.value().display()
450            ),
451        )
452    })?;
453    let canonical = crate::validate::validate_root(&path)
454        .map_err(|message| ResolveError::input(InputField::Root, InputProblem::Invalid, message))?;
455    Ok(candidate.map(|_| canonical))
456}
457
458fn resolve_config_path(inputs: &RunInputs) -> Result<Option<Given<PathBuf>>, ResolveError> {
459    let Some(given) = &inputs.config_path else {
460        return Ok(None);
461    };
462    let path = join_cwd(&given.value, inputs.env().cwd()).ok_or_else(|| {
463        ResolveError::input(
464            InputField::ConfigPath,
465            InputProblem::CwdUnavailable,
466            format!(
467                "the relative config path '{}' needs a current directory",
468                given.value.display()
469            ),
470        )
471    })?;
472    Ok(Some(Given {
473        value: path,
474        origin: given.origin,
475    }))
476}
477
478/// The inputs that every step of one resolve reads.
479struct Context<'a> {
480    inputs: &'a RunInputs,
481    /// The snapshot without the variables that the run does not read.
482    env: &'a EnvSnapshot,
483    root: &'a Path,
484}
485
486/// The result of the steps after the root and the config path.
487struct Loaded {
488    file: FallowConfig,
489    config_file: Sourced<Option<PathBuf>>,
490    config_snapshot: ConfigChainSnapshot,
491    decisions: PerAnalysis<AnalysisDecision>,
492    settings: RunSettings,
493    type_aware: TypeAwareDecision,
494    off: Option<ModeEntry>,
495    on: Option<ModeEntry>,
496}
497
498impl Context<'_> {
499    fn falls_back(&self, config_path: Option<&Given<PathBuf>>) -> bool {
500        config_path.is_none()
501            && self.inputs.config_fallback == ConfigFallback::DefaultsOnDiscoveredError
502    }
503
504    fn allow_remote_extends(&self) -> Sourced<bool> {
505        self.inputs.allow_remote_extends.as_ref().map_or_else(
506            || {
507                Sourced::new(
508                    false,
509                    Source::Default {
510                        rule: "remote-extends-off",
511                    },
512                    Scope::Global,
513                )
514            },
515            |given| given_value(given, Scope::Global),
516        )
517    }
518
519    /// Load, validate, plan, decide and resolve the config of the run.
520    /// `explicit` is a config file with its source; `None` discovers the
521    /// config from the root.
522    fn load(&self, explicit: Option<(&Path, Source)>) -> Result<Loaded, ResolveError> {
523        let options = ConfigFileOptions {
524            allow_remote_extends: *self.allow_remote_extends().value(),
525        };
526        let ConfigFile {
527            config,
528            path,
529            chain,
530        } = load_config_file(self.root, explicit.as_ref().map(|(path, _)| *path), options)
531            .map_err(ResolveError::ConfigLoad)?;
532        steps::validate_command_config(self.inputs.command, self.root, &config).map_err(|err| {
533            ResolveError::ConfigInvalid {
534                file: path.clone(),
535                message: err.to_string(),
536            }
537        })?;
538        let config_file = match (explicit, path) {
539            (Some((_, source)), Some(path)) => Sourced::new(Some(path), source, Scope::Global),
540            (None, Some(path)) => Sourced::new(
541                Some(path),
542                Source::Derived { from: "discovery" },
543                Scope::Global,
544            ),
545            (_, None) => Sourced::new(None, Source::Default { rule: "no-config" }, Scope::Global),
546        };
547        Ok(Loaded {
548            config_snapshot: chain,
549            ..self.decide(config, config_file, false)?
550        })
551    }
552
553    /// The steps of [`Self::load`] with a config that the caller built.
554    #[cfg(any(test, feature = "testing"))]
555    fn inline(&self, config: FallowConfig) -> Result<Loaded, ResolveError> {
556        steps::validate_config(self.root, &config).map_err(|err| ResolveError::ConfigInvalid {
557            file: None,
558            message: err.to_string(),
559        })?;
560        let config_file = Sourced::new(
561            None,
562            Source::Derived {
563                from: "inline-config",
564            },
565            Scope::Global,
566        );
567        self.decide(config, config_file, false)
568    }
569
570    /// The steps of [`Self::load`] with the default config.
571    fn defaults(&self) -> Result<Loaded, ResolveError> {
572        let config_file = Sourced::new(
573            None,
574            Source::Derived {
575                from: "config-fallback",
576            },
577            Scope::Global,
578        );
579        self.decide(FallowConfig::default(), config_file, true)
580    }
581
582    fn decide(
583        &self,
584        file: FallowConfig,
585        config_file: Sourced<Option<PathBuf>>,
586        fell_back: bool,
587    ) -> Result<Loaded, ResolveError> {
588        let path = config_file.value().clone();
589        let plan = self.plan(&file)?;
590        let production =
591            decide_production(&self.production_inputs(), &file.production, path.as_deref());
592        let selection = plan_selections(plan, self.inputs, path.as_deref());
593        let decisions = PerAnalysis {
594            dead_code: AnalysisDecision {
595                selection: selection.dead_code,
596                production: production.dead_code,
597            },
598            health: AnalysisDecision {
599                selection: selection.health,
600                production: production.health,
601            },
602            dupes: AnalysisDecision {
603                selection: selection.dupes,
604                production: production.dupes,
605            },
606        };
607        let mut settings = self.settings(&file, path.as_deref());
608        let (mut off, mut on) =
609            self.mode_entries(&file, path.is_some(), &decisions, &settings, fell_back)?;
610        if self.inputs.surface() == Surface::Lsp {
611            let mut scoped = false;
612            for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
613                scoped |= steps::scope_cache_dir_to_root(&mut entry.config);
614            }
615            if scoped {
616                settings.cache_dir = Sourced::new(
617                    PathBuf::new(),
618                    Source::Derived {
619                        from: "editor-cache-per-root",
620                    },
621                    Scope::Global,
622                );
623            }
624        }
625        let cache_dir = off.as_ref().or(on.as_ref()).map_or_else(
626            || self.cache_dir_without_entry(file.cache.dir.clone()),
627            |entry| entry.config.cache_dir.clone(),
628        );
629        settings.cache_dir = settings.cache_dir.map(|_| cache_dir);
630        let type_aware = super::type_aware::decision(
631            self.inputs.command,
632            &self.inputs.type_aware,
633            self.env,
634            TypeAwareConfigInput {
635                section: &file.type_aware,
636                audit: file.audit.type_aware,
637                file: path.as_deref(),
638            },
639        );
640        Ok(Loaded {
641            file,
642            config_file,
643            config_snapshot: ConfigChainSnapshot::default(),
644            decisions,
645            settings,
646            type_aware,
647            off,
648            on,
649        })
650    }
651
652    fn plan(&self, file: &FallowConfig) -> Result<RunPlan, ResolveError> {
653        let request = run_request(self.inputs.command, &self.inputs.selection);
654        let plan = fallow_config::plan_run(file.plan_sections(), request);
655        if plan.runs_any() {
656            return Ok(plan);
657        }
658        let cause = if [request.dead_code, request.duplication, request.health]
659            .iter()
660            .all(|request| *request == AnalysisRequest::Excluded)
661        {
662            EmptyCause::Request
663        } else if self.inputs.surface() == Surface::Cli {
664            EmptyCause::Config
665        } else {
666            return Ok(plan);
667        };
668        Err(ResolveError::NothingSelected {
669            command: self.inputs.command,
670            cause,
671        })
672    }
673
674    /// The production inputs of the run: the given values, and the variables
675    /// that the env policy lets the run read.
676    fn production_inputs(&self) -> ProductionInputs {
677        let env = |var| self.env.bool(var).set();
678        ProductionInputs {
679            global_flag: self.inputs.production,
680            own_flag: PerAnalysis {
681                dead_code: self.inputs.production_dead_code,
682                health: self.inputs.production_health,
683                dupes: self.inputs.production_dupes,
684            },
685            global_env: env(EnvVar::Production),
686            own_env: PerAnalysis {
687                dead_code: env(EnvVar::ProductionDeadCode),
688                health: env(EnvVar::ProductionHealth),
689                dupes: env(EnvVar::ProductionDupes),
690            },
691        }
692    }
693
694    /// One resolved config for each production mode that a planned analysis
695    /// uses.
696    fn mode_entries(
697        &self,
698        file: &FallowConfig,
699        from_file: bool,
700        decisions: &PerAnalysis<AnalysisDecision>,
701        settings: &RunSettings,
702        lossy: bool,
703    ) -> Result<(Option<ModeEntry>, Option<ModeEntry>), ResolveError> {
704        let needs = |on: bool| {
705            [&decisions.dead_code, &decisions.dupes, &decisions.health]
706                .iter()
707                .any(|decision| {
708                    decision.selection.value().runs() && *decision.production.value() == on
709                })
710        };
711        let entry = |on: bool| -> Result<Option<ModeEntry>, ResolveError> {
712            if !needs(on) {
713                return Ok(None);
714            }
715            let mut config = file.clone();
716            steps::flatten_production(&mut config, from_file, on);
717            let options = settings.resolve_options();
718            let given = self.given_settings();
719            let env = given.env_for_steps(self.env);
720            let mut entry = if lossy {
721                steps::mode_entry_lossy(self.root, config, options, &env)
722            } else {
723                steps::mode_entry(self.root, config, options, &env).map_err(|err| {
724                    ResolveError::Workspace {
725                        message: err.to_string(),
726                    }
727                })?
728            };
729            given.apply(&mut entry.config);
730            Ok(Some(entry))
731        };
732        Ok((entry(false)?, entry(true)?))
733    }
734
735    /// The given settings that win over the environment.
736    fn given_settings(&self) -> GivenSettings {
737        let inputs = self.inputs;
738        GivenSettings {
739            max_file_size_mb: inputs.max_file_size_mb.as_ref().map(|given| given.value),
740            cache_dir: inputs.cache_dir.as_ref().map(|given| given.value.clone()),
741            include_entry_exports: inputs
742                .include_entry_exports
743                .as_ref()
744                .map(|given| given.value),
745            package_baselines: inputs.package_baselines.as_ref().map(|given| given.value),
746        }
747    }
748}
749
750/// The run request of a command and its selection input.
751fn run_request(command: CommandKind, selection: &SelectionInput) -> RunRequest {
752    let run_command = if command == CommandKind::Audit {
753        RunCommand::Audit
754    } else {
755        RunCommand::Combined
756    };
757    match selection {
758        SelectionInput::Lists { only, skip, .. } => RunRequest::from_lists(run_command, only, skip),
759        SelectionInput::Booleans {
760            dead_code,
761            duplication,
762            health,
763            ..
764        } => RunRequest::from_booleans(run_command, *dead_code, *duplication, *health),
765        SelectionInput::Options {
766            dead_code,
767            duplication,
768            health,
769            ..
770        } => RunRequest::from_options(run_command, *dead_code, *duplication, *health),
771        SelectionInput::Single(analysis) => {
772            let request = |candidate| {
773                if candidate == *analysis {
774                    AnalysisRequest::Named
775                } else {
776                    AnalysisRequest::Excluded
777                }
778            };
779            RunRequest {
780                command: run_command,
781                dead_code: request(PlannedAnalysis::DeadCode),
782                duplication: request(PlannedAnalysis::Duplication),
783                health: request(PlannedAnalysis::Health),
784            }
785        }
786    }
787}
788
789/// The selection of each analysis with its source.
790fn plan_selections(
791    plan: RunPlan,
792    inputs: &RunInputs,
793    file: Option<&Path>,
794) -> PerAnalysis<Sourced<AnalysisSelection>> {
795    let request_source = match &inputs.selection {
796        SelectionInput::Lists { origin, .. }
797        | SelectionInput::Booleans { origin, .. }
798        | SelectionInput::Options { origin, .. } => Source::Given { origin: *origin },
799        SelectionInput::Single(_) => Source::Derived { from: "command" },
800    };
801    let request = run_request(inputs.command, &inputs.selection);
802    let sourced = |selection: AnalysisSelection, analysis: PlannedAnalysis| {
803        let source = if let Some(key) = skip_key(selection) {
804            file.map_or(Source::Derived { from: "config" }, |file| {
805                Source::ConfigFile {
806                    file: file.to_path_buf(),
807                    key: config_key_name(key),
808                }
809            })
810        } else if request_is_default(request, analysis) {
811            Source::Default {
812                rule: "runs-by-default",
813            }
814        } else {
815            request_source.clone()
816        };
817        Sourced::new(selection, source, Scope::Analysis)
818    };
819    PerAnalysis {
820        dead_code: sourced(plan.dead_code, PlannedAnalysis::DeadCode),
821        health: sourced(plan.health, PlannedAnalysis::Health),
822        dupes: sourced(plan.duplication, PlannedAnalysis::Duplication),
823    }
824}
825
826fn request_is_default(request: RunRequest, analysis: PlannedAnalysis) -> bool {
827    let value = match analysis {
828        PlannedAnalysis::DeadCode => request.dead_code,
829        PlannedAnalysis::Duplication => request.duplication,
830        PlannedAnalysis::Health => request.health,
831    };
832    value == AnalysisRequest::Default
833}
834
835impl Context<'_> {
836    /// The settings of the run with their sources. The values equal the
837    /// values that the steps write on each resolved config.
838    fn settings(&self, file: &FallowConfig, path: Option<&Path>) -> RunSettings {
839        let inputs = self.inputs;
840        let default = |rule| Source::Default { rule };
841        let environment = |var: EnvVar| Source::Environment { name: var.name() };
842        let config_key = |key| {
843            path.map_or(Source::Derived { from: "config" }, |file| {
844                Source::ConfigFile {
845                    file: file.to_path_buf(),
846                    key,
847                }
848            })
849        };
850        let pick_given = |given: Option<&Given<bool>>, fallback: Sourced<bool>| {
851            given.map_or(fallback, |given| given_value(given, Scope::Global))
852        };
853        let threads = inputs.threads.as_ref().map_or_else(
854            || {
855                Sourced::new(
856                    super::available_threads(),
857                    default("available-parallelism"),
858                    Scope::Global,
859                )
860            },
861            |given| given_value(given, Scope::Global),
862        );
863        let no_cache = pick_given(
864            inputs.no_cache.as_ref(),
865            Sourced::new(false, default("cache-on"), Scope::Global),
866        );
867        let max_file_size_bytes =
868            match (&inputs.max_file_size_mb, steps::max_file_size_env(self.env)) {
869                (Some(given), _) => Sourced::new(
870                    fallow_config::resolve_max_file_size_bytes(Some(given.value)),
871                    given_source(given),
872                    Scope::Global,
873                ),
874                (None, Some(mb)) => Sourced::new(
875                    fallow_config::resolve_max_file_size_bytes(Some(mb)),
876                    environment(EnvVar::MaxFileSize),
877                    Scope::Global,
878                ),
879                (None, None) => Sourced::new(
880                    fallow_config::resolve_max_file_size_bytes(None),
881                    default("max-file-size"),
882                    Scope::Global,
883                ),
884            };
885        let cache_max_size_mb = match self
886            .env
887            .get(EnvVar::CacheMaxSize)
888            .and_then(fallow_config::cache_max_size_from_env_value)
889        {
890            Some(mb) => Sourced::new(Some(mb), environment(EnvVar::CacheMaxSize), Scope::Global),
891            None if file.cache.max_size_mb.is_some() => Sourced::new(
892                file.cache.max_size_mb,
893                config_key("cache.maxSizeMb"),
894                Scope::Global,
895            ),
896            None => Sourced::new(None, default("cache-size"), Scope::Global),
897        };
898        let package_baselines = pick_given(
899            inputs.package_baselines.as_ref(),
900            match self.env.get(EnvVar::PackageBaselines) {
901                Some(raw) if fallow_config::package_baselines_disabled_by_env_value(raw) => {
902                    Sourced::new(false, environment(EnvVar::PackageBaselines), Scope::Global)
903                }
904                _ => Sourced::new(true, default("package-baselines-on"), Scope::Global),
905            },
906        );
907        let include_entry_exports = pick_given(
908            inputs.include_entry_exports.as_ref(),
909            if file.include_entry_exports {
910                Sourced::new(true, config_key("includeEntryExports"), Scope::Global)
911            } else {
912                Sourced::new(false, default("entry-exports-off"), Scope::Global)
913            },
914        );
915        RunSettings {
916            threads,
917            no_cache,
918            allow_remote_extends: self.allow_remote_extends(),
919            max_file_size_bytes,
920            cache_dir: self.cache_dir_source(file, path),
921            cache_max_size_mb,
922            package_baselines,
923            include_entry_exports,
924            output: inputs.output,
925            quiet: inputs.quiet,
926        }
927    }
928
929    /// The source of the cache directory. [`Context::decide`] sets the value.
930    fn cache_dir_source(&self, file: &FallowConfig, path: Option<&Path>) -> Sourced<PathBuf> {
931        let source = if let Some(given) = &self.inputs.cache_dir {
932            given_source(given)
933        } else if self.cache_dir_env().is_some() {
934            Source::Environment {
935                name: EnvVar::CacheDir.name(),
936            }
937        } else {
938            match (path, &file.cache.dir) {
939                (Some(path), Some(_)) => Source::ConfigFile {
940                    file: path.to_path_buf(),
941                    key: "cache.dir",
942                },
943                _ => Source::Default { rule: "cache-dir" },
944            }
945        };
946        Sourced::new(PathBuf::new(), source, Scope::Global)
947    }
948
949    fn cache_dir_env(&self) -> Option<PathBuf> {
950        self.env
951            .get(EnvVar::CacheDir)
952            .map(std::ffi::OsStr::to_os_string)
953            .and_then(fallow_config::cache_dir_from_env_value)
954    }
955
956    /// The cache directory of a run that resolves no config, by the rules of
957    /// a resolved config.
958    fn cache_dir_without_entry(&self, configured: Option<PathBuf>) -> PathBuf {
959        let host = self
960            .inputs
961            .cache_dir
962            .as_ref()
963            .map(|given| given.value.clone())
964            .or_else(|| self.cache_dir_env());
965        host.map_or_else(
966            || fallow_config::config_cache_dir(self.root, configured),
967            |dir| join_cwd(&dir, Some(self.root)).unwrap_or(dir),
968        )
969    }
970}