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(
377        &run,
378        super::duplication::DuplicationRunReport {
379            report: project.duplication,
380            ignored_clone_groups: project.ignored_clone_groups,
381        },
382        section_start,
383    )?;
384    let super::dead_code::DeadCodeProgrammaticRunWithArtifacts {
385        output: dead_code,
386        artifacts,
387    } = dead_code;
388    let dead_code_artifacts = retain_dead_code_artifacts.then_some(artifacts);
389    resolved.ensure_not_cancelled("the health section")?;
390    let health = run_combined_health(
391        &DeadCodeSessionRun {
392            options,
393            resolved,
394            run: resolved_run,
395            prepared,
396            changed_files,
397            session,
398        },
399        share_health,
400        dead_code_artifacts,
401        pre_computed_duplication_for_health,
402    )?;
403
404    Ok(CombinedSectionRun {
405        dead_code: Some(dead_code),
406        duplication,
407        health,
408        root: session.root().to_path_buf(),
409        workspaces: Some(session.workspaces().to_vec()),
410    })
411}
412
413fn run_project_artifact_duplication(
414    run: &CombinedProjectArtifactRun<'_>,
415    duplication: super::duplication::DuplicationRunReport,
416    section_start: Instant,
417) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
418    let CombinedProjectArtifactRun {
419        options,
420        resolved,
421        prepared,
422        changed_files,
423        session,
424        ..
425    } = *run;
426    options
427        .duplication
428        .then(|| {
429            let change_scope =
430                resolved.change_scope(changed_files, session.config(), session.workspaces())?;
431            super::duplication::run_duplication_report_with_session(
432                &prepared.duplication,
433                resolved,
434                session,
435                duplication,
436                &change_scope,
437                section_start,
438            )
439        })
440        .transpose()
441}
442
443fn should_precompute_duplication_for_combined_health(
444    options: &CombinedOptions,
445    prepared: &PreparedCombinedOptions,
446    share_health: bool,
447) -> bool {
448    options.health
449        && share_health
450        && health_may_consume_duplication_report(&prepared.health)
451        && duplication_options_preserve_health_config(&prepared.duplication)
452}
453
454fn analyze_project_artifacts_for_combined(
455    run: &CombinedProjectArtifactRun<'_>,
456    retain_dead_code_artifacts: bool,
457) -> ProgrammaticResult<ProjectAnalysisArtifacts> {
458    let dupes_config = super::duplication::build_dupes_config(
459        &run.prepared.duplication,
460        &run.session.config().duplicates,
461    );
462    run.session
463        .analyze_project_with_artifacts(
464            &dupes_config,
465            ProjectAnalysisArtifactOptions {
466                retain_complexity_artifacts: retain_dead_code_artifacts,
467                retain_graph: retain_dead_code_artifacts,
468                changed_files: run.changed_files.cloned(),
469                collect_source_fingerprints: false,
470            },
471        )
472        .map_err(|err| {
473            super::dead_code::map_engine_error(
474                &err,
475                "combined analysis failed",
476                "FALLOW_COMBINED_FAILED",
477                "combined",
478            )
479        })
480}
481
482fn run_dead_code_with_optional_artifacts(
483    ctx: &DeadCodeSessionRun<'_>,
484    share_health: bool,
485) -> ProgrammaticResult<(
486    Option<crate::DeadCodeProgrammaticOutput>,
487    Option<DeadCodeAnalysisArtifacts>,
488)> {
489    let retain_artifacts = share_health
490        && health_may_consume_dead_code_artifacts(&ctx.prepared.health, ctx.session.config());
491    if retain_artifacts {
492        let dead_code = super::dead_code::run_dead_code_with_session_artifacts(
493            &ctx.prepared.dead_code,
494            ctx.resolved,
495            ctx.session,
496            ctx.changed_files,
497            |_| {},
498            Instant::now(),
499        )?;
500        return Ok((Some(dead_code.output), Some(dead_code.artifacts)));
501    }
502    let dead_code = super::dead_code::run_dead_code_with_session(
503        &ctx.prepared.dead_code,
504        ctx.resolved,
505        ctx.session,
506        ctx.changed_files,
507        |_| {},
508        Instant::now(),
509    )?;
510    Ok((Some(dead_code), None))
511}
512
513fn run_combined_duplication(
514    ctx: &DeadCodeSessionRun<'_>,
515    share_dupes: bool,
516) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
517    if !ctx.options.duplication {
518        return Ok(None);
519    }
520    if !share_dupes {
521        return super::duplication::run_duplication_in_context(
522            &ctx.prepared.duplication,
523            ctx.resolved,
524            ctx.run,
525        )
526        .map(Some);
527    }
528    super::duplication::run_duplication_with_session(
529        &ctx.prepared.duplication,
530        ctx.resolved,
531        ctx.session,
532        ctx.changed_files,
533        Instant::now(),
534    )
535    .map(Some)
536}
537
538fn run_combined_health(
539    ctx: &DeadCodeSessionRun<'_>,
540    share_health: bool,
541    dead_code_artifacts: Option<DeadCodeAnalysisArtifacts>,
542    pre_computed_duplication: Option<fallow_engine::duplicates::DuplicationReport>,
543) -> ProgrammaticResult<Option<crate::HealthProgrammaticOutput>> {
544    if !ctx.options.health {
545        return Ok(None);
546    }
547    if !share_health {
548        return run_health_in_run(&ctx.prepared.health, ctx.resolved, ctx.run).map(Some);
549    }
550    run_health_with_session_artifacts(
551        &ctx.prepared.health,
552        ctx.resolved,
553        ctx.session,
554        ctx.changed_files,
555        dead_code_artifacts,
556        pre_computed_duplication,
557    )
558    .map(Some)
559}
560
561fn run_combined_sections_isolated(
562    call: &CombinedRun<'_>,
563    prepared: &PreparedCombinedOptions,
564) -> ProgrammaticResult<CombinedSectionRun> {
565    let CombinedRun {
566        options,
567        resolved,
568        run,
569    } = *call;
570    Ok(CombinedSectionRun {
571        dead_code: options
572            .dead_code
573            .then(|| {
574                super::dead_code::run_dead_code_in_context(&prepared.dead_code, None, resolved, run)
575            })
576            .transpose()?,
577        duplication: options
578            .duplication
579            .then(|| {
580                super::duplication::run_duplication_in_context(&prepared.duplication, resolved, run)
581            })
582            .transpose()?,
583        health: options
584            .health
585            .then(|| run_health_in_run(&prepared.health, resolved, run))
586            .transpose()?,
587        root: resolved.root().to_path_buf(),
588        workspaces: None,
589    })
590}
591
592fn combined_dead_code_options(options: &CombinedOptions, production: bool) -> DeadCodeOptions {
593    DeadCodeOptions {
594        finding_ids: Vec::new(),
595        analysis: analysis_with_effective_production(&options.analysis, production),
596        filters: DeadCodeFilters::default(),
597        files: Vec::new(),
598        include_entry_exports: options.include_entry_exports,
599        show_cascade: options.show_cascade,
600    }
601}
602
603fn combined_duplication_options(options: &CombinedOptions, production: bool) -> DuplicationOptions {
604    let mut duplication = options.duplication_options.clone();
605    duplication.analysis = analysis_with_effective_production(&options.analysis, production);
606    duplication
607}
608
609fn duplication_options_preserve_health_config(options: &DuplicationOptions) -> bool {
610    options.mode.is_none()
611        && options.min_tokens.is_none()
612        && options.min_lines.is_none()
613        && options.min_occurrences.is_none()
614        && options.threshold.is_none()
615        && options.skip_local.is_none()
616        && options.ignore_symlinks.is_none()
617        && options.cross_language.is_none()
618        && options.ignore_imports.is_none()
619}
620
621fn combined_health_options(options: &CombinedOptions, production: bool) -> ComplexityOptions {
622    let mut health = options.health_options.clone();
623    health.analysis = analysis_with_effective_production(&options.analysis, production);
624    health.config_activates_coverage_gaps = true;
625    health
626}
627
628fn analysis_with_effective_production(
629    analysis: &AnalysisOptions,
630    production: bool,
631) -> AnalysisOptions {
632    AnalysisOptions {
633        production,
634        production_override: Some(production),
635        ..analysis.clone()
636    }
637}
638
639fn combined_next_steps(
640    dead_code: Option<&crate::DeadCodeProgrammaticOutput>,
641    duplication: Option<&crate::DuplicationProgrammaticOutput>,
642    health: Option<&crate::HealthProgrammaticOutput>,
643    root: &std::path::Path,
644    workspaces: Option<&[WorkspaceInfo]>,
645) -> Vec<fallow_types::output::NextStep> {
646    let clone_fingerprints = duplication
647        .map(|duplication| {
648            duplication
649                .output
650                .report
651                .clone_groups
652                .iter()
653                .map(|group| group.fingerprint.as_str())
654                .collect::<Vec<_>>()
655        })
656        .unwrap_or_default();
657    let audit_changed = audit_changed_applicable(root);
658    let workspace_ref = audit_changed
659        .then(|| {
660            workspaces.map_or_else(
661                || default_workspace_ref(root),
662                |workspaces| default_workspace_ref_for_workspaces(root, workspaces),
663            )
664        })
665        .flatten();
666    build_combined_next_steps(&CombinedNextStepsInput {
667        suggestions_enabled: suggestions_enabled(),
668        has_dead_code_findings: dead_code
669            .is_some_and(|dead_code| dead_code.output.results.total_issues() > 0),
670        trace_unused_export: dead_code.and_then(|dead_code| {
671            fallow_output::trace_unused_export_input(&dead_code.output.results, root)
672        }),
673        workspace_ref: workspace_ref.as_deref(),
674        clone_fingerprints: &clone_fingerprints,
675        has_complexity_findings: health.is_some_and(|health| !health.report.findings.is_empty()),
676        offer_setup: setup_pointer_applicable(root),
677        impact_digest: None,
678        audit_changed,
679        has_external_plugins: !fallow_config::discover_external_plugins(root, &[]).is_empty(),
680        has_unused_files: dead_code
681            .is_some_and(|dead_code| !dead_code.output.results.unused_files.is_empty()),
682        // The programmatic runtime has no process-wide record of a loaded
683        // baseline to read, and its caller passes the paths itself, so there is
684        // nothing to point a re-check at here.
685        baseline_recheck: None,
686    })
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692    use crate::DuplicationMode;
693
694    #[test]
695    fn health_reuses_combined_duplication_only_without_detector_overrides() {
696        assert!(duplication_options_preserve_health_config(
697            &DuplicationOptions::default()
698        ));
699        assert!(!duplication_options_preserve_health_config(
700            &DuplicationOptions {
701                min_tokens: Some(1),
702                ..DuplicationOptions::default()
703            }
704        ));
705        assert!(!duplication_options_preserve_health_config(
706            &DuplicationOptions {
707                mode: Some(DuplicationMode::Semantic),
708                ..DuplicationOptions::default()
709            }
710        ));
711    }
712}