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 {
118 allow_remote_extends,
119 },
120 )
121 .map_err(|err| config_load_error(&err))?;
122 Ok(file.path.map(|_| file.config))
123}
124
125fn config_load_error(err: &ConfigLoadError) -> ProgrammaticError {
126 ProgrammaticError::new(format!("failed to load config: {}", err.chain()), 2)
127 .with_code("FALLOW_CONFIG_LOAD_FAILED")
128 .with_context("analysis.configPath")
129}
130
131pub(super) fn health_may_consume_dead_code_artifacts(
132 options: &ComplexityOptions,
133 config: &fallow_config::ResolvedConfig,
134) -> bool {
135 let sections = derive_complexity_options(options);
136 let max_crap = options.max_crap.unwrap_or(config.health.max_crap);
137 sections.file_scores
138 || sections.coverage_gaps
139 || sections.hotspots
140 || sections.targets
141 || sections.force_full
142 || max_crap > 0.0
143}
144
145pub(super) fn health_may_consume_duplication_report(options: &ComplexityOptions) -> bool {
146 let sections = derive_complexity_options(options);
147 sections.score || sections.targets
148}
149
150pub struct ProgrammaticHealthNextStepFacts {
155 pub suggestions_enabled: bool,
157 pub offer_setup: bool,
159 pub impact_digest: Option<fallow_output::ImpactDigestCounts>,
161 pub audit_changed: bool,
163}
164
165pub struct ProgrammaticHealthAnalysis {
170 pub report: HealthReport,
172 pub grouping: Option<HealthGrouping>,
174 pub root: PathBuf,
176 pub elapsed: std::time::Duration,
178}
179
180impl ProgrammaticHealthAnalysis {
181 fn from_engine<GroupResolver>(
182 analysis: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
183 ) -> Self {
184 Self {
185 root: analysis.config.root,
186 report: analysis.report,
187 grouping: analysis.grouping,
188 elapsed: analysis.elapsed,
189 }
190 }
191}
192
193pub struct ProgrammaticHealthRun {
198 pub analysis: ProgrammaticHealthAnalysis,
200 pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
202 pub next_step_facts: ProgrammaticHealthNextStepFacts,
204 pub telemetry_analysis_run_id: Option<String>,
206 pub request_outcomes: Option<fallow_output::RequestOutcomes>,
208}
209
210pub trait ProgrammaticHealthRunner {
215 fn run_programmatic_health(
222 &self,
223 options: &ComplexityOptions,
224 ) -> Result<ProgrammaticHealthRun, ProgrammaticError>;
225
226 fn refuses_config_type_aware(&self) -> bool {
231 false
232 }
233}
234
235#[derive(Debug, Clone, Copy, Default)]
243pub struct EngineHealthRunner;
244
245impl ProgrammaticHealthRunner for EngineHealthRunner {
246 fn run_programmatic_health(
247 &self,
248 options: &ComplexityOptions,
249 ) -> Result<ProgrammaticHealthRun, ProgrammaticError> {
250 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
251 resolved.install(|| {
252 let resolve = || {
255 resolve_programmatic_run(&options.analysis, &ProgrammaticEntry::Health)
256 .map_err(|_| health_config_load_error())
257 };
258 let run = if health_reads_config_type_aware(options) {
259 type_aware_config::resolve_run_refusing_type_aware(
260 &options.analysis,
261 type_aware_config::TypeAwareCommand::Analysis,
262 type_aware_config::ConfigLocation::of(&resolved),
263 resolve,
264 )?
265 } else {
266 resolve()?
267 };
268 run_programmatic_health_on_engine(&resolved, options, &run)
269 })
270 }
271
272 fn refuses_config_type_aware(&self) -> bool {
273 true
274 }
275}
276
277pub(super) fn health_config_load_error() -> ProgrammaticError {
280 programmatic_health_error(
281 "health",
282 fallow_engine::health::HealthError::Message {
283 message: "failed to load health project config".to_owned(),
284 exit_code: 2,
285 },
286 )
287}
288
289fn run_programmatic_health_on_engine(
290 resolved: &ProgrammaticAnalysisContext,
291 options: &ComplexityOptions,
292 run: &ResolvedRun,
293) -> ProgrammaticResult<ProgrammaticHealthRun> {
294 let health_options = derive_programmatic_health_execution_options(resolved, options);
295 let health = crate::run::runnable(run, PlannedAnalysis::Health)?;
296 let loaded = fallow_engine::health::UngroupedHealthSession::load(&health_options, &health)
297 .map_err(|error| programmatic_health_error("health", error))?;
298 let workspace_roots = workspace_roots_for_session(resolved, loaded.workspaces())?;
299 let result = loaded
300 .run(&health_options, workspace_roots)
301 .map_err(|error| programmatic_health_error("health", error))?;
302 resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
303
304 Ok(programmatic_health_run_from_engine_result(
305 result,
306 resolved.request_outcomes(),
307 ))
308}
309
310fn programmatic_health_run_from_engine_result<GroupResolver>(
311 result: fallow_engine::health::HealthAnalysisResult<GroupResolver>,
312 request_outcomes: Option<fallow_output::RequestOutcomes>,
313) -> ProgrammaticHealthRun {
314 let root = result.config.root.clone();
315 let next_step_facts = ProgrammaticHealthNextStepFacts {
316 suggestions_enabled: suggestions_enabled(),
317 offer_setup: setup_pointer_applicable(&root),
318 impact_digest: None,
319 audit_changed: audit_changed_applicable(&root),
320 };
321 ProgrammaticHealthRun {
322 workspace_diagnostics: result.workspace_diagnostics.clone(),
323 analysis: ProgrammaticHealthAnalysis::from_engine(result.without_group_resolver()),
324 next_step_facts,
325 telemetry_analysis_run_id: None,
326 request_outcomes,
327 }
328}
329
330#[cfg(test)]
331pub(super) fn run_health_with_session(
332 options: &ComplexityOptions,
333 resolved: &ProgrammaticAnalysisContext,
334 session: &AnalysisSession,
335 changed_files: Option<&FxHashSet<PathBuf>>,
336) -> ProgrammaticResult<HealthProgrammaticOutput> {
337 run_health_with_session_artifacts(options, resolved, session, changed_files, None, None)
338}
339
340pub(super) fn run_health_with_session_artifacts(
341 options: &ComplexityOptions,
342 resolved: &ProgrammaticAnalysisContext,
343 session: &AnalysisSession,
344 changed_files: Option<&FxHashSet<PathBuf>>,
345 pre_computed_analysis: Option<DeadCodeAnalysisArtifacts>,
346 pre_computed_duplication: Option<DuplicationReport>,
347) -> ProgrammaticResult<HealthProgrammaticOutput> {
348 crate::validate_complexity_options(options)?;
349 let health_options = derive_programmatic_health_execution_options(resolved, options);
350 let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
351 let result = fallow_engine::health::run_ungrouped_health_with_session_artifacts(
352 &health_options,
353 workspace_roots,
354 session,
355 changed_files.map(|files| files.iter().cloned().collect()),
356 pre_computed_analysis,
357 pre_computed_duplication,
358 )
359 .map_err(|error| programmatic_health_error("health", error))?;
360 resolved.record_changed_since_from_runner(result.changed_files_analyzed.as_deref());
361
362 Ok(assemble_health_programmatic_output(
363 options,
364 programmatic_health_run_from_engine_result(result, resolved.request_outcomes()),
365 ))
366}
367
368fn programmatic_health_error(
369 command: &str,
370 error: fallow_engine::health::HealthError,
371) -> ProgrammaticError {
372 let (message, exit_code) = match error {
373 fallow_engine::health::HealthError::Message { message, exit_code } => (message, exit_code),
374 fallow_engine::health::HealthError::Printed(exit_code) => {
375 (format!("{command} failed"), exit_code)
376 }
377 };
378 let code = format!(
379 "FALLOW_{}_FAILED",
380 command.replace('-', "_").to_ascii_uppercase()
381 );
382 ProgrammaticError::new(message, exit_code)
383 .with_code(code)
384 .with_context(format!("fallow {command}"))
385 .with_help(format!(
386 "Re-run `fallow {command} --format json --quiet` in the target project for CLI diagnostics"
387 ))
388}
389
390pub fn run_health(options: &ComplexityOptions) -> ProgrammaticResult<HealthProgrammaticOutput> {
397 run_health_with_runner(options, &EngineHealthRunner)
398}
399
400#[must_use]
401fn derive_programmatic_health_execution_options<'a>(
402 resolved: &'a ProgrammaticAnalysisContext,
403 options: &'a ComplexityOptions,
404) -> fallow_engine::health::HealthExecutionOptions<'a> {
405 let run = crate::derive_complexity_run_options(options);
406
407 fallow_engine::health::HealthExecutionOptions {
408 root: resolved.root(),
409 config_path: resolved.config_path(),
410 output: OutputFormat::Human,
411 no_cache: resolved.no_cache(),
412 threads: resolved.threads(),
413 quiet: true,
414 complexity_breakdown: run.complexity_breakdown,
415 thresholds: crate::thresholds_to_engine(run.thresholds),
416 top: run.top,
417 sort: crate::complexity_sort_to_engine(run.sort),
418 production: resolved.production_override().unwrap_or(false),
419 production_override: resolved.production_override(),
420 allow_remote_extends: resolved.allow_remote_extends(),
421 changed_since: resolved.changed_since(),
422 diff_index: resolved.diff_index(),
423 use_shared_diff_index: false,
424 workspace: resolved.workspace(),
425 changed_workspaces: resolved.changed_workspaces(),
426 baseline: None,
427 save_baseline: None,
428 baseline_mode: fallow_engine::baseline::HealthBaselineMode::Count,
429 baseline_mode_explicit: false,
430 complexity: run.sections.complexity,
431 file_scores: run.sections.file_scores,
432 coverage_gaps: run.sections.coverage_gaps,
433 config_activates_coverage_gaps: options.config_activates_coverage_gaps
434 || !run.sections.any_section,
435 hotspots: run.sections.hotspots,
436 ownership: run.sections.ownership,
437 targets: run.sections.targets,
438 css: run.css,
439 css_deep: run.css_deep,
440 force_full: run.sections.force_full,
441 score_only_output: run.sections.score_only_output,
442 enforce_coverage_gap_gate: true,
443 effort: run.effort.map(crate::target_effort_to_output),
444 score: run.sections.score,
445 gates: fallow_engine::health::HealthGateOptions::default(),
446 since: run.since,
447 min_commits: run.min_commits,
448 explain: resolved.explain_enabled(),
449 summary: false,
450 save_snapshot: None,
451 trend: false,
452 coverage_inputs: crate::coverage_inputs_to_engine(run.coverage_inputs),
453 performance: false,
454 runtime_coverage: None,
455 churn_file: None,
456 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
457 group_by: None,
458 group_filter: None,
459 trend_from: None,
460 scope: None,
461 ownership_emails: run
462 .ownership_emails
463 .map(crate::ownership_email_mode_to_config),
464 }
465}
466
467pub fn run_complexity_with_runner(
480 options: &ComplexityOptions,
481 runner: &impl ProgrammaticHealthRunner,
482) -> ProgrammaticResult<HealthProgrammaticOutput> {
483 crate::validate_complexity_options(options)?;
484 if !runner.refuses_config_type_aware() {
485 reject_health_config_type_aware(options)?;
486 }
487 run_validated_complexity(options, runner)
488}
489
490pub(super) fn run_health_in_run(
494 options: &ComplexityOptions,
495 resolved: &ProgrammaticAnalysisContext,
496 run: &ResolvedRun,
497) -> ProgrammaticResult<HealthProgrammaticOutput> {
498 crate::validate_complexity_options(options)?;
499 crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
500 let health = resolved.install(|| run_programmatic_health_on_engine(resolved, options, run))?;
501 Ok(assemble_health_programmatic_output(options, health))
502}
503
504fn health_reads_config_type_aware(options: &ComplexityOptions) -> bool {
507 !options.css && !crate::derive_complexity_options(options).any_section
508}
509
510fn reject_health_config_type_aware(options: &ComplexityOptions) -> ProgrammaticResult<()> {
513 if !health_reads_config_type_aware(options) {
514 return Ok(());
515 }
516 let root = crate::analysis_context::resolve_analysis_root(options.analysis.root.as_deref())?;
517 crate::analysis_context::validate_analysis_config_path(
518 options.analysis.config_path.as_deref(),
519 )?;
520 type_aware_config::reject_config_type_aware_at(
521 &options.analysis,
522 type_aware_config::ConfigLocation {
523 root: &root,
524 config_path: options.analysis.config_path.as_deref(),
525 allow_remote_extends: options.analysis.allow_remote_extends,
526 },
527 type_aware_config::TypeAwareCommand::Analysis,
528 )
529}
530
531fn run_validated_complexity(
532 options: &ComplexityOptions,
533 runner: &impl ProgrammaticHealthRunner,
534) -> ProgrammaticResult<HealthProgrammaticOutput> {
535 crate::analysis_context::ensure_options_not_cancelled(&options.analysis, "health analysis")?;
536 Ok(assemble_health_programmatic_output(
537 options,
538 runner.run_programmatic_health(options)?,
539 ))
540}
541
542fn assemble_health_programmatic_output(
543 options: &ComplexityOptions,
544 run: ProgrammaticHealthRun,
545) -> HealthProgrammaticOutput {
546 let ProgrammaticHealthRun {
547 analysis,
548 workspace_diagnostics,
549 next_step_facts,
550 telemetry_analysis_run_id,
551 request_outcomes,
552 } = run;
553 let root = analysis.root.clone();
554 let next_steps =
555 fallow_output::build_health_next_steps(fallow_output::build_health_next_steps_input(
556 &analysis.report,
557 next_step_facts.suggestions_enabled,
558 next_step_facts.offer_setup,
559 next_step_facts.impact_digest,
560 next_step_facts.audit_changed,
561 None,
562 ));
563 HealthProgrammaticOutput {
564 report: analysis.report,
565 grouping: analysis.grouping,
566 root,
567 elapsed: analysis.elapsed,
568 explain: options.analysis.explain,
569 workspace_diagnostics,
570 next_steps,
571 telemetry_analysis_run_id,
572 request_outcomes,
573 }
574}
575
576pub fn run_health_with_runner(
582 options: &ComplexityOptions,
583 runner: &impl ProgrammaticHealthRunner,
584) -> ProgrammaticResult<HealthProgrammaticOutput> {
585 run_complexity_with_runner(options, runner)
586}
587
588#[cfg(test)]
589mod cancellation_tests;
590#[cfg(test)]
591mod tests;