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