1use std::path::{Path, PathBuf};
4
5use fallow_config::{FallowConfig, HealthConfig, PlannedAnalysis};
6use fallow_engine::{
7 dead_code::DeadCodeAnalysisArtifacts,
8 duplicates::DuplicationReport,
9 project_config::{self, ConfigFileOptions, ConfigLoadError},
10 session::AnalysisSession,
11};
12use fallow_output::{HealthGrouping, HealthReport};
13use fallow_types::output_format::OutputFormat;
14use fallow_types::workspace::WorkspaceDiagnostic;
15use rustc_hash::FxHashSet;
16
17mod audit;
18mod audit_base_ref;
19mod combined;
20mod dead_code;
21mod decision_surface;
22mod duplication;
23mod feature_flags;
24mod mutation;
25mod mutation_record;
26mod mutation_replay;
27mod mutation_runner_options;
28mod mutation_witness;
29mod similar_code;
30mod trace;
31mod type_aware_config;
32
33pub use crate::runtime_output::{
34 ArchitectureOutput, ArchitectureProgrammaticOutput, AuditProgrammaticKeySnapshot,
35 AuditProgrammaticOutput, BoundaryViolationsOutput, BoundaryViolationsProgrammaticOutput,
36 CircularDependenciesOutput, CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput,
37 DeadCodeOutput, DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput,
38 DuplicationOutput, DuplicationProgrammaticOutput, FeatureFlagsOutput,
39 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
40 TraceClassMemberOutput, TraceCloneOutput, TraceCloneProgrammaticOutput, TraceDependencyOutput,
41 TraceDependencyProgrammaticOutput, TraceErrorOutput, TraceErrorProgrammaticOutput,
42 TraceExportOutput, TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
43 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
44 serialize_health_report_json,
45};
46pub use audit::{AUDIT_CONFIG_BASELINE_UNSUPPORTED, run_audit};
47#[cfg(any(test, feature = "testing"))]
48pub(crate) use audit::{analysis_options_for_audit, resolve_audit_run};
49pub use combined::run_combined;
50pub use dead_code::{
51 run_architecture, run_boundary_violations, run_circular_dependencies, run_dead_code,
52 run_dead_code_with_baseline,
53};
54pub use decision_surface::run_decision_surface;
55pub use duplication::run_duplication;
56pub use feature_flags::run_feature_flags;
57pub use mutation::{plan_mutation, run_mutation, run_mutation_with_progress};
58pub use mutation_replay::replay_mutation;
59pub use similar_code::{
60 inspect_similar_code, parse_similar_code_candidate_snapshot, review_similar_code,
61 run_similar_code, select_similar_code_candidate_snapshot,
62};
63pub use trace::{
64 TraceCloneBenchmarkResult, benchmark_trace_clone_compact_json,
65 benchmark_trace_graph_family_compact_json, run_trace_clone, run_trace_dependency,
66 run_trace_error, run_trace_export, run_trace_file, run_trace_import_path,
67};
68pub use type_aware_config::TYPE_AWARE_CONFIG_UNSUPPORTED;
69
70use crate::{
71 ComplexityOptions, ProgrammaticError,
72 analysis_context::{
73 ProgrammaticAnalysisContext, resolve_programmatic_analysis_context,
74 workspace_roots_for_session,
75 },
76 derive_complexity_options,
77 next_steps::{audit_changed_applicable, setup_pointer_applicable, suggestions_enabled},
78 run::{ProgrammaticEntry, ResolvedRun, resolve_programmatic_run},
79};
80
81type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
82
83pub fn load_health_config(
95 options: &crate::AnalysisOptions,
96) -> ProgrammaticResult<Option<HealthConfig>> {
97 let root = crate::analysis_context::resolve_analysis_root(options.root.as_deref())?;
98 crate::analysis_context::validate_analysis_config_path(options.config_path.as_deref())?;
99 let loaded = load_config_file(
100 &root,
101 options.config_path.as_deref(),
102 options.allow_remote_extends,
103 )?;
104 Ok(loaded.map(|config| config.health))
105}
106
107fn load_config_file(
110 root: &Path,
111 config_path: Option<&Path>,
112 allow_remote_extends: bool,
113) -> ProgrammaticResult<Option<FallowConfig>> {
114 let file = project_config::load_config_file(
115 root,
116 config_path,
117 ConfigFileOptions::new(allow_remote_extends, &fallow_config::EnvSnapshot::capture()),
118 )
119 .map_err(|err| config_load_error(&err))?;
120 Ok(file.path.map(|_| file.config))
121}
122
123fn config_load_error(err: &ConfigLoadError) -> ProgrammaticError {
124 ProgrammaticError::new(format!("failed to load config: {}", err.chain()), 2)
125 .with_code("FALLOW_CONFIG_LOAD_FAILED")
126 .with_context("analysis.configPath")
127}
128
129pub(super) fn health_may_consume_dead_code_artifacts(
130 options: &ComplexityOptions,
131 config: &fallow_config::ResolvedConfig,
132) -> bool {
133 let sections = derive_complexity_options(options);
134 let max_crap = options.max_crap.unwrap_or(config.health.max_crap);
135 sections.file_scores
136 || sections.coverage_gaps
137 || sections.hotspots
138 || sections.targets
139 || sections.force_full
140 || max_crap > 0.0
141}
142
143pub(super) fn health_may_consume_duplication_report(options: &ComplexityOptions) -> bool {
144 let sections = derive_complexity_options(options);
145 sections.score || sections.targets
146}
147
148pub struct ProgrammaticHealthNextStepFacts {
153 pub suggestions_enabled: bool,
155 pub offer_setup: bool,
157 pub impact_digest: Option<fallow_output::ImpactDigestCounts>,
159 pub audit_changed: bool,
161}
162
163pub struct ProgrammaticHealthAnalysis {
168 pub report: HealthReport,
170 pub grouping: Option<HealthGrouping>,
172 pub root: PathBuf,
174 pub elapsed: std::time::Duration,
176}
177
178impl ProgrammaticHealthAnalysis {
179 fn from_engine<GroupResolver>(
180 analysis: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
181 ) -> Self {
182 Self {
183 root: analysis.config.root,
184 report: analysis.report,
185 grouping: analysis.grouping,
186 elapsed: analysis.elapsed,
187 }
188 }
189}
190
191pub struct ProgrammaticHealthRun {
196 pub analysis: ProgrammaticHealthAnalysis,
198 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
200 pub next_step_facts: ProgrammaticHealthNextStepFacts,
202 pub telemetry_analysis_run_id: Option<String>,
204 pub request_outcomes: Option<fallow_output::RequestOutcomes>,
206}
207
208pub trait ProgrammaticHealthRunner {
213 fn run_programmatic_health(
220 &self,
221 options: &ComplexityOptions,
222 ) -> Result<ProgrammaticHealthRun, ProgrammaticError>;
223
224 fn refuses_config_type_aware(&self) -> bool {
229 false
230 }
231}
232
233#[derive(Debug, Clone, Copy, Default)]
241pub struct EngineHealthRunner;
242
243impl ProgrammaticHealthRunner for EngineHealthRunner {
244 fn run_programmatic_health(
245 &self,
246 options: &ComplexityOptions,
247 ) -> Result<ProgrammaticHealthRun, ProgrammaticError> {
248 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
249 resolved.install(|| {
250 let resolve = || {
253 resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::Health)
254 .map_err(|_| health_config_load_error())
255 };
256 let run = if health_reads_config_type_aware(options) {
257 type_aware_config::resolve_run_refusing_type_aware(
258 &options.analysis,
259 type_aware_config::TypeAwareCommand::Analysis,
260 type_aware_config::ConfigLocation::of(&resolved),
261 resolve,
262 )?
263 } else {
264 resolve()?
265 };
266 run_programmatic_health_on_engine(&resolved, options, &run)
267 })
268 }
269
270 fn refuses_config_type_aware(&self) -> bool {
271 true
272 }
273}
274
275pub(super) fn health_config_load_error() -> ProgrammaticError {
278 programmatic_health_error(
279 "health",
280 fallow_engine::health::HealthError::Message {
281 message: "failed to load health project config".to_owned(),
282 exit_code: 2,
283 },
284 )
285}
286
287fn run_programmatic_health_on_engine(
288 resolved: &ProgrammaticAnalysisContext,
289 options: &ComplexityOptions,
290 run: &ResolvedRun,
291) -> ProgrammaticResult<ProgrammaticHealthRun> {
292 let health_options = derive_programmatic_health_execution_options(resolved, options);
293 let health = crate::run::runnable(run, PlannedAnalysis::Health)?;
294 let loaded = fallow_engine::health::UngroupedHealthSession::load(&health_options, &health)
295 .map_err(|error| programmatic_health_error("health", error))?;
296 let workspace_roots = workspace_roots_for_session(resolved, loaded.workspaces())?;
297 let result = loaded
298 .run(&health_options, workspace_roots)
299 .map_err(|error| programmatic_health_error("health", error))?;
300 resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
301
302 Ok(programmatic_health_run_from_engine_result(
303 result,
304 resolved.request_outcomes(),
305 ))
306}
307
308fn programmatic_health_run_from_engine_result<GroupResolver>(
309 result: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
310 request_outcomes: Option<fallow_output::RequestOutcomes>,
311) -> ProgrammaticHealthRun {
312 let root = result.config.root.clone();
313 let next_step_facts = ProgrammaticHealthNextStepFacts {
314 suggestions_enabled: suggestions_enabled(),
315 offer_setup: setup_pointer_applicable(&root),
316 impact_digest: None,
317 audit_changed: audit_changed_applicable(&root),
318 };
319 ProgrammaticHealthRun {
320 workspace_diagnostics: result.workspace_diagnostics.clone(),
321 analysis: ProgrammaticHealthAnalysis::from_engine(result.without_group_resolver()),
322 next_step_facts,
323 telemetry_analysis_run_id: None,
324 request_outcomes,
325 }
326}
327
328#[cfg(test)]
329pub(super) fn run_health_with_session(
330 options: &ComplexityOptions,
331 resolved: &ProgrammaticAnalysisContext,
332 session: &AnalysisSession,
333 changed_files: Option<&FxHashSet<PathBuf>>,
334) -> ProgrammaticResult<HealthProgrammaticOutput> {
335 run_health_with_session_artifacts(options, resolved, session, changed_files, None, None)
336}
337
338pub(super) fn run_health_with_session_artifacts(
339 options: &ComplexityOptions,
340 resolved: &ProgrammaticAnalysisContext,
341 session: &AnalysisSession,
342 changed_files: Option<&FxHashSet<PathBuf>>,
343 pre_computed_analysis: Option<DeadCodeAnalysisArtifacts>,
344 pre_computed_duplication: Option<DuplicationReport>,
345) -> ProgrammaticResult<HealthProgrammaticOutput> {
346 crate::validate_complexity_options(options)?;
347 let health_options = derive_programmatic_health_execution_options(resolved, options);
348 let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
349 let result = fallow_engine::health::run_ungrouped_health_with_session_artifacts(
350 &health_options,
351 workspace_roots,
352 session,
353 changed_files.map(|files| files.iter().cloned().collect()),
354 pre_computed_analysis,
355 pre_computed_duplication,
356 )
357 .map_err(|error| programmatic_health_error("health", error))?;
358 resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
359
360 Ok(assemble_health_programmatic_output(
361 options,
362 programmatic_health_run_from_engine_result(result, resolved.request_outcomes()),
363 ))
364}
365
366fn programmatic_health_error(
367 command: &str,
368 error: fallow_engine::health::HealthError,
369) -> ProgrammaticError {
370 let (message, exit_code) = match error {
371 fallow_engine::health::HealthError::Message { message, exit_code } => (message, exit_code),
372 fallow_engine::health::HealthError::Printed(exit_code) => {
373 (format!("{command} failed"), exit_code)
374 }
375 };
376 let code = format!(
377 "FALLOW_{}_FAILED",
378 command.replace('-', "_").to_ascii_uppercase()
379 );
380 ProgrammaticError::new(message, exit_code)
381 .with_code(code)
382 .with_context(format!("fallow {command}"))
383 .with_help(format!(
384 "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
385 ))
386}
387
388pub fn run_health(options: &ComplexityOptions) -> ProgrammaticResult<HealthProgrammaticOutput> {
395 run_health_with_runner(options, &EngineHealthRunner)
396}
397
398#[must_use]
399fn derive_programmatic_health_execution_options<'a>(
400 resolved: &'a ProgrammaticAnalysisContext,
401 options: &'a ComplexityOptions,
402) -> fallow_engine::health::HealthExecutionOptions<'a> {
403 let run = crate::derive_complexity_run_options(options);
404
405 fallow_engine::health::HealthExecutionOptions {
406 root: resolved.root(),
407 config_path: resolved.config_path(),
408 output: OutputFormat::Human,
409 no_cache: resolved.no_cache(),
410 threads: resolved.threads(),
411 quiet: true,
412 complexity_breakdown: run.complexity_breakdown,
413 thresholds: crate::thresholds_to_engine(run.thresholds),
414 top: run.top,
415 sort: crate::complexity_sort_to_engine(run.sort),
416 production: resolved.production_override().unwrap_or(false),
417 production_override: resolved.production_override(),
418 allow_remote_extends: resolved.allow_remote_extends(),
419 changed_since: resolved.changed_since(),
420 diff_index: resolved.diff_index(),
421 use_shared_diff_index: false,
422 workspace: resolved.workspace(),
423 changed_workspaces: resolved.changed_workspaces(),
424 baseline: None,
425 save_baseline: None,
426 baseline_mode: fallow_engine::baseline::HealthBaselineMode::Count,
427 baseline_mode_explicit: false,
428 complexity: run.sections.complexity,
429 file_scores: run.sections.file_scores,
430 coverage_gaps: run.sections.coverage_gaps,
431 config_activates_coverage_gaps: options.config_activates_coverage_gaps
432 || !run.sections.any_section,
433 hotspots: run.sections.hotspots,
434 ownership: run.sections.ownership,
435 targets: run.sections.targets,
436 css: run.css,
437 css_deep: run.css_deep,
438 force_full: run.sections.force_full,
439 score_only_output: run.sections.score_only_output,
440 enforce_coverage_gap_gate: true,
441 effort: run.effort.map(crate::target_effort_to_output),
442 score: run.sections.score,
443 gates: fallow_engine::health::HealthGateOptions::default(),
444 since: run.since,
445 min_commits: run.min_commits,
446 explain: resolved.explain_enabled(),
447 summary: false,
448 save_snapshot: None,
449 trend: false,
450 coverage_inputs: crate::coverage_inputs_to_engine(run.coverage_inputs),
451 performance: false,
452 runtime_coverage: None,
453 churn_file: None,
454 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
455 group_by: None,
456 group_filter: None,
457 trend_from: None,
458 scope: None,
459 ownership_emails: run
460 .ownership_emails
461 .map(crate::ownership_email_mode_to_config),
462 }
463}
464
465pub fn run_complexity_with_runner(
478 options: &ComplexityOptions,
479 runner: &impl ProgrammaticHealthRunner,
480) -> ProgrammaticResult<HealthProgrammaticOutput> {
481 crate::validate_complexity_options(options)?;
482 if !runner.refuses_config_type_aware() {
483 reject_health_config_type_aware(options)?;
484 }
485 run_validated_complexity(options, runner)
486}
487
488pub(super) fn run_health_in_run(
492 options: &ComplexityOptions,
493 resolved: &ProgrammaticAnalysisContext,
494 run: &ResolvedRun,
495) -> ProgrammaticResult<HealthProgrammaticOutput> {
496 crate::validate_complexity_options(options)?;
497 crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
498 let health = resolved.install(|| run_programmatic_health_on_engine(resolved, options, run))?;
499 Ok(assemble_health_programmatic_output(options, health))
500}
501
502fn health_reads_config_type_aware(options: &ComplexityOptions) -> bool {
505 !options.css && !crate::derive_complexity_options(options).any_section
506}
507
508fn reject_health_config_type_aware(options: &ComplexityOptions) -> ProgrammaticResult<()> {
511 if !health_reads_config_type_aware(options) {
512 return Ok(());
513 }
514 let root = crate::analysis_context::resolve_analysis_root(options.analysis.root.as_deref())?;
515 crate::analysis_context::validate_analysis_config_path(
516 options.analysis.config_path.as_deref(),
517 )?;
518 type_aware_config::reject_config_type_aware_at(
519 &options.analysis,
520 type_aware_config::ConfigLocation {
521 root: &root,
522 config_path: options.analysis.config_path.as_deref(),
523 allow_remote_extends: options.analysis.allow_remote_extends,
524 },
525 type_aware_config::TypeAwareCommand::Analysis,
526 )
527}
528
529fn run_validated_complexity(
530 options: &ComplexityOptions,
531 runner: &impl ProgrammaticHealthRunner,
532) -> ProgrammaticResult<HealthProgrammaticOutput> {
533 crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
534 Ok(assemble_health_programmatic_output(
535 options,
536 runner.run_programmatic_health(options)?,
537 ))
538}
539
540fn assemble_health_programmatic_output(
541 options: &ComplexityOptions,
542 run: ProgrammaticHealthRun,
543) -> HealthProgrammaticOutput {
544 let ProgrammaticHealthRun {
545 analysis,
546 workspace_diagnostics,
547 next_step_facts,
548 telemetry_analysis_run_id,
549 request_outcomes,
550 } = run;
551 let root = analysis.root.clone();
552 let next_steps =
553 fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
554 &analysis.report,
555 next_step_facts.suggestions_enabled,
556 next_step_facts.offer_setup,
557 next_step_facts.impact_digest,
558 next_step_facts.audit_changed,
559 None,
560 ));
561 HealthProgrammaticOutput {
562 report: analysis.report,
563 grouping: analysis.grouping,
564 root,
565 elapsed: analysis.elapsed,
566 explain: options.analysis.explain,
567 workspace_diagnostics,
568 next_steps,
569 telemetry_analysis_run_id,
570 request_outcomes,
571 }
572}
573
574pub fn run_health_with_runner(
580 options: &ComplexityOptions,
581 runner: &impl ProgrammaticHealthRunner,
582) -> ProgrammaticResult<HealthProgrammaticOutput> {
583 run_complexity_with_runner(options, runner)
584}
585
586#[cfg(test)]
587mod cancellation_tests;
588#[cfg(test)]
589mod tests;