use std::{path::PathBuf, time::Instant};
use fallow_config::{PlannedAnalysis, WorkspaceInfo};
use fallow_engine::{
dead_code::DeadCodeAnalysisArtifacts,
project_analysis::{ProjectAnalysisArtifactOptions, ProjectAnalysisArtifacts},
session::AnalysisSession,
};
use fallow_output::{
CombinedNextStepsInput, SkipReasonName, SkippedAnalysis, SkippedAnalysisName,
build_combined_next_steps,
};
use rustc_hash::FxHashSet;
use crate::{
AnalysisOptions, CombinedOptions, CombinedProgrammaticOutput, ComplexityOptions,
DeadCodeFilters, DeadCodeOptions, DuplicationOptions, ProgrammaticError,
analysis_context::{changed_files_for_run, resolve_programmatic_analysis_context},
next_steps::{
audit_changed_applicable, default_workspace_ref, default_workspace_ref_for_workspaces,
setup_pointer_applicable, suggestions_enabled,
},
run::{
AnalysisSlot, ProgrammaticEntry, ResolveError, ResolvedRun, RouteSettings,
resolve_route_run_raw,
},
};
use super::{
ProgrammaticResult, health_may_consume_dead_code_artifacts,
health_may_consume_duplication_report, run_health_in_run, run_health_with_session_artifacts,
};
use fallow_engine::project_config::ProductionModes;
struct PreparedCombinedOptions {
dead_code: DeadCodeOptions,
duplication: DuplicationOptions,
health: ComplexityOptions,
}
struct CombinedSectionRun {
dead_code: Option<crate::DeadCodeProgrammaticOutput>,
duplication: Option<crate::DuplicationProgrammaticOutput>,
health: Option<crate::HealthProgrammaticOutput>,
root: PathBuf,
workspaces: Option<Vec<WorkspaceInfo>>,
}
struct DeadCodeSessionRun<'a> {
options: &'a CombinedOptions,
resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
run: &'a ResolvedRun,
prepared: &'a PreparedCombinedOptions,
changed_files: Option<&'a FxHashSet<PathBuf>>,
session: &'a AnalysisSession,
}
pub fn run_combined(options: &CombinedOptions) -> ProgrammaticResult<CombinedProgrammaticOutput> {
if !(options.dead_code || options.duplication || options.health) {
return Err(
ProgrammaticError::new(crate::run::COMBINED_EMPTY_MESSAGE, 2)
.with_code("FALLOW_COMBINED_EMPTY")
.with_context("combined"),
);
}
let start = Instant::now();
let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
resolved.install(|| {
resolved.ensure_not_cancelled("combined analysis")?;
let resolve = || resolve_combined_run(options, &resolved);
let run = if options.dead_code || options.health {
super::type_aware_config::resolve_run_refusing_type_aware(
&options.analysis,
super::type_aware_config::TypeAwareCommand::Analysis,
super::type_aware_config::ConfigLocation::of(&resolved),
resolve,
)?
} else {
resolve()?
};
let options = &options_with_run_plan(options, &run);
let production_modes = run.production_modes();
let prepared = prepare_combined_options(options, production_modes);
let changed_files = changed_files_for_run(&resolved)?;
let sections = run_combined_sections(
&CombinedRun {
options,
resolved: &resolved,
run: &run,
},
&prepared,
changed_files.as_ref(),
production_modes,
)?;
let next_steps = combined_next_steps(
sections.dead_code.as_ref(),
sections.duplication.as_ref(),
sections.health.as_ref(),
§ions.root,
sections.workspaces.as_deref(),
);
Ok(CombinedProgrammaticOutput {
dead_code: sections.dead_code,
duplication: sections.duplication,
health: sections.health,
root: sections.root,
elapsed: start.elapsed(),
explain: options.analysis.explain,
next_steps,
telemetry_analysis_run_id: None,
request_outcomes: resolved.request_outcomes(),
skipped: skipped_analyses(&run),
})
})
}
fn resolve_combined_run(
options: &CombinedOptions,
resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
) -> ProgrammaticResult<ResolvedRun> {
resolve_route_run_raw(
&options.analysis,
&ProgrammaticEntry::Combined {
dead_code: options.dead_code,
duplication: options.duplication,
health: options.health,
production_dead_code: options.production_dead_code,
production_health: options.production_health,
production_dupes: options.production_dupes,
},
RouteSettings {
include_entry_exports: options.include_entry_exports,
audit_base: None,
},
)
.map_err(|err| match err {
ResolveError::ConfigInvalid { .. } | ResolveError::Workspace { .. }
if health_runs_alone(options, resolved) =>
{
super::health_config_load_error()
}
_ => crate::run::programmatic_error(&err),
})
}
fn health_runs_alone(
options: &CombinedOptions,
resolved: &crate::analysis_context::ProgrammaticAnalysisContext,
) -> bool {
if options.dead_code || !options.health {
return false;
}
if !options.duplication {
return true;
}
let Ok(config) = super::load_config_file(
resolved.root(),
resolved.config_path().as_deref(),
resolved.allow_remote_extends(),
) else {
return false;
};
let request = fallow_config::RunRequest::from_booleans(
fallow_config::RunCommand::Combined,
false,
true,
true,
);
!fallow_config::plan_run(config.unwrap_or_default().plan_sections(), request)
.duplication
.runs()
}
fn options_with_run_plan(options: &CombinedOptions, run: &ResolvedRun) -> CombinedOptions {
let runs = |analysis| matches!(run.analysis(analysis), AnalysisSlot::Runs(_));
CombinedOptions {
dead_code: runs(PlannedAnalysis::DeadCode),
duplication: runs(PlannedAnalysis::Duplication),
health: runs(PlannedAnalysis::Health),
..options.clone()
}
}
fn skipped_analyses(run: &ResolvedRun) -> Vec<SkippedAnalysis> {
[
(PlannedAnalysis::DeadCode, SkippedAnalysisName::DeadCode),
(
PlannedAnalysis::Duplication,
SkippedAnalysisName::Duplication,
),
(PlannedAnalysis::Health, SkippedAnalysisName::Health),
]
.into_iter()
.filter_map(|(analysis, name)| match run.analysis(analysis) {
AnalysisSlot::Runs(_) => None,
AnalysisSlot::Skipped { reason } => {
let by_config = matches!(
reason.value(),
fallow_config::AnalysisSelection::Skipped(fallow_config::SkipReason::Config(_))
);
let config_key = match reason.source() {
fallow_types::sourced::Source::ConfigFile { key, .. } if by_config => {
Some((*key).to_owned())
}
_ => None,
};
Some(SkippedAnalysis {
analysis: name,
reason: if by_config {
SkipReasonName::OffByConfig
} else {
SkipReasonName::NotRequested
},
config_key,
})
}
})
.collect()
}
#[derive(Clone, Copy)]
struct CombinedRun<'a> {
options: &'a CombinedOptions,
resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
run: &'a ResolvedRun,
}
fn prepare_combined_options(
options: &CombinedOptions,
production_modes: ProductionModes,
) -> PreparedCombinedOptions {
PreparedCombinedOptions {
dead_code: combined_dead_code_options(options, production_modes.dead_code),
duplication: combined_duplication_options(options, production_modes.dupes),
health: combined_health_options(options, production_modes.health),
}
}
fn run_combined_sections(
call: &CombinedRun<'_>,
prepared: &PreparedCombinedOptions,
changed_files: Option<&FxHashSet<PathBuf>>,
production_modes: ProductionModes,
) -> ProgrammaticResult<CombinedSectionRun> {
let options = call.options;
let share_health =
options.dead_code && options.health && production_modes.dead_code_matches_health();
let share_dupes =
options.dead_code && options.duplication && production_modes.dead_code_matches_dupes();
if share_health || share_dupes {
return run_combined_with_dead_code_session(
call,
prepared,
changed_files,
share_health,
share_dupes,
);
}
run_combined_sections_isolated(call, prepared)
}
fn run_combined_with_dead_code_session(
call: &CombinedRun<'_>,
prepared: &PreparedCombinedOptions,
changed_files: Option<&FxHashSet<PathBuf>>,
share_health: bool,
share_dupes: bool,
) -> ProgrammaticResult<CombinedSectionRun> {
let CombinedRun {
options,
resolved,
run,
} = *call;
resolved.ensure_not_cancelled("config load and file discovery")?;
let session = super::dead_code::load_dead_code_session(&prepared.dead_code, resolved, run)?;
super::dead_code::resolve_package_map_before_analysis(resolved, &session)?;
if share_dupes {
return run_combined_with_project_artifacts(CombinedProjectArtifactRun {
options,
resolved,
run,
prepared,
changed_files,
share_health,
session: &session,
});
}
let ctx = DeadCodeSessionRun {
options,
resolved,
run,
prepared,
changed_files,
session: &session,
};
let (dead_code, dead_code_artifacts) =
run_dead_code_with_optional_artifacts(&ctx, options.health && share_health)?;
let duplication = run_combined_duplication(&ctx, share_dupes)?;
resolved.ensure_not_cancelled("the health section")?;
let health = run_combined_health(&ctx, share_health, dead_code_artifacts, None)?;
Ok(CombinedSectionRun {
dead_code,
duplication,
health,
root: session.root().to_path_buf(),
workspaces: Some(session.workspaces().to_vec()),
})
}
#[derive(Clone, Copy)]
struct CombinedProjectArtifactRun<'a> {
options: &'a CombinedOptions,
resolved: &'a crate::analysis_context::ProgrammaticAnalysisContext,
run: &'a ResolvedRun,
prepared: &'a PreparedCombinedOptions,
changed_files: Option<&'a FxHashSet<PathBuf>>,
share_health: bool,
session: &'a AnalysisSession,
}
fn run_combined_with_project_artifacts(
run: CombinedProjectArtifactRun<'_>,
) -> ProgrammaticResult<CombinedSectionRun> {
let CombinedProjectArtifactRun {
options,
resolved,
run: resolved_run,
prepared,
changed_files,
share_health,
session,
} = run;
let retain_dead_code_artifacts =
share_health && health_may_consume_dead_code_artifacts(&prepared.health, session.config());
let section_start = Instant::now();
let project = analyze_project_artifacts_for_combined(&run, retain_dead_code_artifacts)?;
let dead_code = super::dead_code::run_dead_code_from_artifacts(
&prepared.dead_code,
resolved,
session,
changed_files,
project.dead_code,
section_start,
)?;
let pre_computed_duplication_for_health =
should_precompute_duplication_for_combined_health(options, prepared, share_health)
.then(|| project.duplication.clone());
let duplication = run_project_artifact_duplication(&run, project.duplication, section_start)?;
let super::dead_code::DeadCodeProgrammaticRunWithArtifacts {
output: dead_code,
artifacts,
} = dead_code;
let dead_code_artifacts = retain_dead_code_artifacts.then_some(artifacts);
resolved.ensure_not_cancelled("the health section")?;
let health = run_combined_health(
&DeadCodeSessionRun {
options,
resolved,
run: resolved_run,
prepared,
changed_files,
session,
},
share_health,
dead_code_artifacts,
pre_computed_duplication_for_health,
)?;
Ok(CombinedSectionRun {
dead_code: Some(dead_code),
duplication,
health,
root: session.root().to_path_buf(),
workspaces: Some(session.workspaces().to_vec()),
})
}
fn run_project_artifact_duplication(
run: &CombinedProjectArtifactRun<'_>,
duplication: fallow_engine::duplicates::DuplicationReport,
section_start: Instant,
) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
let CombinedProjectArtifactRun {
options,
resolved,
prepared,
changed_files,
session,
..
} = *run;
options
.duplication
.then(|| {
let change_scope =
resolved.change_scope(changed_files, session.config(), session.workspaces())?;
super::duplication::run_duplication_report_with_session(
&prepared.duplication,
resolved,
session,
duplication,
&change_scope,
section_start,
)
})
.transpose()
}
fn should_precompute_duplication_for_combined_health(
options: &CombinedOptions,
prepared: &PreparedCombinedOptions,
share_health: bool,
) -> bool {
options.health
&& share_health
&& health_may_consume_duplication_report(&prepared.health)
&& duplication_options_preserve_health_config(&prepared.duplication)
}
fn analyze_project_artifacts_for_combined(
run: &CombinedProjectArtifactRun<'_>,
retain_dead_code_artifacts: bool,
) -> ProgrammaticResult<ProjectAnalysisArtifacts> {
let dupes_config = super::duplication::build_dupes_config(
&run.prepared.duplication,
&run.session.config().duplicates,
);
run.session
.analyze_project_with_artifacts(
&dupes_config,
ProjectAnalysisArtifactOptions {
retain_complexity_artifacts: retain_dead_code_artifacts,
retain_graph: retain_dead_code_artifacts,
changed_files: run.changed_files.cloned(),
collect_source_fingerprints: false,
},
)
.map_err(|err| {
super::dead_code::map_engine_error(
&err,
"combined analysis failed",
"FALLOW_COMBINED_FAILED",
"combined",
)
})
}
fn run_dead_code_with_optional_artifacts(
ctx: &DeadCodeSessionRun<'_>,
share_health: bool,
) -> ProgrammaticResult<(
Option<crate::DeadCodeProgrammaticOutput>,
Option<DeadCodeAnalysisArtifacts>,
)> {
let retain_artifacts = share_health
&& health_may_consume_dead_code_artifacts(&ctx.prepared.health, ctx.session.config());
if retain_artifacts {
let dead_code = super::dead_code::run_dead_code_with_session_artifacts(
&ctx.prepared.dead_code,
ctx.resolved,
ctx.session,
ctx.changed_files,
|_| {},
Instant::now(),
)?;
return Ok((Some(dead_code.output), Some(dead_code.artifacts)));
}
let dead_code = super::dead_code::run_dead_code_with_session(
&ctx.prepared.dead_code,
ctx.resolved,
ctx.session,
ctx.changed_files,
|_| {},
Instant::now(),
)?;
Ok((Some(dead_code), None))
}
fn run_combined_duplication(
ctx: &DeadCodeSessionRun<'_>,
share_dupes: bool,
) -> ProgrammaticResult<Option<crate::DuplicationProgrammaticOutput>> {
if !ctx.options.duplication {
return Ok(None);
}
if !share_dupes {
return super::duplication::run_duplication_in_context(
&ctx.prepared.duplication,
ctx.resolved,
ctx.run,
)
.map(Some);
}
super::duplication::run_duplication_with_session(
&ctx.prepared.duplication,
ctx.resolved,
ctx.session,
ctx.changed_files,
Instant::now(),
)
.map(Some)
}
fn run_combined_health(
ctx: &DeadCodeSessionRun<'_>,
share_health: bool,
dead_code_artifacts: Option<DeadCodeAnalysisArtifacts>,
pre_computed_duplication: Option<fallow_engine::duplicates::DuplicationReport>,
) -> ProgrammaticResult<Option<crate::HealthProgrammaticOutput>> {
if !ctx.options.health {
return Ok(None);
}
if !share_health {
return run_health_in_run(&ctx.prepared.health, ctx.resolved, ctx.run).map(Some);
}
run_health_with_session_artifacts(
&ctx.prepared.health,
ctx.resolved,
ctx.session,
ctx.changed_files,
dead_code_artifacts,
pre_computed_duplication,
)
.map(Some)
}
fn run_combined_sections_isolated(
call: &CombinedRun<'_>,
prepared: &PreparedCombinedOptions,
) -> ProgrammaticResult<CombinedSectionRun> {
let CombinedRun {
options,
resolved,
run,
} = *call;
Ok(CombinedSectionRun {
dead_code: options
.dead_code
.then(|| {
super::dead_code::run_dead_code_in_context(&prepared.dead_code, None, resolved, run)
})
.transpose()?,
duplication: options
.duplication
.then(|| {
super::duplication::run_duplication_in_context(&prepared.duplication, resolved, run)
})
.transpose()?,
health: options
.health
.then(|| run_health_in_run(&prepared.health, resolved, run))
.transpose()?,
root: resolved.root().to_path_buf(),
workspaces: None,
})
}
fn combined_dead_code_options(options: &CombinedOptions, production: bool) -> DeadCodeOptions {
DeadCodeOptions {
finding_ids: Vec::new(),
analysis: analysis_with_effective_production(&options.analysis, production),
filters: DeadCodeFilters::default(),
files: Vec::new(),
include_entry_exports: options.include_entry_exports,
show_cascade: options.show_cascade,
}
}
fn combined_duplication_options(options: &CombinedOptions, production: bool) -> DuplicationOptions {
let mut duplication = options.duplication_options.clone();
duplication.analysis = analysis_with_effective_production(&options.analysis, production);
duplication
}
fn duplication_options_preserve_health_config(options: &DuplicationOptions) -> bool {
options.mode.is_none()
&& options.min_tokens.is_none()
&& options.min_lines.is_none()
&& options.min_occurrences.is_none()
&& options.threshold.is_none()
&& options.skip_local.is_none()
&& options.ignore_symlinks.is_none()
&& options.cross_language.is_none()
&& options.ignore_imports.is_none()
}
fn combined_health_options(options: &CombinedOptions, production: bool) -> ComplexityOptions {
let mut health = options.health_options.clone();
health.analysis = analysis_with_effective_production(&options.analysis, production);
health.config_activates_coverage_gaps = true;
health
}
fn analysis_with_effective_production(
analysis: &AnalysisOptions,
production: bool,
) -> AnalysisOptions {
AnalysisOptions {
production,
production_override: Some(production),
..analysis.clone()
}
}
fn combined_next_steps(
dead_code: Option<&crate::DeadCodeProgrammaticOutput>,
duplication: Option<&crate::DuplicationProgrammaticOutput>,
health: Option<&crate::HealthProgrammaticOutput>,
root: &std::path::Path,
workspaces: Option<&[WorkspaceInfo]>,
) -> Vec<fallow_types::output::NextStep> {
let clone_fingerprints = duplication
.map(|duplication| {
duplication
.output
.report
.clone_groups
.iter()
.map(|group| group.fingerprint.as_str())
.collect::<Vec<_>>()
})
.unwrap_or_default();
let audit_changed = audit_changed_applicable(root);
let workspace_ref = audit_changed
.then(|| {
workspaces.map_or_else(
|| default_workspace_ref(root),
|workspaces| default_workspace_ref_for_workspaces(root, workspaces),
)
})
.flatten();
build_combined_next_steps(&CombinedNextStepsInput {
suggestions_enabled: suggestions_enabled(),
has_dead_code_findings: dead_code
.is_some_and(|dead_code| dead_code.output.results.total_issues() > 0),
trace_unused_export: dead_code.and_then(|dead_code| {
fallow_output::trace_unused_export_input(&dead_code.output.results, root)
}),
workspace_ref: workspace_ref.as_deref(),
clone_fingerprints: &clone_fingerprints,
has_complexity_findings: health.is_some_and(|health| !health.report.findings.is_empty()),
offer_setup: setup_pointer_applicable(root),
impact_digest: None,
audit_changed,
has_external_plugins: !fallow_config::discover_external_plugins(root, &[]).is_empty(),
has_unused_files: dead_code
.is_some_and(|dead_code| !dead_code.output.results.unused_files.is_empty()),
baseline_recheck: None,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DuplicationMode;
#[test]
fn health_reuses_combined_duplication_only_without_detector_overrides() {
assert!(duplication_options_preserve_health_config(
&DuplicationOptions::default()
));
assert!(!duplication_options_preserve_health_config(
&DuplicationOptions {
min_tokens: Some(1),
..DuplicationOptions::default()
}
));
assert!(!duplication_options_preserve_health_config(
&DuplicationOptions {
mode: Some(DuplicationMode::Semantic),
..DuplicationOptions::default()
}
));
}
}