Skip to main content

fallow_api/
run.rs

1//! One resolved run for each programmatic call.
2//!
3//! Each typed runner that loads a config calls [`resolve_programmatic_run`]
4//! once with its own [`ProgrammaticEntry`]. The resolver loads and validates
5//! the config, decides the selection and the production mode of each
6//! analysis, and resolves one config for each production mode. The runner
7//! opens each session from that run, so the analyses of one call share one
8//! config load.
9
10use 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/// The head run of an audit with `options`, resolved through the steps of
20/// the audit runner. The base ref is `HEAD`, because the run does not depend
21/// on it. A parity row of a surface that calls the audit runner uses it.
22///
23/// # Errors
24///
25/// Returns the errors of the audit runner.
26#[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/// The typed runner that starts a run. Each entry maps to one
42/// [`CommandKind`] and one [`SelectionInput`].
43#[derive(Debug, Clone)]
44#[non_exhaustive]
45pub enum ProgrammaticEntry {
46    /// The dead-code runners: dead code, circular dependencies, boundary
47    /// violations and architecture.
48    DeadCode,
49    /// The duplication runner.
50    Duplication,
51    /// The health runner.
52    Health,
53    /// The feature flags runner.
54    FeatureFlags,
55    /// The project info and the boundary list runners.
56    List,
57    /// The import path trace.
58    TracePath,
59    /// The export, file and clone traces.
60    TraceChain,
61    /// The error trace.
62    TraceError,
63    /// The dependency trace.
64    TraceDependency,
65    /// The decision surface.
66    DecisionSurface,
67    /// The mutation runners.
68    Mutation,
69    /// The similar-code runners.
70    SimilarCode,
71    /// The doctor.
72    Doctor,
73    /// The combined runner.
74    Combined {
75        /// Run the dead-code analysis.
76        dead_code: bool,
77        /// Run the duplication analysis.
78        duplication: bool,
79        /// Run the health analysis.
80        health: bool,
81        /// The production mode of the dead-code analysis.
82        production_dead_code: Option<bool>,
83        /// The production mode of the health analysis.
84        production_health: Option<bool>,
85        /// The production mode of the duplication analysis.
86        production_dupes: Option<bool>,
87    },
88    /// The audit runner.
89    Audit {
90        /// The request for the dead-code analysis.
91        dead_code: Option<bool>,
92        /// The request for the duplication analysis.
93        duplication: Option<bool>,
94        /// The request for the health analysis.
95        health: Option<bool>,
96        /// `AuditOptions::production`: production mode for every analysis
97        /// when `analysis.production_override` is `None`.
98        production: bool,
99        /// The production mode of the dead-code analysis.
100        production_dead_code: Option<bool>,
101        /// The production mode of the health analysis.
102        production_health: Option<bool>,
103        /// The production mode of the duplication analysis.
104        production_dupes: Option<bool>,
105    },
106}
107
108impl ProgrammaticEntry {
109    /// The command of the entry.
110    #[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    /// How the entry selects its analyses.
132    #[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    /// Whether the runner of the entry reads the production options of
174    /// [`AnalysisOptions`]. The mutation, similar-code and doctor runners
175    /// take the production mode from the config only.
176    const fn reads_production(&self) -> bool {
177        !matches!(self, Self::Mutation | Self::SimilarCode | Self::Doctor)
178    }
179}
180
181/// Settings of one runner that are not in [`AnalysisOptions`].
182#[derive(Debug, Clone, Default)]
183pub(crate) struct RouteSettings {
184    /// The `include_entry_exports` option of the runner.
185    pub include_entry_exports: bool,
186    /// The base ref that the caller of an audit names.
187    pub audit_base: Option<NamedAuditBase>,
188}
189
190/// The base ref that the caller of an audit names, by the option that names
191/// it.
192#[derive(Debug, Clone)]
193pub(crate) enum NamedAuditBase {
194    /// The `base` option of the audit.
195    Base(String),
196    /// The `changed_since` option of the analysis.
197    ChangedSince(String),
198}
199
200impl NamedAuditBase {
201    /// The `base` option of `options`, else its `analysis.changed_since`.
202    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
213/// Resolve the run of one programmatic call.
214///
215/// `options.host` names the surface and the environment snapshot. `None`
216/// means the Rust API with a snapshot of the process environment. The surface
217/// names the origin of each given value: an option of the Rust API, an option
218/// of the Node bindings, or an MCP tool parameter.
219///
220/// # Errors
221///
222/// Returns the structured error of [`ProgrammaticError`] with the same code
223/// and context as the runners: `FALLOW_INVALID_ROOT`,
224/// `FALLOW_INVALID_CONFIG_PATH`, `FALLOW_INVALID_THREADS`,
225/// `FALLOW_CONFIG_LOAD_FAILED`, `FALLOW_COMBINED_EMPTY` or
226/// `FALLOW_AUDIT_NO_ANALYSIS`.
227pub fn resolve_programmatic_run(
228    options: &AnalysisOptions,
229    entry: &ProgrammaticEntry,
230) -> ProgrammaticResult<ResolvedRun> {
231    resolve_route_run(options, entry, RouteSettings::default())
232}
233
234/// [`resolve_programmatic_run`] with the settings of one runner.
235pub(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
243/// [`resolve_route_run`] with the error of the resolver, for a runner that
244/// maps some errors to its own code.
245pub(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
253/// The names of one option on the Rust API, on the Node bindings and as an
254/// MCP tool parameter.
255struct 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
342/// The environment snapshot of one programmatic call: the snapshot of
343/// `options.host`, else a snapshot of the process environment.
344pub(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
351/// The raw run inputs of one programmatic call.
352pub(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
458/// The message of `FALLOW_COMBINED_EMPTY`.
459pub(crate) const COMBINED_EMPTY_MESSAGE: &str =
460    "combined analysis requires at least one enabled section";
461
462/// The message of `FALLOW_AUDIT_NO_ANALYSIS`.
463pub(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
465/// The structured error of a resolver error, with the code and the context
466/// that the typed runners return.
467pub(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                // The typed routes refuse a type-aware layer with this code, so
487                // a caller that can run the CLI falls back on it.
488                (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
511/// The runnable of `analysis` in `run`.
512///
513/// # Errors
514///
515/// Returns `FALLOW_INTERNAL_ERROR` when the run skips the analysis: each
516/// runner resolves a run that selects the analyses that it opens.
517pub(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
531/// A session of `runnable` with the rule settings of one runner.
532///
533/// # Errors
534///
535/// Returns `FALLOW_INTERNAL_ERROR` when `adjust` changes a decided field of
536/// the run: the runners write rule settings only.
537pub(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;