Skip to main content

fallow_api/runtime/
combined.rs

1use std::{path::PathBuf, time::Instant};
2
3use fallow_config::{PlannedAnalysis, WorkspaceInfo};
4use fallow_engine::{
5    dead_code::DeadCodeAnalysisArtifacts,
6    project_analysis::{ProjectAnalysisArtifactOptions, ProjectAnalysisArtifacts},
7    session::AnalysisSession,
8};
9use fallow_output::{
10    CombinedNextStepsInput, SkipReasonName, SkippedAnalysis, SkippedAnalysisName,
11    build_combined_next_steps,
12};
13use rustc_hash::FxHashSet;
14
15use crate::{
16    AnalysisOptions, CombinedOptions, CombinedProgrammaticOutput, ComplexityOptions,
17    DeadCodeFilters, DeadCodeOptions, DuplicationOptions, ProgrammaticError,
18    analysis_context::{changed_files_for_run, resolve_programmatic_analysis_context},
19    next_steps::{
20        audit_changed_applicable, default_workspace_ref, default_workspace_ref_for_workspaces,
21        setup_pointer_applicable, suggestions_enabled,
22    },
23    run::{
24        AnalysisSlot, ProgrammaticEntry, ResolveError, ResolvedRun, RouteSettings,
25        resolve_route_run_raw,
26    },
27};
28
29use super::{
30    ProgrammaticResult, health_may_consume_dead_code_artifacts,
31    health_may_consume_duplication_report, run_health_in_run, run_health_with_session_artifacts,
32};
33use fallow_engine::project_config::ProductionModes;
34
35struct PreparedCombinedOptions {
36    dead_code: DeadCodeOptions,
37    duplication: DuplicationOptions,
38    health: ComplexityOptions,
39}
40
41struct CombinedSectionRun {
42    dead_code: Option<crate::DeadCodeProgrammaticOutput>,
43    duplication: Option<crate::DuplicationProgrammaticOutput>,
44    health: Option<crate::HealthProgrammaticOutput>,
45    root: PathBuf,
46    workspaces: Option<Vec<WorkspaceInfo>>,
47}
48
49struct DeadCodeSessionRun<'a> {
50    options: &'a CombinedOptions,
51    resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
52    run: &'a ResolvedRun,
53    prepared: &'a PreparedCombinedOptions,
54    changed_files: Option<&'a FxHashSet<PathBuf>>,
55    session: &'a AnalysisSession,
56}
57
58/// Run bare combined analysis through one programmatic analysis session.
59///
60/// # Errors
61///
62/// Returns a structured programmatic error for invalid options, config load
63/// failures, or analysis failures. When the dead-code or health section runs
64/// and the environment or `typeAware.enabled` turns on type-aware analysis
65/// that the options leave off, it returns
66/// [`super::TYPE_AWARE_CONFIG_UNSUPPORTED`].
67pub fn run_combined(options: &CombinedOptions) -> ProgrammaticResult<CombinedProgrammaticOutput> {
68    if !(options.dead_code || options.duplication || options.health) {
69        return Err(
70            ProgrammaticError::new(crate::run::COMBINED_EMPTY_MESSAGE, 2)
71                .with_code("FALLOW_COMBINED_EMPTY")
72                .with_context("combined"),
73        );
74    }
75
76    let start = Instant::now();
77    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
78    resolved.install(|| {
79        resolved.ensure_not_cancelled("combined analysis")?;
80        let resolve = || resolve_combined_run(options, &resolved);
81        // Bare `fallow` makes dead code type-aware and adds type coupling to
82        // health from config. The shared-session paths below do not pass
83        // through the checks of `run_dead_code` and `run_health`, so the
84        // check runs here.
85        let run = if options.dead_code || options.health {
86            super::type_aware_config::resolve_run_refusing_type_aware(
87                &options.analysis,
88                super::type_aware_config::TypeAwareCommand::Analysis,
89                super::type_aware_config::ConfigLocation::of(&resolved),
90                resolve,
91            )?
92        } else {
93            resolve()?
94        };
95        let options = &options_with_run_plan(options, &run);
96        let production_modes = run.production_modes();
97        let prepared = prepare_combined_options(options, production_modes);
98        let changed_files = changed_files_for_run(&resolved)?;
99        let sections = run_combined_sections(
100            &CombinedRun {
101                options,
102                resolved: &resolved,
103                run: &run,
104            },
105            &prepared,
106            changed_files.as_ref(),
107            production_modes,
108        )?;
109
110        let next_steps = combined_next_steps(
111            sections.dead_code.as_ref(),
112            sections.duplication.as_ref(),
113            sections.health.as_ref(),
114            &sections.root,
115            sections.workspaces.as_deref(),
116        );
117
118        Ok(CombinedProgrammaticOutput {
119            dead_code: sections.dead_code,
120            duplication: sections.duplication,
121            health: sections.health,
122            root: sections.root,
123            elapsed: start.elapsed(),
124            explain: options.analysis.explain,
125            next_steps,
126            telemetry_analysis_run_id: None,
127            request_outcomes: resolved.request_outcomes(),
128            skipped: skipped_analyses(&run),
129        })
130    })
131}
132
133/// The run of a combined call. When the health analysis runs alone, a config
134/// that parses but does not validate gives the error of the health analysis,
135/// as `run_health` reports it.
136fn resolve_combined_run(
137    options: &CombinedOptions,
138    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
139) -> ProgrammaticResult<ResolvedRun> {
140    resolve_route_run_raw(
141        &options.analysis,
142        &ProgrammaticEntry::Combined {
143            dead_code: options.dead_code,
144            duplication: options.duplication,
145            health: options.health,
146            production_dead_code: options.production_dead_code,
147            production_health: options.production_health,
148            production_dupes: options.production_dupes,
149        },
150        RouteSettings {
151            include_entry_exports: options.include_entry_exports,
152            audit_base: None,
153        },
154    )
155    .map_err(|err| match err {
156        ResolveError::ConfigInvalid { .. } | ResolveError::Workspace { .. }
157            if health_runs_alone(options, resolved) =>
158        {
159            super::health_config_load_error()
160        }
161        _ => crate::run::programmatic_error(&err),
162    })
163}
164
165/// Whether the plan of the call runs the health analysis and no other. The
166/// plan of the duplication analysis reads only the parsed config file.
167fn health_runs_alone(
168    options: &CombinedOptions,
169    resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
170) -> bool {
171    if options.dead_code || !options.health {
172        return false;
173    }
174    if !options.duplication {
175        return true;
176    }
177    let Ok(config) = super::load_config_file(
178        resolved.root(),
179        resolved.config_path().as_deref(),
180        resolved.allow_remote_extends(),
181    ) else {
182        return false;
183    };
184    let request = fallow_config::RunRequest::from_booleans(
185        fallow_config::RunCommand::Combined,
186        false,
187        true,
188        true,
189    );
190    !fallow_config::plan_run(config.unwrap_or_default().plan_sections(), request)
191        .duplication
192        .runs()
193}
194
195/// The options with the plan of the run: the run plans each analysis with
196/// [`fallow_config::plan_run`], as the bare `fallow` command does. A run that
197/// selects only the duplication analysis names it. A run with another
198/// analysis runs duplication by default, so `duplicates.enabled: false` turns
199/// it off.
200fn options_with_run_plan(options: &CombinedOptions, run: &ResolvedRun) -> CombinedOptions {
201    let runs = |analysis| matches!(run.analysis(analysis), AnalysisSlot::Runs(_));
202    CombinedOptions {
203        dead_code: runs(PlannedAnalysis::DeadCode),
204        duplication: runs(PlannedAnalysis::Duplication),
205        health: runs(PlannedAnalysis::Health),
206        ..options.clone()
207    }
208}
209
210/// Each analysis that the run skips, with the reason.
211fn skipped_analyses(run: &ResolvedRun) -> Vec<SkippedAnalysis> {
212    [
213        (PlannedAnalysis::DeadCode, SkippedAnalysisName::DeadCode),
214        (
215            PlannedAnalysis::Duplication,
216            SkippedAnalysisName::Duplication,
217        ),
218        (PlannedAnalysis::Health, SkippedAnalysisName::Health),
219    ]
220    .into_iter()
221    .filter_map(|(analysis, name)| match run.analysis(analysis) {
222        AnalysisSlot::Runs(_) => None,
223        AnalysisSlot::Skipped { reason } => {
224            let by_config = matches!(
225                reason.value(),
226                fallow_config::AnalysisSelection::Skipped(fallow_config::SkipReason::Config(_))
227            );
228            let config_key = match reason.source() {
229                fallow_types::sourced::Source::ConfigFile { key, .. } if by_config => {
230                    Some((*key).to_owned())
231                }
232                _ => None,
233            };
234            Some(SkippedAnalysis {
235                analysis: name,
236                reason: if by_config {
237                    SkipReasonName::OffByConfig
238                } else {
239                    SkipReasonName::NotRequested
240                },
241                config_key,
242            })
243        }
244    })
245    .collect()
246}
247
248/// The inputs that each section of a combined call reads.
249#[derive(Clone, Copy)]
250struct CombinedRun<'a> {
251    options: &'a CombinedOptions,
252    resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
253    run: &'a ResolvedRun,
254}
255
256fn prepare_combined_options(
257    options: &CombinedOptions,
258    production_modes: ProductionModes,
259) -> PreparedCombinedOptions {
260    PreparedCombinedOptions {
261        dead_code: combined_dead_code_options(options, production_modes.dead_code),
262        duplication: combined_duplication_options(options, production_modes.dupes),
263        health: combined_health_options(options, production_modes.health),
264    }
265}
266
267fn run_combined_sections(
268    call: &CombinedRun<'_>,
269    prepared: &PreparedCombinedOptions,
270    changed_files: Option<&FxHashSet<PathBuf>>,
271    production_modes: ProductionModes,
272) -> ProgrammaticResult<CombinedSectionRun> {
273    let options = call.options;
274    let share_health =
275        options.dead_code && options.health && production_modes.dead_code_matches_health();
276    let share_dupes =
277        options.dead_code && options.duplication && production_modes.dead_code_matches_dupes();
278    if share_health || share_dupes {
279        return run_combined_with_dead_code_session(
280            call,
281            prepared,
282            changed_files,
283            share_health,
284            share_dupes,
285        );
286    }
287    run_combined_sections_isolated(call, prepared)
288}
289
290fn run_combined_with_dead_code_session(
291    call: &CombinedRun<'_>,
292    prepared: &PreparedCombinedOptions,
293    changed_files: Option<&FxHashSet<PathBuf>>,
294    share_health: bool,
295    share_dupes: bool,
296) -> ProgrammaticResult<CombinedSectionRun> {
297    let CombinedRun {
298        options,
299        resolved,
300        run,
301    } = *call;
302    resolved.ensure_not_cancelled("config load and file discovery")?;
303    let session = super::dead_code::load_dead_code_session(&prepared.dead_code, resolved, run)?;
304    super::dead_code::resolve_package_map_before_analysis(resolved, &session)?;
305    if share_dupes {
306        return run_combined_with_project_artifacts(CombinedProjectArtifactRun {
307            options,
308            resolved,
309            run,
310            prepared,
311            changed_files,
312            share_health,
313            session: &session,
314        });
315    }
316    let ctx = DeadCodeSessionRun {
317        options,
318        resolved,
319        run,
320        prepared,
321        changed_files,
322        session: &session,
323    };
324    let (dead_code, dead_code_artifacts) =
325        run_dead_code_with_optional_artifacts(&ctx, options.health && share_health)?;
326    let duplication = run_combined_duplication(&ctx, share_dupes)?;
327    resolved.ensure_not_cancelled("the health section")?;
328    let health = run_combined_health(&ctx, share_health, dead_code_artifacts, None)?;
329    Ok(CombinedSectionRun {
330        dead_code,
331        duplication,
332        health,
333        root: session.root().to_path_buf(),
334        workspaces: Some(session.workspaces().to_vec()),
335    })
336}
337
338#[derive(Clone, Copy)]
339struct CombinedProjectArtifactRun<'a> {
340    options: &'a CombinedOptions,
341    resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
342    run: &'a ResolvedRun,
343    prepared: &'a PreparedCombinedOptions,
344    changed_files: Option<&'a FxHashSet<PathBuf>>,
345    share_health: bool,
346    session: &'a AnalysisSession,
347}
348
349fn run_combined_with_project_artifacts(
350    run: CombinedProjectArtifactRun<'_>,
351) -> ProgrammaticResult<CombinedSectionRun> {
352    let CombinedProjectArtifactRun {
353        options,
354        resolved,
355        run: resolved_run,
356        prepared,
357        changed_files,
358        share_health,
359        session,
360    } = run;
361    let retain_dead_code_artifacts =
362        share_health && health_may_consume_dead_code_artifacts(&prepared.health, session.config());
363    let section_start = Instant::now();
364    let project = analyze_project_artifacts_for_combined(&run, retain_dead_code_artifacts)?;
365    let dead_code = super::dead_code::run_dead_code_from_artifacts(
366        &prepared.dead_code,
367        resolved,
368        session,
369        changed_files,
370        project.dead_code,
371        section_start,
372    )?;
373    let pre_computed_duplication_for_health =
374        should_precompute_duplication_for_combined_health(options, prepared, share_health)
375            .then(|| project.duplication.clone());
376    let duplication = run_project_artifact_duplication(&run, project.duplication, section_start)?;
377    let super::dead_code::DeadCodeProgrammaticRunWithArtifacts {
378        output: dead_code,
379        artifacts,
380    } = dead_code;
381    let dead_code_artifacts = retain_dead_code_artifacts.then_some(artifacts);
382    resolved.ensure_not_cancelled("the health section")?;
383    let health = run_combined_health(
384        &DeadCodeSessionRun {
385            options,
386            resolved,
387            run: resolved_run,
388            prepared,
389            changed_files,
390            session,
391        },
392        share_health,
393        dead_code_artifacts,
394        pre_computed_duplication_for_health,
395    )?;
396
397    Ok(CombinedSectionRun {
398        dead_code: Some(dead_code),
399        duplication,
400        health,
401        root: session.root().to_path_buf(),
402        workspaces: Some(session.workspaces().to_vec()),
403    })
404}
405
406fn run_project_artifact_duplication(
407    run: &CombinedProjectArtifactRun<'_>,
408    duplication: fallow_engine::duplicates::DuplicationReport,
409    section_start: Instant,
410) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
411    let CombinedProjectArtifactRun {
412        options,
413        resolved,
414        prepared,
415        changed_files,
416        session,
417        ..
418    } = *run;
419    options
420        .duplication
421        .then(|| {
422            let change_scope =
423                resolved.change_scope(changed_files, session.config(), session.workspaces())?;
424            super::duplication::run_duplication_report_with_session(
425                &prepared.duplication,
426                resolved,
427                session,
428                duplication,
429                &change_scope,
430                section_start,
431            )
432        })
433        .transpose()
434}
435
436fn should_precompute_duplication_for_combined_health(
437    options: &CombinedOptions,
438    prepared: &PreparedCombinedOptions,
439    share_health: bool,
440) -> bool {
441    options.health
442        && share_health
443        && health_may_consume_duplication_report(&prepared.health)
444        && duplication_options_preserve_health_config(&prepared.duplication)
445}
446
447fn analyze_project_artifacts_for_combined(
448    run: &CombinedProjectArtifactRun<'_>,
449    retain_dead_code_artifacts: bool,
450) -> ProgrammaticResult<ProjectAnalysisArtifacts> {
451    let dupes_config = super::duplication::build_dupes_config(
452        &run.prepared.duplication,
453        &run.session.config().duplicates,
454    );
455    run.session
456        .analyze_project_with_artifacts(
457            &dupes_config,
458            ProjectAnalysisArtifactOptions {
459                retain_complexity_artifacts: retain_dead_code_artifacts,
460                retain_graph: retain_dead_code_artifacts,
461                changed_files: run.changed_files.cloned(),
462                collect_source_fingerprints: false,
463            },
464        )
465        .map_err(|err| {
466            super::dead_code::map_engine_error(
467                &err,
468                "combined analysis failed",
469                "FALLOW_COMBINED_FAILED",
470                "combined",
471            )
472        })
473}
474
475fn run_dead_code_with_optional_artifacts(
476    ctx: &DeadCodeSessionRun<'_>,
477    share_health: bool,
478) -> ProgrammaticResult<(
479    Option<crate::DeadCodeProgrammaticOutput>,
480    Option<DeadCodeAnalysisArtifacts>,
481)> {
482    let retain_artifacts = share_health
483        && health_may_consume_dead_code_artifacts(&ctx.prepared.health, ctx.session.config());
484    if retain_artifacts {
485        let dead_code = super::dead_code::run_dead_code_with_session_artifacts(
486            &ctx.prepared.dead_code,
487            ctx.resolved,
488            ctx.session,
489            ctx.changed_files,
490            |_| {},
491            Instant::now(),
492        )?;
493        return Ok((Some(dead_code.output), Some(dead_code.artifacts)));
494    }
495    let dead_code = super::dead_code::run_dead_code_with_session(
496        &ctx.prepared.dead_code,
497        ctx.resolved,
498        ctx.session,
499        ctx.changed_files,
500        |_| {},
501        Instant::now(),
502    )?;
503    Ok((Some(dead_code), None))
504}
505
506fn run_combined_duplication(
507    ctx: &DeadCodeSessionRun<'_>,
508    share_dupes: bool,
509) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
510    if !ctx.options.duplication {
511        return Ok(None);
512    }
513    if !share_dupes {
514        return super::duplication::run_duplication_in_context(
515            &ctx.prepared.duplication,
516            ctx.resolved,
517            ctx.run,
518        )
519        .map(Some);
520    }
521    super::duplication::run_duplication_with_session(
522        &ctx.prepared.duplication,
523        ctx.resolved,
524        ctx.session,
525        ctx.changed_files,
526        Instant::now(),
527    )
528    .map(Some)
529}
530
531fn run_combined_health(
532    ctx: &DeadCodeSessionRun<'_>,
533    share_health: bool,
534    dead_code_artifacts: Option<DeadCodeAnalysisArtifacts>,
535    pre_computed_duplication: Option<fallow_engine::duplicates::DuplicationReport>,
536) -> ProgrammaticResult<Option<crate::HealthProgrammaticOutput>> {
537    if !ctx.options.health {
538        return Ok(None);
539    }
540    if !share_health {
541        return run_health_in_run(&ctx.prepared.health, ctx.resolved, ctx.run).map(Some);
542    }
543    run_health_with_session_artifacts(
544        &ctx.prepared.health,
545        ctx.resolved,
546        ctx.session,
547        ctx.changed_files,
548        dead_code_artifacts,
549        pre_computed_duplication,
550    )
551    .map(Some)
552}
553
554fn run_combined_sections_isolated(
555    call: &CombinedRun<'_>,
556    prepared: &PreparedCombinedOptions,
557) -> ProgrammaticResult<CombinedSectionRun> {
558    let CombinedRun {
559        options,
560        resolved,
561        run,
562    } = *call;
563    Ok(CombinedSectionRun {
564        dead_code: options
565            .dead_code
566            .then(|| {
567                super::dead_code::run_dead_code_in_context(&prepared.dead_code, None, resolved, run)
568            })
569            .transpose()?,
570        duplication: options
571            .duplication
572            .then(|| {
573                super::duplication::run_duplication_in_context(&prepared.duplication, resolved, run)
574            })
575            .transpose()?,
576        health: options
577            .health
578            .then(|| run_health_in_run(&prepared.health, resolved, run))
579            .transpose()?,
580        root: resolved.root().to_path_buf(),
581        workspaces: None,
582    })
583}
584
585fn combined_dead_code_options(options: &CombinedOptions, production: bool) -> DeadCodeOptions {
586    DeadCodeOptions {
587        finding_ids: Vec::new(),
588        analysis: analysis_with_effective_production(&options.analysis, production),
589        filters: DeadCodeFilters::default(),
590        files: Vec::new(),
591        include_entry_exports: options.include_entry_exports,
592        show_cascade: options.show_cascade,
593    }
594}
595
596fn combined_duplication_options(options: &CombinedOptions, production: bool) -> DuplicationOptions {
597    let mut duplication = options.duplication_options.clone();
598    duplication.analysis = analysis_with_effective_production(&options.analysis, production);
599    duplication
600}
601
602fn duplication_options_preserve_health_config(options: &DuplicationOptions) -> bool {
603    options.mode.is_none()
604        && options.min_tokens.is_none()
605        && options.min_lines.is_none()
606        && options.min_occurrences.is_none()
607        && options.threshold.is_none()
608        && options.skip_local.is_none()
609        && options.ignore_symlinks.is_none()
610        && options.cross_language.is_none()
611        && options.ignore_imports.is_none()
612}
613
614fn combined_health_options(options: &CombinedOptions, production: bool) -> ComplexityOptions {
615    let mut health = options.health_options.clone();
616    health.analysis = analysis_with_effective_production(&options.analysis, production);
617    health.config_activates_coverage_gaps = true;
618    health
619}
620
621fn analysis_with_effective_production(
622    analysis: &AnalysisOptions,
623    production: bool,
624) -> AnalysisOptions {
625    AnalysisOptions {
626        production,
627        production_override: Some(production),
628        ..analysis.clone()
629    }
630}
631
632fn combined_next_steps(
633    dead_code: Option<&crate::DeadCodeProgrammaticOutput>,
634    duplication: Option<&crate::DuplicationProgrammaticOutput>,
635    health: Option<&crate::HealthProgrammaticOutput>,
636    root: &std::path::Path,
637    workspaces: Option<&[WorkspaceInfo]>,
638) -> Vec<fallow_types::output::NextStep> {
639    let clone_fingerprints = duplication
640        .map(|duplication| {
641            duplication
642                .output
643                .report
644                .clone_groups
645                .iter()
646                .map(|group| group.fingerprint.as_str())
647                .collect::<Vec<_>>()
648        })
649        .unwrap_or_default();
650    let audit_changed = audit_changed_applicable(root);
651    let workspace_ref = audit_changed
652        .then(|| {
653            workspaces.map_or_else(
654                || default_workspace_ref(root),
655                |workspaces| default_workspace_ref_for_workspaces(root, workspaces),
656            )
657        })
658        .flatten();
659    build_combined_next_steps(&CombinedNextStepsInput {
660        suggestions_enabled: suggestions_enabled(),
661        has_dead_code_findings: dead_code
662            .is_some_and(|dead_code| dead_code.output.results.total_issues() > 0),
663        trace_unused_export: dead_code.and_then(|dead_code| {
664            fallow_output::trace_unused_export_input(&dead_code.output.results, root)
665        }),
666        workspace_ref: workspace_ref.as_deref(),
667        clone_fingerprints: &clone_fingerprints,
668        has_complexity_findings: health.is_some_and(|health| !health.report.findings.is_empty()),
669        offer_setup: setup_pointer_applicable(root),
670        impact_digest: None,
671        audit_changed,
672        has_external_plugins: !fallow_config::discover_external_plugins(root, &[]).is_empty(),
673        has_unused_files: dead_code
674            .is_some_and(|dead_code| !dead_code.output.results.unused_files.is_empty()),
675        // The programmatic runtime has no process-wide record of a loaded
676        // baseline to read, and its caller passes the paths itself, so there is
677        // nothing to point a re-check at here.
678        baseline_recheck: None,
679    })
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use crate::DuplicationMode;
686
687    #[test]
688    fn health_reuses_combined_duplication_only_without_detector_overrides() {
689        assert!(duplication_options_preserve_health_config(
690            &DuplicationOptions::default()
691        ));
692        assert!(!duplication_options_preserve_health_config(
693            &DuplicationOptions {
694                min_tokens: Some(1),
695                ..DuplicationOptions::default()
696            }
697        ));
698        assert!(!duplication_options_preserve_health_config(
699            &DuplicationOptions {
700                mode: Some(DuplicationMode::Semantic),
701                ..DuplicationOptions::default()
702            }
703        ));
704    }
705}