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    // A relative root is validated as the user gave it, so the check also
454    // covers its spelling from `PWD`.
455    let validated = match (inputs.root.is_some(), inputs.env().cwd()) {
456        (true, Some(cwd)) => crate::validate::validate_root_in(candidate.value(), cwd),
457        (true, None) => crate::validate::validate_root(&path),
458        (false, _) => crate::validate::validate_current_dir_root(&path),
459    };
460    let canonical = validated
461        .map_err(|message| ResolveError::input(InputField::Root, InputProblem::Invalid, message))?;
462    Ok(candidate.map(|_| canonical))
463}
464
465fn resolve_config_path(inputs: &RunInputs) -> Result<Option<Given<PathBuf>>, ResolveError> {
466    let Some(given) = &inputs.config_path else {
467        return Ok(None);
468    };
469    let path = join_cwd(&given.value, inputs.env().cwd()).ok_or_else(|| {
470        ResolveError::input(
471            InputField::ConfigPath,
472            InputProblem::CwdUnavailable,
473            format!(
474                "the relative config path '{}' needs a current directory",
475                given.value.display()
476            ),
477        )
478    })?;
479    Ok(Some(Given {
480        value: path,
481        origin: given.origin,
482    }))
483}
484
485/// The inputs that every step of one resolve reads.
486struct Context<'a> {
487    inputs: &'a RunInputs,
488    /// The snapshot without the variables that the run does not read.
489    env: &'a EnvSnapshot,
490    root: &'a Path,
491}
492
493/// The result of the steps after the root and the config path.
494struct Loaded {
495    file: FallowConfig,
496    config_file: Sourced<Option<PathBuf>>,
497    config_snapshot: ConfigChainSnapshot,
498    decisions: PerAnalysis<AnalysisDecision>,
499    settings: RunSettings,
500    type_aware: TypeAwareDecision,
501    off: Option<ModeEntry>,
502    on: Option<ModeEntry>,
503}
504
505impl Context<'_> {
506    fn falls_back(&self, config_path: Option<&Given<PathBuf>>) -> bool {
507        config_path.is_none()
508            && self.inputs.config_fallback == ConfigFallback::DefaultsOnDiscoveredError
509    }
510
511    fn allow_remote_extends(&self) -> Sourced<bool> {
512        self.inputs.allow_remote_extends.as_ref().map_or_else(
513            || {
514                Sourced::new(
515                    false,
516                    Source::Default {
517                        rule: "remote-extends-off",
518                    },
519                    Scope::Global,
520                )
521            },
522            |given| given_value(given, Scope::Global),
523        )
524    }
525
526    /// Load, validate, plan, decide and resolve the config of the run.
527    /// `explicit` is a config file with its source; `None` discovers the
528    /// config from the root.
529    fn load(&self, explicit: Option<(&Path, Source)>) -> Result<Loaded, ResolveError> {
530        let options = ConfigFileOptions::new(*self.allow_remote_extends().value(), self.env);
531        let ConfigFile {
532            config,
533            path,
534            chain,
535        } = load_config_file(self.root, explicit.as_ref().map(|(path, _)| *path), options)
536            .map_err(ResolveError::ConfigLoad)?;
537        steps::validate_command_config(self.inputs.command, self.root, &config).map_err(|err| {
538            ResolveError::ConfigInvalid {
539                file: path.clone(),
540                message: err.to_string(),
541            }
542        })?;
543        let config_file = match (explicit, path) {
544            (Some((_, source)), Some(path)) => Sourced::new(Some(path), source, Scope::Global),
545            (None, Some(path)) => Sourced::new(
546                Some(path),
547                Source::Derived { from: "discovery" },
548                Scope::Global,
549            ),
550            (_, None) => Sourced::new(None, Source::Default { rule: "no-config" }, Scope::Global),
551        };
552        Ok(Loaded {
553            config_snapshot: chain,
554            ..self.decide(config, config_file, false)?
555        })
556    }
557
558    /// The steps of [`Self::load`] with a config that the caller built.
559    #[cfg(any(test, feature = "testing"))]
560    fn inline(&self, config: FallowConfig) -> Result<Loaded, ResolveError> {
561        steps::validate_config(self.root, &config).map_err(|err| ResolveError::ConfigInvalid {
562            file: None,
563            message: err.to_string(),
564        })?;
565        let config_file = Sourced::new(
566            None,
567            Source::Derived {
568                from: "inline-config",
569            },
570            Scope::Global,
571        );
572        self.decide(config, config_file, false)
573    }
574
575    /// The steps of [`Self::load`] with the default config.
576    fn defaults(&self) -> Result<Loaded, ResolveError> {
577        let config_file = Sourced::new(
578            None,
579            Source::Derived {
580                from: "config-fallback",
581            },
582            Scope::Global,
583        );
584        self.decide(FallowConfig::default(), config_file, true)
585    }
586
587    fn decide(
588        &self,
589        file: FallowConfig,
590        config_file: Sourced<Option<PathBuf>>,
591        fell_back: bool,
592    ) -> Result<Loaded, ResolveError> {
593        let path = config_file.value().clone();
594        let plan = self.plan(&file)?;
595        let production =
596            decide_production(&self.production_inputs(), &file.production, path.as_deref());
597        let selection = plan_selections(plan, self.inputs, path.as_deref());
598        let decisions = PerAnalysis {
599            dead_code: AnalysisDecision {
600                selection: selection.dead_code,
601                production: production.dead_code,
602            },
603            health: AnalysisDecision {
604                selection: selection.health,
605                production: production.health,
606            },
607            dupes: AnalysisDecision {
608                selection: selection.dupes,
609                production: production.dupes,
610            },
611        };
612        let mut settings = self.settings(&file, path.as_deref());
613        let (mut off, mut on) =
614            self.mode_entries(&file, path.is_some(), &decisions, &settings, fell_back)?;
615        if self.inputs.surface() == Surface::Lsp {
616            let mut scoped = false;
617            for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
618                scoped |= steps::scope_cache_dir_to_root(&mut entry.config);
619            }
620            if scoped {
621                settings.cache_dir = Sourced::new(
622                    PathBuf::new(),
623                    Source::Derived {
624                        from: "editor-cache-per-root",
625                    },
626                    Scope::Global,
627                );
628            }
629        }
630        let cache_dir = off.as_ref().or(on.as_ref()).map_or_else(
631            || self.cache_dir_without_entry(file.cache.dir.clone()),
632            |entry| entry.config.cache_dir.clone(),
633        );
634        settings.cache_dir = settings.cache_dir.map(|_| cache_dir);
635        let type_aware = super::type_aware::decision(
636            self.inputs.command,
637            &self.inputs.type_aware,
638            self.env,
639            TypeAwareConfigInput {
640                section: &file.type_aware,
641                audit: file.audit.type_aware,
642                file: path.as_deref(),
643            },
644        );
645        Ok(Loaded {
646            file,
647            config_file,
648            config_snapshot: ConfigChainSnapshot::default(),
649            decisions,
650            settings,
651            type_aware,
652            off,
653            on,
654        })
655    }
656
657    fn plan(&self, file: &FallowConfig) -> Result<RunPlan, ResolveError> {
658        let request = run_request(self.inputs.command, &self.inputs.selection);
659        let plan = fallow_config::plan_run(file.plan_sections(), request);
660        if plan.runs_any() {
661            return Ok(plan);
662        }
663        let cause = if [request.dead_code, request.duplication, request.health]
664            .iter()
665            .all(|request| *request == AnalysisRequest::Excluded)
666        {
667            EmptyCause::Request
668        } else if self.inputs.surface() == Surface::Cli {
669            EmptyCause::Config
670        } else {
671            return Ok(plan);
672        };
673        Err(ResolveError::NothingSelected {
674            command: self.inputs.command,
675            cause,
676        })
677    }
678
679    /// The production inputs of the run: the given values, and the variables
680    /// that the env policy lets the run read.
681    fn production_inputs(&self) -> ProductionInputs {
682        let env = |var| self.env.bool(var).set();
683        ProductionInputs {
684            global_flag: self.inputs.production,
685            own_flag: PerAnalysis {
686                dead_code: self.inputs.production_dead_code,
687                health: self.inputs.production_health,
688                dupes: self.inputs.production_dupes,
689            },
690            global_env: env(EnvVar::Production),
691            own_env: PerAnalysis {
692                dead_code: env(EnvVar::ProductionDeadCode),
693                health: env(EnvVar::ProductionHealth),
694                dupes: env(EnvVar::ProductionDupes),
695            },
696        }
697    }
698
699    /// One resolved config for each production mode that a planned analysis
700    /// uses.
701    fn mode_entries(
702        &self,
703        file: &FallowConfig,
704        from_file: bool,
705        decisions: &PerAnalysis<AnalysisDecision>,
706        settings: &RunSettings,
707        lossy: bool,
708    ) -> Result<(Option<ModeEntry>, Option<ModeEntry>), ResolveError> {
709        let needs = |on: bool| {
710            [&decisions.dead_code, &decisions.dupes, &decisions.health]
711                .iter()
712                .any(|decision| {
713                    decision.selection.value().runs() && *decision.production.value() == on
714                })
715        };
716        let entry = |on: bool| -> Result<Option<ModeEntry>, ResolveError> {
717            if !needs(on) {
718                return Ok(None);
719            }
720            let mut config = file.clone();
721            steps::flatten_production(&mut config, from_file, on);
722            let options = settings.resolve_options();
723            let given = self.given_settings();
724            let env = given.env_for_steps(self.env);
725            let mut entry = if lossy {
726                steps::mode_entry_lossy(self.root, config, options, &env)
727            } else {
728                steps::mode_entry(self.root, config, options, &env).map_err(|err| {
729                    ResolveError::Workspace {
730                        message: err.to_string(),
731                    }
732                })?
733            };
734            given.apply(&mut entry.config);
735            Ok(Some(entry))
736        };
737        Ok((entry(false)?, entry(true)?))
738    }
739
740    /// The given settings that win over the environment.
741    fn given_settings(&self) -> GivenSettings {
742        let inputs = self.inputs;
743        GivenSettings {
744            max_file_size_mb: inputs.max_file_size_mb.as_ref().map(|given| given.value),
745            cache_dir: inputs.cache_dir.as_ref().map(|given| given.value.clone()),
746            include_entry_exports: inputs
747                .include_entry_exports
748                .as_ref()
749                .map(|given| given.value),
750            package_baselines: inputs.package_baselines.as_ref().map(|given| given.value),
751        }
752    }
753}
754
755/// The run request of a command and its selection input.
756fn run_request(command: CommandKind, selection: &SelectionInput) -> RunRequest {
757    let run_command = if command == CommandKind::Audit {
758        RunCommand::Audit
759    } else {
760        RunCommand::Combined
761    };
762    match selection {
763        SelectionInput::Lists { only, skip, .. } => RunRequest::from_lists(run_command, only, skip),
764        SelectionInput::Booleans {
765            dead_code,
766            duplication,
767            health,
768            ..
769        } => RunRequest::from_booleans(run_command, *dead_code, *duplication, *health),
770        SelectionInput::Options {
771            dead_code,
772            duplication,
773            health,
774            ..
775        } => RunRequest::from_options(run_command, *dead_code, *duplication, *health),
776        SelectionInput::Single(analysis) => {
777            let request = |candidate| {
778                if candidate == *analysis {
779                    AnalysisRequest::Named
780                } else {
781                    AnalysisRequest::Excluded
782                }
783            };
784            RunRequest {
785                command: run_command,
786                dead_code: request(PlannedAnalysis::DeadCode),
787                duplication: request(PlannedAnalysis::Duplication),
788                health: request(PlannedAnalysis::Health),
789            }
790        }
791    }
792}
793
794/// The selection of each analysis with its source.
795fn plan_selections(
796    plan: RunPlan,
797    inputs: &RunInputs,
798    file: Option<&Path>,
799) -> PerAnalysis<Sourced<AnalysisSelection>> {
800    let request_source = match &inputs.selection {
801        SelectionInput::Lists { origin, .. }
802        | SelectionInput::Booleans { origin, .. }
803        | SelectionInput::Options { origin, .. } => Source::Given { origin: *origin },
804        SelectionInput::Single(_) => Source::Derived { from: "command" },
805    };
806    let request = run_request(inputs.command, &inputs.selection);
807    let sourced = |selection: AnalysisSelection, analysis: PlannedAnalysis| {
808        let source = if let Some(key) = skip_key(selection) {
809            file.map_or(Source::Derived { from: "config" }, |file| {
810                Source::ConfigFile {
811                    file: file.to_path_buf(),
812                    key: config_key_name(key),
813                }
814            })
815        } else if request_is_default(request, analysis) {
816            Source::Default {
817                rule: "runs-by-default",
818            }
819        } else {
820            request_source.clone()
821        };
822        Sourced::new(selection, source, Scope::Analysis)
823    };
824    PerAnalysis {
825        dead_code: sourced(plan.dead_code, PlannedAnalysis::DeadCode),
826        health: sourced(plan.health, PlannedAnalysis::Health),
827        dupes: sourced(plan.duplication, PlannedAnalysis::Duplication),
828    }
829}
830
831fn request_is_default(request: RunRequest, analysis: PlannedAnalysis) -> bool {
832    let value = match analysis {
833        PlannedAnalysis::DeadCode => request.dead_code,
834        PlannedAnalysis::Duplication => request.duplication,
835        PlannedAnalysis::Health => request.health,
836    };
837    value == AnalysisRequest::Default
838}
839
840impl Context<'_> {
841    /// The settings of the run with their sources. The values equal the
842    /// values that the steps write on each resolved config.
843    fn settings(&self, file: &FallowConfig, path: Option<&Path>) -> RunSettings {
844        let inputs = self.inputs;
845        let default = |rule| Source::Default { rule };
846        let environment = |var: EnvVar| Source::Environment { name: var.name() };
847        let config_key = |key| {
848            path.map_or(Source::Derived { from: "config" }, |file| {
849                Source::ConfigFile {
850                    file: file.to_path_buf(),
851                    key,
852                }
853            })
854        };
855        let pick_given = |given: Option<&Given<bool>>, fallback: Sourced<bool>| {
856            given.map_or(fallback, |given| given_value(given, Scope::Global))
857        };
858        let threads = inputs.threads.as_ref().map_or_else(
859            || {
860                Sourced::new(
861                    super::available_threads(),
862                    default("available-parallelism"),
863                    Scope::Global,
864                )
865            },
866            |given| given_value(given, Scope::Global),
867        );
868        let no_cache = pick_given(
869            inputs.no_cache.as_ref(),
870            Sourced::new(false, default("cache-on"), Scope::Global),
871        );
872        let max_file_size_bytes =
873            match (&inputs.max_file_size_mb, steps::max_file_size_env(self.env)) {
874                (Some(given), _) => Sourced::new(
875                    fallow_config::resolve_max_file_size_bytes(Some(given.value)),
876                    given_source(given),
877                    Scope::Global,
878                ),
879                (None, Some(mb)) => Sourced::new(
880                    fallow_config::resolve_max_file_size_bytes(Some(mb)),
881                    environment(EnvVar::MaxFileSize),
882                    Scope::Global,
883                ),
884                (None, None) => Sourced::new(
885                    fallow_config::resolve_max_file_size_bytes(None),
886                    default("max-file-size"),
887                    Scope::Global,
888                ),
889            };
890        let cache_max_size_mb = match self
891            .env
892            .get(EnvVar::CacheMaxSize)
893            .and_then(fallow_config::cache_max_size_from_env_value)
894        {
895            Some(mb) => Sourced::new(Some(mb), environment(EnvVar::CacheMaxSize), Scope::Global),
896            None if file.cache.max_size_mb.is_some() => Sourced::new(
897                file.cache.max_size_mb,
898                config_key("cache.maxSizeMb"),
899                Scope::Global,
900            ),
901            None => Sourced::new(None, default("cache-size"), Scope::Global),
902        };
903        let package_baselines = pick_given(
904            inputs.package_baselines.as_ref(),
905            match self.env.get(EnvVar::PackageBaselines) {
906                Some(raw) if fallow_config::package_baselines_disabled_by_env_value(raw) => {
907                    Sourced::new(false, environment(EnvVar::PackageBaselines), Scope::Global)
908                }
909                _ => Sourced::new(true, default("package-baselines-on"), Scope::Global),
910            },
911        );
912        let include_entry_exports = pick_given(
913            inputs.include_entry_exports.as_ref(),
914            if file.include_entry_exports {
915                Sourced::new(true, config_key("includeEntryExports"), Scope::Global)
916            } else {
917                Sourced::new(false, default("entry-exports-off"), Scope::Global)
918            },
919        );
920        RunSettings {
921            threads,
922            no_cache,
923            allow_remote_extends: self.allow_remote_extends(),
924            max_file_size_bytes,
925            cache_dir: self.cache_dir_source(file, path),
926            cache_max_size_mb,
927            package_baselines,
928            include_entry_exports,
929            output: inputs.output,
930            quiet: inputs.quiet,
931        }
932    }
933
934    /// The source of the cache directory. [`Context::decide`] sets the value.
935    fn cache_dir_source(&self, file: &FallowConfig, path: Option<&Path>) -> Sourced<PathBuf> {
936        let source = if let Some(given) = &self.inputs.cache_dir {
937            given_source(given)
938        } else if self.cache_dir_env().is_some() {
939            Source::Environment {
940                name: EnvVar::CacheDir.name(),
941            }
942        } else {
943            match (path, &file.cache.dir) {
944                (Some(path), Some(_)) => Source::ConfigFile {
945                    file: path.to_path_buf(),
946                    key: "cache.dir",
947                },
948                _ => Source::Default { rule: "cache-dir" },
949            }
950        };
951        Sourced::new(PathBuf::new(), source, Scope::Global)
952    }
953
954    fn cache_dir_env(&self) -> Option<PathBuf> {
955        self.env
956            .get(EnvVar::CacheDir)
957            .map(std::ffi::OsStr::to_os_string)
958            .and_then(fallow_config::cache_dir_from_env_value)
959    }
960
961    /// The cache directory of a run that resolves no config, by the rules of
962    /// a resolved config.
963    fn cache_dir_without_entry(&self, configured: Option<PathBuf>) -> PathBuf {
964        let host = self
965            .inputs
966            .cache_dir
967            .as_ref()
968            .map(|given| given.value.clone())
969            .or_else(|| self.cache_dir_env());
970        host.map_or_else(
971            || fallow_config::config_cache_dir(self.root, configured),
972            |dir| join_cwd(&dir, Some(self.root)).unwrap_or(dir),
973        )
974    }
975}