1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum InputField {
24 Root,
26 ConfigPath,
28 Threads,
30 Env(EnvVar),
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum InputProblem {
37 CwdUnavailable,
40 Invalid,
42 Zero,
44 InvalidValue,
46 NotUnicode,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum EmptyCause {
53 Request,
55 Config,
57}
58
59#[derive(Debug)]
61#[non_exhaustive]
62pub enum ResolveError {
63 Input {
65 field: InputField,
67 problem: InputProblem,
69 message: String,
71 },
72 ConfigLoad(ConfigLoadError),
74 ConfigInvalid {
76 file: Option<PathBuf>,
78 message: String,
80 },
81 Workspace {
83 message: String,
85 },
86 NothingSelected {
88 command: CommandKind,
90 cause: EmptyCause,
92 },
93}
94
95impl ResolveError {
96 #[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 const fn is_config_error(&self) -> bool {
109 matches!(
110 self,
111 Self::ConfigLoad(_) | Self::ConfigInvalid { .. } | Self::Workspace { .. }
112 )
113 }
114
115 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
152pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub enum BaseConfig {
176 Head,
179 BaseCopy,
185}
186
187#[derive(Debug, Clone)]
189pub struct BaseSide {
190 pub root: Given<PathBuf>,
192 pub config: BaseConfig,
194 pub cache_dir: Option<Given<PathBuf>>,
197}
198
199pub fn resolve_base_run(head: &ResolvedRun, base: BaseSide) -> Result<ResolvedRun, ResolveError> {
207 resolve_base_side(head, base, false)
208}
209
210pub 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
257fn 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
279fn 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#[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
326fn 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 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
409fn 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
478struct Context<'a> {
480 inputs: &'a RunInputs,
481 env: &'a EnvSnapshot,
483 root: &'a Path,
484}
485
486struct 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 fn load(&self, explicit: Option<(&Path, Source)>) -> Result<Loaded, ResolveError> {
523 let options = ConfigFileOptions::new(*self.allow_remote_extends().value(), self.env);
524 let ConfigFile {
525 config,
526 path,
527 chain,
528 } = load_config_file(self.root, explicit.as_ref().map(|(path, _)| *path), options)
529 .map_err(ResolveError::ConfigLoad)?;
530 steps::validate_command_config(self.inputs.command, self.root, &config).map_err(|err| {
531 ResolveError::ConfigInvalid {
532 file: path.clone(),
533 message: err.to_string(),
534 }
535 })?;
536 let config_file = match (explicit, path) {
537 (Some((_, source)), Some(path)) => Sourced::new(Some(path), source, Scope::Global),
538 (None, Some(path)) => Sourced::new(
539 Some(path),
540 Source::Derived { from: "discovery" },
541 Scope::Global,
542 ),
543 (_, None) => Sourced::new(None, Source::Default { rule: "no-config" }, Scope::Global),
544 };
545 Ok(Loaded {
546 config_snapshot: chain,
547 ..self.decide(config, config_file, false)?
548 })
549 }
550
551 #[cfg(any(test, feature = "testing"))]
553 fn inline(&self, config: FallowConfig) -> Result<Loaded, ResolveError> {
554 steps::validate_config(self.root, &config).map_err(|err| ResolveError::ConfigInvalid {
555 file: None,
556 message: err.to_string(),
557 })?;
558 let config_file = Sourced::new(
559 None,
560 Source::Derived {
561 from: "inline-config",
562 },
563 Scope::Global,
564 );
565 self.decide(config, config_file, false)
566 }
567
568 fn defaults(&self) -> Result<Loaded, ResolveError> {
570 let config_file = Sourced::new(
571 None,
572 Source::Derived {
573 from: "config-fallback",
574 },
575 Scope::Global,
576 );
577 self.decide(FallowConfig::default(), config_file, true)
578 }
579
580 fn decide(
581 &self,
582 file: FallowConfig,
583 config_file: Sourced<Option<PathBuf>>,
584 fell_back: bool,
585 ) -> Result<Loaded, ResolveError> {
586 let path = config_file.value().clone();
587 let plan = self.plan(&file)?;
588 let production =
589 decide_production(&self.production_inputs(), &file.production, path.as_deref());
590 let selection = plan_selections(plan, self.inputs, path.as_deref());
591 let decisions = PerAnalysis {
592 dead_code: AnalysisDecision {
593 selection: selection.dead_code,
594 production: production.dead_code,
595 },
596 health: AnalysisDecision {
597 selection: selection.health,
598 production: production.health,
599 },
600 dupes: AnalysisDecision {
601 selection: selection.dupes,
602 production: production.dupes,
603 },
604 };
605 let mut settings = self.settings(&file, path.as_deref());
606 let (mut off, mut on) =
607 self.mode_entries(&file, path.is_some(), &decisions, &settings, fell_back)?;
608 if self.inputs.surface() == Surface::Lsp {
609 let mut scoped = false;
610 for entry in [off.as_mut(), on.as_mut()].into_iter().flatten() {
611 scoped |= steps::scope_cache_dir_to_root(&mut entry.config);
612 }
613 if scoped {
614 settings.cache_dir = Sourced::new(
615 PathBuf::new(),
616 Source::Derived {
617 from: "editor-cache-per-root",
618 },
619 Scope::Global,
620 );
621 }
622 }
623 let cache_dir = off.as_ref().or(on.as_ref()).map_or_else(
624 || self.cache_dir_without_entry(file.cache.dir.clone()),
625 |entry| entry.config.cache_dir.clone(),
626 );
627 settings.cache_dir = settings.cache_dir.map(|_| cache_dir);
628 let type_aware = super::type_aware::decision(
629 self.inputs.command,
630 &self.inputs.type_aware,
631 self.env,
632 TypeAwareConfigInput {
633 section: &file.type_aware,
634 audit: file.audit.type_aware,
635 file: path.as_deref(),
636 },
637 );
638 Ok(Loaded {
639 file,
640 config_file,
641 config_snapshot: ConfigChainSnapshot::default(),
642 decisions,
643 settings,
644 type_aware,
645 off,
646 on,
647 })
648 }
649
650 fn plan(&self, file: &FallowConfig) -> Result<RunPlan, ResolveError> {
651 let request = run_request(self.inputs.command, &self.inputs.selection);
652 let plan = fallow_config::plan_run(file.plan_sections(), request);
653 if plan.runs_any() {
654 return Ok(plan);
655 }
656 let cause = if [request.dead_code, request.duplication, request.health]
657 .iter()
658 .all(|request| *request == AnalysisRequest::Excluded)
659 {
660 EmptyCause::Request
661 } else if self.inputs.surface() == Surface::Cli {
662 EmptyCause::Config
663 } else {
664 return Ok(plan);
665 };
666 Err(ResolveError::NothingSelected {
667 command: self.inputs.command,
668 cause,
669 })
670 }
671
672 fn production_inputs(&self) -> ProductionInputs {
675 let env = |var| self.env.bool(var).set();
676 ProductionInputs {
677 global_flag: self.inputs.production,
678 own_flag: PerAnalysis {
679 dead_code: self.inputs.production_dead_code,
680 health: self.inputs.production_health,
681 dupes: self.inputs.production_dupes,
682 },
683 global_env: env(EnvVar::Production),
684 own_env: PerAnalysis {
685 dead_code: env(EnvVar::ProductionDeadCode),
686 health: env(EnvVar::ProductionHealth),
687 dupes: env(EnvVar::ProductionDupes),
688 },
689 }
690 }
691
692 fn mode_entries(
695 &self,
696 file: &FallowConfig,
697 from_file: bool,
698 decisions: &PerAnalysis<AnalysisDecision>,
699 settings: &RunSettings,
700 lossy: bool,
701 ) -> Result<(Option<ModeEntry>, Option<ModeEntry>), ResolveError> {
702 let needs = |on: bool| {
703 [&decisions.dead_code, &decisions.dupes, &decisions.health]
704 .iter()
705 .any(|decision| {
706 decision.selection.value().runs() && *decision.production.value() == on
707 })
708 };
709 let entry = |on: bool| -> Result<Option<ModeEntry>, ResolveError> {
710 if !needs(on) {
711 return Ok(None);
712 }
713 let mut config = file.clone();
714 steps::flatten_production(&mut config, from_file, on);
715 let options = settings.resolve_options();
716 let given = self.given_settings();
717 let env = given.env_for_steps(self.env);
718 let mut entry = if lossy {
719 steps::mode_entry_lossy(self.root, config, options, &env)
720 } else {
721 steps::mode_entry(self.root, config, options, &env).map_err(|err| {
722 ResolveError::Workspace {
723 message: err.to_string(),
724 }
725 })?
726 };
727 given.apply(&mut entry.config);
728 Ok(Some(entry))
729 };
730 Ok((entry(false)?, entry(true)?))
731 }
732
733 fn given_settings(&self) -> GivenSettings {
735 let inputs = self.inputs;
736 GivenSettings {
737 max_file_size_mb: inputs.max_file_size_mb.as_ref().map(|given| given.value),
738 cache_dir: inputs.cache_dir.as_ref().map(|given| given.value.clone()),
739 include_entry_exports: inputs
740 .include_entry_exports
741 .as_ref()
742 .map(|given| given.value),
743 package_baselines: inputs.package_baselines.as_ref().map(|given| given.value),
744 }
745 }
746}
747
748fn run_request(command: CommandKind, selection: &SelectionInput) -> RunRequest {
750 let run_command = if command == CommandKind::Audit {
751 RunCommand::Audit
752 } else {
753 RunCommand::Combined
754 };
755 match selection {
756 SelectionInput::Lists { only, skip, .. } => RunRequest::from_lists(run_command, only, skip),
757 SelectionInput::Booleans {
758 dead_code,
759 duplication,
760 health,
761 ..
762 } => RunRequest::from_booleans(run_command, *dead_code, *duplication, *health),
763 SelectionInput::Options {
764 dead_code,
765 duplication,
766 health,
767 ..
768 } => RunRequest::from_options(run_command, *dead_code, *duplication, *health),
769 SelectionInput::Single(analysis) => {
770 let request = |candidate| {
771 if candidate == *analysis {
772 AnalysisRequest::Named
773 } else {
774 AnalysisRequest::Excluded
775 }
776 };
777 RunRequest {
778 command: run_command,
779 dead_code: request(PlannedAnalysis::DeadCode),
780 duplication: request(PlannedAnalysis::Duplication),
781 health: request(PlannedAnalysis::Health),
782 }
783 }
784 }
785}
786
787fn plan_selections(
789 plan: RunPlan,
790 inputs: &RunInputs,
791 file: Option<&Path>,
792) -> PerAnalysis<Sourced<AnalysisSelection>> {
793 let request_source = match &inputs.selection {
794 SelectionInput::Lists { origin, .. }
795 | SelectionInput::Booleans { origin, .. }
796 | SelectionInput::Options { origin, .. } => Source::Given { origin: *origin },
797 SelectionInput::Single(_) => Source::Derived { from: "command" },
798 };
799 let request = run_request(inputs.command, &inputs.selection);
800 let sourced = |selection: AnalysisSelection, analysis: PlannedAnalysis| {
801 let source = if let Some(key) = skip_key(selection) {
802 file.map_or(Source::Derived { from: "config" }, |file| {
803 Source::ConfigFile {
804 file: file.to_path_buf(),
805 key: config_key_name(key),
806 }
807 })
808 } else if request_is_default(request, analysis) {
809 Source::Default {
810 rule: "runs-by-default",
811 }
812 } else {
813 request_source.clone()
814 };
815 Sourced::new(selection, source, Scope::Analysis)
816 };
817 PerAnalysis {
818 dead_code: sourced(plan.dead_code, PlannedAnalysis::DeadCode),
819 health: sourced(plan.health, PlannedAnalysis::Health),
820 dupes: sourced(plan.duplication, PlannedAnalysis::Duplication),
821 }
822}
823
824fn request_is_default(request: RunRequest, analysis: PlannedAnalysis) -> bool {
825 let value = match analysis {
826 PlannedAnalysis::DeadCode => request.dead_code,
827 PlannedAnalysis::Duplication => request.duplication,
828 PlannedAnalysis::Health => request.health,
829 };
830 value == AnalysisRequest::Default
831}
832
833impl Context<'_> {
834 fn settings(&self, file: &FallowConfig, path: Option<&Path>) -> RunSettings {
837 let inputs = self.inputs;
838 let default = |rule| Source::Default { rule };
839 let environment = |var: EnvVar| Source::Environment { name: var.name() };
840 let config_key = |key| {
841 path.map_or(Source::Derived { from: "config" }, |file| {
842 Source::ConfigFile {
843 file: file.to_path_buf(),
844 key,
845 }
846 })
847 };
848 let pick_given = |given: Option<&Given<bool>>, fallback: Sourced<bool>| {
849 given.map_or(fallback, |given| given_value(given, Scope::Global))
850 };
851 let threads = inputs.threads.as_ref().map_or_else(
852 || {
853 Sourced::new(
854 super::available_threads(),
855 default("available-parallelism"),
856 Scope::Global,
857 )
858 },
859 |given| given_value(given, Scope::Global),
860 );
861 let no_cache = pick_given(
862 inputs.no_cache.as_ref(),
863 Sourced::new(false, default("cache-on"), Scope::Global),
864 );
865 let max_file_size_bytes =
866 match (&inputs.max_file_size_mb, steps::max_file_size_env(self.env)) {
867 (Some(given), _) => Sourced::new(
868 fallow_config::resolve_max_file_size_bytes(Some(given.value)),
869 given_source(given),
870 Scope::Global,
871 ),
872 (None, Some(mb)) => Sourced::new(
873 fallow_config::resolve_max_file_size_bytes(Some(mb)),
874 environment(EnvVar::MaxFileSize),
875 Scope::Global,
876 ),
877 (None, None) => Sourced::new(
878 fallow_config::resolve_max_file_size_bytes(None),
879 default("max-file-size"),
880 Scope::Global,
881 ),
882 };
883 let cache_max_size_mb = match self
884 .env
885 .get(EnvVar::CacheMaxSize)
886 .and_then(fallow_config::cache_max_size_from_env_value)
887 {
888 Some(mb) => Sourced::new(Some(mb), environment(EnvVar::CacheMaxSize), Scope::Global),
889 None if file.cache.max_size_mb.is_some() => Sourced::new(
890 file.cache.max_size_mb,
891 config_key("cache.maxSizeMb"),
892 Scope::Global,
893 ),
894 None => Sourced::new(None, default("cache-size"), Scope::Global),
895 };
896 let package_baselines = pick_given(
897 inputs.package_baselines.as_ref(),
898 match self.env.get(EnvVar::PackageBaselines) {
899 Some(raw) if fallow_config::package_baselines_disabled_by_env_value(raw) => {
900 Sourced::new(false, environment(EnvVar::PackageBaselines), Scope::Global)
901 }
902 _ => Sourced::new(true, default("package-baselines-on"), Scope::Global),
903 },
904 );
905 let include_entry_exports = pick_given(
906 inputs.include_entry_exports.as_ref(),
907 if file.include_entry_exports {
908 Sourced::new(true, config_key("includeEntryExports"), Scope::Global)
909 } else {
910 Sourced::new(false, default("entry-exports-off"), Scope::Global)
911 },
912 );
913 RunSettings {
914 threads,
915 no_cache,
916 allow_remote_extends: self.allow_remote_extends(),
917 max_file_size_bytes,
918 cache_dir: self.cache_dir_source(file, path),
919 cache_max_size_mb,
920 package_baselines,
921 include_entry_exports,
922 output: inputs.output,
923 quiet: inputs.quiet,
924 }
925 }
926
927 fn cache_dir_source(&self, file: &FallowConfig, path: Option<&Path>) -> Sourced<PathBuf> {
929 let source = if let Some(given) = &self.inputs.cache_dir {
930 given_source(given)
931 } else if self.cache_dir_env().is_some() {
932 Source::Environment {
933 name: EnvVar::CacheDir.name(),
934 }
935 } else {
936 match (path, &file.cache.dir) {
937 (Some(path), Some(_)) => Source::ConfigFile {
938 file: path.to_path_buf(),
939 key: "cache.dir",
940 },
941 _ => Source::Default { rule: "cache-dir" },
942 }
943 };
944 Sourced::new(PathBuf::new(), source, Scope::Global)
945 }
946
947 fn cache_dir_env(&self) -> Option<PathBuf> {
948 self.env
949 .get(EnvVar::CacheDir)
950 .map(std::ffi::OsStr::to_os_string)
951 .and_then(fallow_config::cache_dir_from_env_value)
952 }
953
954 fn cache_dir_without_entry(&self, configured: Option<PathBuf>) -> PathBuf {
957 let host = self
958 .inputs
959 .cache_dir
960 .as_ref()
961 .map(|given| given.value.clone())
962 .or_else(|| self.cache_dir_env());
963 host.map_or_else(
964 || fallow_config::config_cache_dir(self.root, configured),
965 |dir| join_cwd(&dir, Some(self.root)).unwrap_or(dir),
966 )
967 }
968}