1use std::path::PathBuf;
11
12pub use fallow_config::{CommandKind, EnvSnapshot, EnvVar, HostInputs, SelectionInput, Surface};
13pub use fallow_engine::resolved_run::{
14 AnalysisSlot, ResolveError, ResolvedRun, Runnable, resolve_run,
15};
16#[cfg(feature = "testing")]
17pub use fallow_engine::resolved_run::{parity, testing};
18
19#[cfg(feature = "testing")]
27pub fn resolve_audit_head_run(options: &crate::AuditOptions) -> ProgrammaticResult<ResolvedRun> {
28 let folded = crate::runtime::analysis_options_for_audit(options, "HEAD");
29 crate::runtime::resolve_audit_run(options, &folded)
30}
31
32use fallow_config::{PlannedAnalysis, RunInputs};
33use fallow_engine::resolved_run::{InputField, InputProblem};
34use fallow_types::output_format::OutputFormat;
35use fallow_types::sourced::{Given, Origin};
36
37use crate::{AnalysisOptions, ProgrammaticError};
38
39type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
40
41#[derive(Debug, Clone)]
44#[non_exhaustive]
45pub enum ProgrammaticEntry {
46 DeadCode,
49 Duplication,
51 Health,
53 FeatureFlags,
55 List,
57 TracePath,
59 TraceChain,
61 TraceError,
63 TraceDependency,
65 DecisionSurface,
67 Mutation,
69 SimilarCode,
71 Doctor,
73 Combined {
75 dead_code: bool,
77 duplication: bool,
79 health: bool,
81 production_dead_code: Option<bool>,
83 production_health: Option<bool>,
85 production_dupes: Option<bool>,
87 },
88 Audit {
90 dead_code: Option<bool>,
92 duplication: Option<bool>,
94 health: Option<bool>,
96 production: bool,
99 production_dead_code: Option<bool>,
101 production_health: Option<bool>,
103 production_dupes: Option<bool>,
105 },
106}
107
108impl ProgrammaticEntry {
109 #[must_use]
111 pub const fn command(&self) -> CommandKind {
112 match self {
113 Self::DeadCode => CommandKind::DeadCode,
114 Self::Duplication => CommandKind::Dupes,
115 Self::Health => CommandKind::Health,
116 Self::FeatureFlags => CommandKind::Flags,
117 Self::List => CommandKind::List,
118 Self::TracePath => CommandKind::TracePath,
119 Self::TraceChain => CommandKind::TraceChain,
120 Self::TraceError => CommandKind::TraceError,
121 Self::TraceDependency => CommandKind::TraceDependency,
122 Self::DecisionSurface => CommandKind::DecisionSurface,
123 Self::Mutation => CommandKind::Mutation,
124 Self::SimilarCode => CommandKind::SimilarCode,
125 Self::Doctor => CommandKind::Doctor,
126 Self::Combined { .. } => CommandKind::Combined,
127 Self::Audit { .. } => CommandKind::Audit,
128 }
129 }
130
131 #[must_use]
133 pub const fn selection(&self) -> SelectionInput {
134 match self {
135 Self::Duplication => SelectionInput::Single(PlannedAnalysis::Duplication),
136 Self::Health => SelectionInput::Single(PlannedAnalysis::Health),
137 Self::Combined {
138 dead_code,
139 duplication,
140 health,
141 ..
142 } => SelectionInput::Booleans {
143 dead_code: *dead_code,
144 duplication: *duplication,
145 health: *health,
146 origin: Origin::ApiOption("combined"),
147 },
148 Self::Audit {
149 dead_code,
150 duplication,
151 health,
152 ..
153 } => SelectionInput::Options {
154 dead_code: *dead_code,
155 duplication: *duplication,
156 health: *health,
157 origin: Origin::ApiOption("audit"),
158 },
159 Self::DeadCode
160 | Self::FeatureFlags
161 | Self::List
162 | Self::TracePath
163 | Self::TraceChain
164 | Self::TraceError
165 | Self::TraceDependency
166 | Self::DecisionSurface
167 | Self::Mutation
168 | Self::SimilarCode
169 | Self::Doctor => SelectionInput::Single(PlannedAnalysis::DeadCode),
170 }
171 }
172
173 const fn reads_production(&self) -> bool {
177 !matches!(self, Self::Mutation | Self::SimilarCode | Self::Doctor)
178 }
179}
180
181#[derive(Debug, Clone, Default)]
183pub(crate) struct RouteSettings {
184 pub include_entry_exports: bool,
186 pub audit_base: Option<NamedAuditBase>,
188}
189
190#[derive(Debug, Clone)]
193pub(crate) enum NamedAuditBase {
194 Base(String),
196 ChangedSince(String),
198}
199
200impl NamedAuditBase {
201 pub(crate) fn of(options: &crate::AuditOptions) -> Option<Self> {
203 options.base.clone().map(Self::Base).or_else(|| {
204 options
205 .analysis
206 .changed_since
207 .clone()
208 .map(Self::ChangedSince)
209 })
210 }
211}
212
213pub fn resolve_programmatic_run(
228 options: &AnalysisOptions,
229 entry: &ProgrammaticEntry,
230) -> ProgrammaticResult<ResolvedRun> {
231 resolve_route_run(options, entry, RouteSettings::default())
232}
233
234pub(crate) fn resolve_route_run(
236 options: &AnalysisOptions,
237 entry: &ProgrammaticEntry,
238 route: RouteSettings,
239) -> ProgrammaticResult<ResolvedRun> {
240 resolve_route_run_raw(options, entry, route).map_err(|err| programmatic_error(&err))
241}
242
243pub(crate) fn resolve_route_run_raw(
246 options: &AnalysisOptions,
247 entry: &ProgrammaticEntry,
248 route: RouteSettings,
249) -> Result<ResolvedRun, ResolveError> {
250 fallow_engine::resolved_run::resolve_run(&run_inputs(options, entry, route))
251}
252
253struct OptionName {
256 api: &'static str,
257 node: &'static str,
258 mcp: &'static str,
259}
260
261const ROOT: OptionName = OptionName {
262 api: "analysis.root",
263 node: "root",
264 mcp: "root",
265};
266const CONFIG_PATH: OptionName = OptionName {
267 api: "analysis.config_path",
268 node: "configPath",
269 mcp: "config",
270};
271const ALLOW_REMOTE_EXTENDS: OptionName = OptionName {
272 api: "analysis.allow_remote_extends",
273 node: "allowRemoteExtends",
274 mcp: "allow_remote_extends",
275};
276const NO_CACHE: OptionName = OptionName {
277 api: "analysis.no_cache",
278 node: "noCache",
279 mcp: "no_cache",
280};
281const THREADS: OptionName = OptionName {
282 api: "analysis.threads",
283 node: "threads",
284 mcp: "threads",
285};
286const NO_PACKAGE_BASELINES: OptionName = OptionName {
287 api: "analysis.no_package_baselines",
288 node: "noPackageBaselines",
289 mcp: "no_package_baselines",
290};
291const PRODUCTION_OVERRIDE: OptionName = OptionName {
292 api: "analysis.production_override",
293 node: "production",
294 mcp: "production",
295};
296const PRODUCTION: OptionName = OptionName {
297 api: "analysis.production",
298 node: "production",
299 mcp: "production",
300};
301const AUDIT_PRODUCTION: OptionName = OptionName {
302 api: "audit.production",
303 node: "production",
304 mcp: "production",
305};
306const INCLUDE_ENTRY_EXPORTS: OptionName = OptionName {
307 api: "include_entry_exports",
308 node: "includeEntryExports",
309 mcp: "include_entry_exports",
310};
311const PRODUCTION_DEAD_CODE: OptionName = OptionName {
312 api: "production_dead_code",
313 node: "productionDeadCode",
314 mcp: "production_dead_code",
315};
316const PRODUCTION_HEALTH: OptionName = OptionName {
317 api: "production_health",
318 node: "productionHealth",
319 mcp: "production_health",
320};
321const PRODUCTION_DUPES: OptionName = OptionName {
322 api: "production_dupes",
323 node: "productionDupes",
324 mcp: "production_dupes",
325};
326const AUDIT_BASE: OptionName = OptionName {
327 api: "audit.base",
328 node: "base",
329 mcp: "base",
330};
331const CHANGED_SINCE: OptionName = OptionName {
332 api: "analysis.changed_since",
333 node: "changedSince",
334 mcp: "changed_since",
335};
336const TYPE_AWARE: OptionName = OptionName {
337 api: "analysis.type_aware.enabled",
338 node: "typeAware.enabled",
339 mcp: "type_aware",
340};
341
342pub(crate) fn host_env(options: &AnalysisOptions) -> EnvSnapshot {
345 options
346 .host
347 .as_ref()
348 .map_or_else(EnvSnapshot::capture, |host| host.env.clone())
349}
350
351pub(crate) fn run_inputs(
353 options: &AnalysisOptions,
354 entry: &ProgrammaticEntry,
355 route: RouteSettings,
356) -> RunInputs {
357 let HostInputs { surface, env } = options.host.clone().unwrap_or_else(|| HostInputs {
358 surface: Surface::Api,
359 env: EnvSnapshot::capture(),
360 });
361 let origin = |name: OptionName| match surface {
362 Surface::Node => Origin::NodeOption(name.node),
363 Surface::Mcp => Origin::ToolParam(name.mcp),
364 Surface::Api | Surface::Cli | Surface::Lsp => Origin::ApiOption(name.api),
365 };
366 let given = |value, name| Given {
367 value,
368 origin: origin(name),
369 };
370 let when_true = |value: bool, name| value.then(|| given(true, name));
371 let mut inputs = RunInputs::new(surface, env, entry.command(), entry.selection());
372 inputs.root = options.root.clone().map(|root| Given {
373 value: root,
374 origin: origin(ROOT),
375 });
376 inputs.config_path = options.config_path.clone().map(|path: PathBuf| Given {
377 value: path,
378 origin: origin(CONFIG_PATH),
379 });
380 inputs.allow_remote_extends = when_true(options.allow_remote_extends, ALLOW_REMOTE_EXTENDS);
381 inputs.no_cache = when_true(options.no_cache, NO_CACHE);
382 inputs.threads = options.threads.map(|threads| Given {
383 value: threads,
384 origin: origin(THREADS),
385 });
386 inputs.package_baselines = options
387 .no_package_baselines
388 .then(|| given(false, NO_PACKAGE_BASELINES));
389 inputs.include_entry_exports = when_true(route.include_entry_exports, INCLUDE_ENTRY_EXPORTS);
390 inputs.audit_base = route.audit_base.map(|named| {
391 let (value, name) = match named {
392 NamedAuditBase::Base(value) => (value, AUDIT_BASE),
393 NamedAuditBase::ChangedSince(value) => (value, CHANGED_SINCE),
394 };
395 Given {
396 value,
397 origin: origin(name),
398 }
399 });
400 inputs.type_aware.enabled = options
401 .type_aware
402 .enabled
403 .map(|enabled| given(enabled, TYPE_AWARE));
404 inputs.output = OutputFormat::Json;
405 inputs.quiet = true;
406 if entry.reads_production() {
407 set_production(&mut inputs, options, entry, given);
408 }
409 inputs
410}
411
412fn set_production(
413 inputs: &mut RunInputs,
414 options: &AnalysisOptions,
415 entry: &ProgrammaticEntry,
416 given: impl Fn(bool, OptionName) -> Given<bool>,
417) {
418 let global_option = |legacy: bool, name| {
419 options
420 .production_override
421 .map(|value| given(value, PRODUCTION_OVERRIDE))
422 .or_else(|| legacy.then(|| given(true, name)))
423 };
424 let own = |value: Option<bool>, name| value.map(|value| given(value, name));
425 let (global, per_analysis) = match entry {
426 ProgrammaticEntry::Audit {
427 production,
428 production_dead_code,
429 production_health,
430 production_dupes,
431 ..
432 } => (
433 global_option(*production, AUDIT_PRODUCTION),
434 Some((*production_dead_code, *production_health, *production_dupes)),
435 ),
436 ProgrammaticEntry::Combined {
437 production_dead_code,
438 production_health,
439 production_dupes,
440 ..
441 } => (
442 global_option(options.production, PRODUCTION),
443 Some((*production_dead_code, *production_health, *production_dupes)),
444 ),
445 _ => (global_option(options.production, PRODUCTION), None),
446 };
447 inputs.production = global;
448 if let Some((dead_code, health, dupes)) = per_analysis {
449 inputs.production_dead_code = own(dead_code, PRODUCTION_DEAD_CODE);
450 inputs.production_health = own(health, PRODUCTION_HEALTH);
451 inputs.production_dupes = own(dupes, PRODUCTION_DUPES);
452 }
453}
454
455const CONFIG_LOAD_FAILED: &str = "FALLOW_CONFIG_LOAD_FAILED";
456const CONFIG_PATH_CONTEXT: &str = "analysis.configPath";
457
458pub(crate) const COMBINED_EMPTY_MESSAGE: &str =
460 "combined analysis requires at least one enabled section";
461
462pub(crate) const AUDIT_NO_ANALYSIS_MESSAGE: &str = "this audit selects no domain: the options, the audit.deadCode, audit.health and audit.dupes config keys, and duplicates.enabled leave nothing to run";
464
465pub(crate) fn programmatic_error(err: &ResolveError) -> ProgrammaticError {
468 let config_error = |message: String| {
469 ProgrammaticError::new(format!("failed to load config: {message}"), 2)
470 .with_code(CONFIG_LOAD_FAILED)
471 .with_context(CONFIG_PATH_CONTEXT)
472 };
473 match err {
474 ResolveError::Input {
475 field,
476 problem,
477 message,
478 } => {
479 let (code, context) = match (field, problem) {
480 (InputField::Root, InputProblem::CwdUnavailable) => {
481 ("FALLOW_CWD_UNAVAILABLE", "analysis.root")
482 }
483 (InputField::Root, _) => ("FALLOW_INVALID_ROOT", "analysis.root"),
484 (InputField::ConfigPath, _) => ("FALLOW_INVALID_CONFIG_PATH", CONFIG_PATH_CONTEXT),
485 (InputField::Threads, _) => ("FALLOW_INVALID_THREADS", "analysis.threads"),
486 (InputField::Env(EnvVar::TypeAware), _) => (
489 crate::TYPE_AWARE_CONFIG_UNSUPPORTED,
490 EnvVar::TypeAware.name(),
491 ),
492 (InputField::Env(var), _) => ("FALLOW_INVALID_ENV", var.name()),
493 };
494 ProgrammaticError::new(message.clone(), 2)
495 .with_code(code)
496 .with_context(context)
497 }
498 ResolveError::ConfigLoad(load) => config_error(load.chain().to_owned()),
499 ResolveError::NothingSelected { command, .. } => match command {
500 CommandKind::Audit => ProgrammaticError::new(AUDIT_NO_ANALYSIS_MESSAGE, 2)
501 .with_code("FALLOW_AUDIT_NO_ANALYSIS")
502 .with_context("audit"),
503 _ => ProgrammaticError::new(COMBINED_EMPTY_MESSAGE, 2)
504 .with_code("FALLOW_COMBINED_EMPTY")
505 .with_context("combined"),
506 },
507 _ => config_error(err.message()),
508 }
509}
510
511pub(crate) fn runnable(
518 run: &ResolvedRun,
519 analysis: PlannedAnalysis,
520) -> ProgrammaticResult<Runnable<'_>> {
521 match run.analysis(analysis) {
522 AnalysisSlot::Runs(runnable) => Ok(runnable),
523 AnalysisSlot::Skipped { .. } => Err(ProgrammaticError::new(
524 format!("the resolved run skips the {analysis:?} analysis"),
525 2,
526 )
527 .with_code("FALLOW_INTERNAL_ERROR")),
528 }
529}
530
531pub(crate) fn open_session_adjusted(
538 runnable: &Runnable<'_>,
539 adjust: impl FnOnce(&mut fallow_config::ResolvedConfig),
540) -> ProgrammaticResult<fallow_engine::session::AnalysisSession> {
541 runnable.open_session_adjusted(adjust).map_err(|err| {
542 ProgrammaticError::new(err.to_string(), 2).with_code("FALLOW_INTERNAL_ERROR")
543 })
544}
545
546#[cfg(test)]
547#[path = "run_tests.rs"]
548mod tests;
549
550#[cfg(test)]
551#[path = "run_parity_tests.rs"]
552mod parity_tests;