1use std::path::{Path, PathBuf};
4
5use fallow_config::{EmailMode, WorkspaceInfo};
6use fallow_output::{
7 DiffIndex, EffortEstimate, FindingSeverity, GroupByMode, RuntimeCoverageReport,
8 RuntimeCoverageWatermark,
9};
10use fallow_types::output_format::OutputFormat;
11use fallow_types::path_util::is_absolute_path_any_platform;
12use fallow_types::results::AnalysisResults;
13use rustc_hash::{FxHashMap, FxHashSet};
14
15use crate::module_graph::RetainedModuleGraph;
16use crate::results::DeadCodeAnalysisArtifacts;
17
18mod actions;
19mod analysis_data;
20mod assembly;
21mod baseline_io;
22mod branching;
23pub use branching::BranchingByFile;
24use branching::branching_by_file;
25mod change_coupling_section;
26mod churn_file;
27mod component_rollup;
28mod contributor;
29mod core_pipeline;
30mod coverage_gaps;
31pub mod coverage_input;
32mod coverage_intelligence;
33mod coverage_settings;
34pub mod coverage_v8;
35mod css_analytics;
36mod cycle_files;
37mod cyclomatic_policy;
38mod derived_sections;
39pub(crate) mod diagnostics;
40mod execute;
41mod file_lines;
42mod file_scores;
43mod filters;
44mod finding_sort;
45mod findings;
46mod findings_pipeline;
47mod framework_health;
48mod grouping;
49pub use grouping::validate_group_filter;
50mod health_error;
51mod hotspots;
52pub(crate) mod ignore;
53mod inline;
54pub use inline::{InlineComplexity, inline_complexity};
55mod large_functions;
56mod output_build;
57pub mod ownership;
58mod package_json;
59mod pipeline;
60mod react_hooks;
61mod result;
62mod runner;
63mod runtime_filter;
64mod runtime_sections;
65mod scope;
66pub mod scoring;
69mod shallow_directories;
70pub mod styling_score;
71mod subset_filter;
72mod tailwind_theme;
73mod targets;
74mod test_reach;
75mod threshold_overrides;
76mod timings;
77mod vital_data;
78mod vital_signs_scope;
79
80pub use crate::results::HealthAnalysisResult;
81pub use churn_file::validate_health_churn_file;
82pub use css_analytics::StylingAnalysisArtifacts;
83use derived_sections::{
84 HealthDerivedSectionInput, HealthDerivedSections, prepare_health_derived_sections,
85};
86use execute::HealthOptions;
87pub use execute::{execute_health_inner, execute_health_inner_with_baseline};
88use file_scores::{
89 FileScoresAndChurnInput, compute_file_scores_and_churn, health_file_scores_slice,
90 print_slow_churn_note,
91};
92use finding_sort::sort_findings;
93pub use health_error::HealthError;
94pub use hotspots::{
95 TargetChurnEvidence, TargetChurnOptions, TargetChurnOutcome, analyze_target_churn,
96};
97pub use pipeline::{HealthPipelineInputs, HealthScopeInputs};
98pub use runner::{
99 UngroupedHealthSession, run_ungrouped_health_with_session,
100 run_ungrouped_health_with_session_artifacts,
101};
102pub use test_reach::TestReachGraph;
103use vital_data::{HealthVitalData, HealthVitalDataInput, prepare_health_vital_data};
104use vital_signs_scope::{
105 VitalSignsAndCountsInput, apply_duplication_metrics, compute_vital_signs_and_counts,
106};
107
108pub(crate) fn build_styling_analysis_artifacts(
109 files: &[crate::discover::DiscoveredFile],
110 modules: &[crate::source::ModuleInfo],
111 config: &fallow_config::ResolvedConfig,
112) -> StylingAnalysisArtifacts {
113 css_analytics::build_styling_analysis_artifacts(files, modules, config)
114}
115
116#[must_use]
118pub fn shared_parse_data_from_artifacts(
119 results: &AnalysisResults,
120 graph: Option<RetainedModuleGraph>,
121 modules: Option<Vec<crate::source::ModuleInfo>>,
122 files: Option<Vec<crate::discover::DiscoveredFile>>,
123 workspaces: Vec<WorkspaceInfo>,
124 script_used_packages: impl IntoIterator<Item = String>,
125) -> Option<HealthSharedParseData> {
126 let (Some(modules), Some(files)) = (modules, files) else {
127 return None;
128 };
129 let script_used_packages: FxHashSet<String> = script_used_packages.into_iter().collect();
130 let mut results = results.clone();
134 results.restore_cascade_findings();
135 let analysis_output = graph.map(|graph| DeadCodeAnalysisArtifacts {
136 results: results.clone(),
137 timings: None,
138 graph: Some(graph),
139 modules: None,
140 files: None,
141 script_used_packages: script_used_packages.clone(),
142 trace_provenance: crate::trace::TraceProvenance::default(),
143 file_hashes: FxHashMap::default(),
144 });
145 Some(HealthSharedParseData {
146 files,
147 modules,
148 dead_code_results: Some(results),
149 workspaces,
150 analysis_output,
151 })
152}
153
154#[must_use]
160pub fn should_precompute_dead_code_analysis(
161 options: &HealthExecutionOptions<'_>,
162 config: &fallow_config::ResolvedConfig,
163) -> bool {
164 let max_crap = options
165 .thresholds
166 .max_crap
167 .unwrap_or(config.health.max_crap);
168 options.file_scores
169 || options.coverage_gaps
170 || options.shallow_directories
171 || options.config_activates_coverage_gaps
172 || options.hotspots
173 || options.targets
174 || options.force_full
175 || max_crap > 0.0
176 || options.runtime_coverage.is_some()
177}
178
179pub trait HealthGroupResolver {
185 fn mode_label(&self) -> &'static str;
187 fn group_of<'a>(&'a self, rel_path: &'a Path) -> PathGroup<'a>;
189}
190
191#[derive(Debug, Clone, Copy)]
193pub struct PathGroup<'a> {
194 pub key: &'a str,
196 pub section_owners: Option<&'a [String]>,
199}
200
201#[derive(Debug, Clone, Copy)]
204#[expect(
205 clippy::empty_enums,
206 reason = "NoGroupResolver must be uninhabited so that no code can construct it"
207)]
208pub enum NoGroupResolver {}
209
210#[expect(
211 clippy::uninhabited_references,
212 reason = "NoGroupResolver is uninhabited; these methods are unreachable and exist only to satisfy the trait bound for the group-less programmatic path"
213)]
214impl HealthGroupResolver for NoGroupResolver {
215 fn mode_label(&self) -> &'static str {
216 match *self {}
217 }
218 fn group_of<'a>(&'a self, _rel_path: &'a Path) -> PathGroup<'a> {
219 match *self {}
220 }
221}
222
223pub type RuntimeCoverageAnalyzer<'a> = dyn Fn(&RuntimeCoverageOptions, RuntimeCoverageSeamInput<'_>) -> Result<RuntimeCoverageReport, u8>
235 + 'a;
236
237pub struct RuntimeCoverageSeamInput<'a> {
239 pub root: &'a Path,
241 pub modules: &'a [fallow_types::extract::ModuleInfo],
243 pub analysis_output: &'a DeadCodeAnalysisArtifacts,
246 pub istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
248 pub file_paths: &'a rustc_hash::FxHashMap<fallow_types::discover::FileId, &'a PathBuf>,
250 pub ignore_set: &'a globset::GlobSet,
252 pub changed_files: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
254 pub ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
256 pub top: Option<usize>,
258 pub codeowners_path: Option<&'a str>,
260 pub quiet: bool,
262 pub output: OutputFormat,
264 pub test_reach: Option<&'a TestReachGraph>,
267}
268
269pub struct HealthSeams<'a> {
273 pub runtime_coverage_analyzer: &'a RuntimeCoverageAnalyzer<'a>,
275 pub note_graph_structure: &'a dyn Fn(usize, usize),
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub enum HealthSort {
284 Severity,
287 Cyclomatic,
289 Cognitive,
291 Lines,
293}
294
295#[derive(Debug, Clone, Copy, Default, PartialEq)]
297pub struct HealthThresholdOverrides {
298 pub max_cyclomatic: Option<u16>,
300 pub max_cognitive: Option<u16>,
302 pub max_crap: Option<f64>,
305 pub max_file_lines: Option<u32>,
308}
309
310#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
312pub struct HealthCoverageInputs<'a> {
313 pub coverage: Option<&'a Path>,
315 pub coverage_root: Option<&'a Path>,
318 pub coverage_relocated: bool,
324}
325
326pub fn validate_coverage_root_absolute(coverage_root: Option<&Path>) -> Result<(), String> {
333 if let Some(path) = coverage_root
334 && !is_absolute_path_any_platform(path)
335 {
336 return Err(format!(
337 "--coverage-root expects an absolute path prefix from the coverage data, got '{}'. Use the checkout prefix from the machine that generated coverage, for example '/home/runner/work/myapp'.",
338 path.display()
339 ));
340 }
341 Ok(())
342}
343
344#[derive(Debug, Clone, Copy, Default, PartialEq)]
346pub struct HealthGateOptions {
347 pub min_score: Option<f64>,
349 pub min_severity: Option<FindingSeverity>,
351 pub report_only: bool,
353 pub fail_on_stale_baseline: bool,
355 pub fail_on_parse_error: bool,
359 pub fail_on_issues: bool,
363}
364
365#[derive(Debug, Clone)]
367pub struct HealthSectionOptions {
368 output: OutputFormat,
369 complexity: bool,
370 file_scores: bool,
371 coverage_gaps: bool,
372 shallow_directories: bool,
373 hotspots: bool,
374 targets: bool,
375 css: bool,
376 score: bool,
377 score_gate: bool,
378 snapshot_requested: bool,
379 trend: bool,
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub struct DerivedHealthSections {
385 pub any_section: bool,
388 pub complexity: bool,
390 pub file_scores: bool,
392 pub coverage_gaps: bool,
394 pub shallow_directories: bool,
396 pub hotspots: bool,
398 pub targets: bool,
400 pub css: bool,
402 pub score: bool,
404 pub force_full: bool,
407 pub score_only_output: bool,
410}
411
412impl DerivedHealthSections {
413 pub const NONE: Self = Self {
415 any_section: false,
416 complexity: false,
417 file_scores: false,
418 coverage_gaps: false,
419 shallow_directories: false,
420 hotspots: false,
421 targets: false,
422 css: false,
423 score: false,
424 force_full: false,
425 score_only_output: false,
426 };
427}
428
429#[derive(Debug, Clone)]
432pub struct HealthRunOptionsInput<'a> {
433 pub output: OutputFormat,
435 pub thresholds: HealthThresholdOverrides,
437 pub top: Option<usize>,
439 pub sort: HealthSort,
441 pub complexity: bool,
443 pub file_scores: bool,
445 pub coverage_gaps: bool,
447 pub shallow_directories: bool,
449 pub hotspots: bool,
451 pub ownership: bool,
453 pub ownership_emails: Option<EmailMode>,
455 pub targets: bool,
457 pub css: bool,
459 pub effort: Option<EffortEstimate>,
461 pub score: bool,
463 pub gates: HealthGateOptions,
465 pub snapshot_requested: bool,
467 pub trend: bool,
469 pub since: Option<&'a str>,
471 pub min_commits: Option<u32>,
473 pub coverage_inputs: HealthCoverageInputs<'a>,
475 pub runtime_coverage: Option<RuntimeCoverageOptions>,
477}
478
479#[derive(Debug, Clone)]
481pub struct HealthRunOptions<'a> {
482 pub thresholds: HealthThresholdOverrides,
484 pub top: Option<usize>,
486 pub sort: HealthSort,
488 pub sections: DerivedHealthSections,
490 pub ownership: bool,
492 pub ownership_emails: Option<EmailMode>,
494 pub effort: Option<EffortEstimate>,
496 pub gates: HealthGateOptions,
498 pub since: Option<&'a str>,
500 pub min_commits: Option<u32>,
502 pub coverage_inputs: HealthCoverageInputs<'a>,
504 pub runtime_coverage: Option<RuntimeCoverageOptions>,
506}
507
508#[derive(Debug, Clone)]
512pub struct HealthExecutionOptions<'a> {
513 pub root: &'a Path,
515 pub config_path: &'a Option<PathBuf>,
517 pub output: OutputFormat,
519 pub no_cache: bool,
521 pub threads: usize,
523 pub quiet: bool,
525 pub complexity_breakdown: bool,
530 pub thresholds: HealthThresholdOverrides,
532 pub top: Option<usize>,
534 pub sort: HealthSort,
536 pub production: bool,
539 pub production_override: Option<bool>,
542 pub allow_remote_extends: bool,
544 pub changed_since: Option<&'a str>,
546 pub diff_index: Option<&'a DiffIndex>,
548 pub use_shared_diff_index: bool,
551 pub workspace: Option<&'a [String]>,
553 pub changed_workspaces: Option<&'a str>,
555 pub scope: Option<PathBuf>,
560 pub baseline: Option<&'a Path>,
562 pub save_baseline: Option<&'a Path>,
564 pub baseline_mode: crate::baseline::HealthBaselineMode,
569 pub baseline_mode_explicit: bool,
575 pub complexity: bool,
577 pub file_scores: bool,
579 pub coverage_gaps: bool,
581 pub config_activates_coverage_gaps: bool,
584 pub shallow_directories: bool,
586 pub hotspots: bool,
588 pub ownership: bool,
590 pub ownership_emails: Option<EmailMode>,
592 pub targets: bool,
594 pub css: bool,
596 pub css_deep: bool,
598 pub force_full: bool,
601 pub score_only_output: bool,
604 pub enforce_coverage_gap_gate: bool,
606 pub effort: Option<EffortEstimate>,
608 pub score: bool,
610 pub gates: HealthGateOptions,
612 pub since: Option<&'a str>,
614 pub min_commits: Option<u32>,
616 pub explain: bool,
618 pub summary: bool,
620 pub save_snapshot: Option<PathBuf>,
622 pub trend: bool,
624 pub coverage_inputs: HealthCoverageInputs<'a>,
626 pub performance: bool,
628 pub runtime_coverage: Option<RuntimeCoverageOptions>,
630 pub churn_file: Option<&'a Path>,
632 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
634 pub group_by: Option<GroupByMode>,
636 pub group_filter: Option<&'a [String]>,
639 pub trend_from: Option<&'a Path>,
642}
643
644#[must_use]
646fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
647 let score = options.score
648 || options.score_gate
649 || options.trend
650 || matches!(options.output, OutputFormat::Badge);
651 let any_section = score || requests_a_section(options);
652 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
653 let force_full = options.snapshot_requested || effective_score;
654
655 DerivedHealthSections {
656 any_section,
657 complexity: if any_section {
658 options.complexity
659 } else {
660 true
661 },
662 file_scores: if any_section {
663 options.file_scores
664 } else {
665 true
666 } || force_full,
667 coverage_gaps: if any_section {
668 options.coverage_gaps
669 } else {
670 false
671 },
672 shallow_directories: options.shallow_directories,
673 hotspots: if any_section { options.hotspots } else { true }
674 || options.snapshot_requested
675 || options.trend,
676 targets: if any_section { options.targets } else { true },
677 css: options.css,
678 score: effective_score,
679 force_full,
680 score_only_output: is_health_score_only_output(options, score),
681 }
682}
683
684fn requests_a_section(options: &HealthSectionOptions) -> bool {
686 options.complexity
687 || options.file_scores
688 || options.coverage_gaps
689 || options.shallow_directories
690 || options.hotspots
691 || options.targets
692}
693
694#[must_use]
696pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
697 let targets = input.targets || input.effort.is_some();
698 let sections = derive_health_sections(&HealthSectionOptions {
699 output: input.output,
700 complexity: input.complexity,
701 file_scores: input.file_scores,
702 coverage_gaps: input.coverage_gaps,
703 shallow_directories: input.shallow_directories,
704 hotspots: input.hotspots,
705 targets,
706 css: input.css,
707 score: input.score,
708 score_gate: input.gates.min_score.is_some(),
709 snapshot_requested: input.snapshot_requested,
710 trend: input.trend,
711 });
712
713 HealthRunOptions {
714 thresholds: input.thresholds,
715 top: input.top,
716 sort: input.sort,
717 sections,
718 ownership: input.ownership && sections.hotspots,
719 ownership_emails: input.ownership_emails,
720 effort: input.effort,
721 gates: input.gates,
722 since: input.since,
723 min_commits: input.min_commits,
724 coverage_inputs: input.coverage_inputs,
725 runtime_coverage: input.runtime_coverage,
726 }
727}
728
729fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
730 score
731 && !options.complexity
732 && !options.file_scores
733 && !options.coverage_gaps
734 && !options.shallow_directories
735 && !options.hotspots
736 && !options.targets
737 && !options.trend
738}
739
740#[derive(Debug, Clone)]
742pub struct RuntimeCoverageOptions {
743 pub path: PathBuf,
745 pub min_invocations_hot: u64,
747 pub min_observation_volume: Option<u32>,
752 pub low_traffic_threshold: Option<f64>,
756 pub license_jwt: String,
758 pub watermark: Option<RuntimeCoverageWatermark>,
760}
761
762pub struct HealthSharedParseData {
764 pub files: Vec<fallow_types::discover::DiscoveredFile>,
766 pub modules: Vec<fallow_types::extract::ModuleInfo>,
768 pub dead_code_results: Option<AnalysisResults>,
770 pub workspaces: Vec<WorkspaceInfo>,
772 pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 fn health_run_input() -> HealthRunOptionsInput<'static> {
781 HealthRunOptionsInput {
782 output: OutputFormat::Json,
783 thresholds: HealthThresholdOverrides::default(),
784 top: None,
785 sort: HealthSort::Cyclomatic,
786 complexity: false,
787 file_scores: false,
788 coverage_gaps: false,
789 shallow_directories: false,
790 hotspots: false,
791 ownership: false,
792 ownership_emails: None,
793 targets: false,
794 css: false,
795 effort: None,
796 score: false,
797 gates: HealthGateOptions::default(),
798 snapshot_requested: false,
799 trend: false,
800 since: None,
801 min_commits: None,
802 coverage_inputs: HealthCoverageInputs::default(),
803 runtime_coverage: None,
804 }
805 }
806
807 #[test]
808 fn health_execution_options_own_shared_runner_scope() {
809 let root = Path::new("/project");
810 let config_path = None;
811 let workspace = vec!["packages/app".to_string()];
812 let diff = DiffIndex::from_unified_diff(
813 "diff --git a/src/a.ts b/src/a.ts\n\
814 --- a/src/a.ts\n\
815 +++ b/src/a.ts\n\
816 @@ -0,0 +1,1 @@\n\
817 +new line\n",
818 );
819 let runtime_coverage = RuntimeCoverageOptions {
820 path: PathBuf::from("coverage/v8"),
821 min_invocations_hot: 10,
822 min_observation_volume: Some(500),
823 low_traffic_threshold: Some(0.01),
824 license_jwt: "test.jwt".to_string(),
825 watermark: None,
826 };
827
828 let options = HealthExecutionOptions {
829 root,
830 config_path: &config_path,
831 output: OutputFormat::Json,
832 no_cache: true,
833 threads: 2,
834 quiet: true,
835 complexity_breakdown: true,
836 thresholds: HealthThresholdOverrides::default(),
837 top: Some(5),
838 sort: HealthSort::Cognitive,
839 production: true,
840 production_override: Some(true),
841 allow_remote_extends: false,
842 changed_since: Some("HEAD~1"),
843 diff_index: Some(&diff),
844 use_shared_diff_index: false,
845 workspace: Some(&workspace),
846 changed_workspaces: None,
847 scope: None,
848 baseline: Some(Path::new(".fallow/health-baseline.json")),
849 save_baseline: None,
850 baseline_mode: crate::baseline::HealthBaselineMode::Count,
851 baseline_mode_explicit: false,
852 complexity: true,
853 file_scores: true,
854 coverage_gaps: false,
855 shallow_directories: false,
856 config_activates_coverage_gaps: false,
857 hotspots: true,
858 ownership: false,
859 ownership_emails: None,
860 targets: true,
861 css: false,
862 css_deep: false,
863 force_full: true,
864 score_only_output: false,
865 enforce_coverage_gap_gate: true,
866 effort: Some(EffortEstimate::Low),
867 score: true,
868 gates: HealthGateOptions {
869 min_score: Some(80.0),
870 min_severity: None,
871 report_only: false,
872 fail_on_stale_baseline: false,
873 fail_on_parse_error: false,
874 fail_on_issues: false,
875 },
876 since: Some("30d"),
877 min_commits: Some(2),
878 explain: true,
879 summary: false,
880 save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
881 trend: true,
882 coverage_inputs: HealthCoverageInputs::default(),
883 performance: true,
884 runtime_coverage: Some(runtime_coverage),
885 churn_file: Some(Path::new("churn.json")),
886 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
887 group_by: Some(GroupByMode::Directory),
888 group_filter: None,
889 trend_from: None,
890 };
891
892 assert_eq!(options.root, root);
893 assert!(
894 options
895 .diff_index
896 .is_some_and(|index| index.line_is_added("src/a.ts", 1))
897 );
898 assert_eq!(options.workspace, Some(workspace.as_slice()));
899 assert!(options.runtime_coverage.is_some());
900 assert_eq!(options.group_by, Some(GroupByMode::Directory));
901 assert_eq!(
902 options.save_snapshot.as_deref(),
903 Some(Path::new(".fallow/snapshots/health.json"))
904 );
905 }
906
907 #[test]
908 fn health_run_options_default_sections_match_health_defaults() {
909 let run = derive_health_run_options(health_run_input());
910
911 assert!(run.sections.complexity);
912 assert!(run.sections.file_scores);
913 assert!(run.sections.hotspots);
914 assert!(run.sections.targets);
915 assert!(run.sections.score);
916 assert!(!run.ownership);
917 }
918
919 #[test]
920 fn health_run_options_effort_requests_targets() {
921 let mut input = health_run_input();
922 input.effort = Some(EffortEstimate::Low);
923
924 let run = derive_health_run_options(input);
925
926 assert!(run.sections.targets);
927 assert_eq!(run.effort, Some(EffortEstimate::Low));
928 }
929
930 struct HealthExecutionOptionsFixture {
931 config_path: Option<PathBuf>,
932 }
933
934 impl HealthExecutionOptionsFixture {
935 const fn new() -> Self {
936 Self { config_path: None }
937 }
938
939 fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
940 HealthExecutionOptions {
941 root,
942 config_path: &self.config_path,
943 output: OutputFormat::Human,
944 no_cache: true,
945 threads: 1,
946 quiet: true,
947 complexity_breakdown: false,
948 thresholds: HealthThresholdOverrides::default(),
949 top: None,
950 sort: HealthSort::Cyclomatic,
951 production: false,
952 production_override: None,
953 allow_remote_extends: false,
954 changed_since: None,
955 diff_index: None,
956 use_shared_diff_index: false,
957 workspace: None,
958 changed_workspaces: None,
959 scope: None,
960 baseline: None,
961 save_baseline: None,
962 baseline_mode: crate::baseline::HealthBaselineMode::Count,
963 baseline_mode_explicit: false,
964 complexity: true,
965 file_scores: false,
966 coverage_gaps: false,
967 shallow_directories: false,
968 config_activates_coverage_gaps: false,
969 hotspots: false,
970 ownership: false,
971 ownership_emails: None,
972 targets: false,
973 css: false,
974 css_deep: false,
975 force_full: false,
976 score_only_output: false,
977 enforce_coverage_gap_gate: true,
978 effort: None,
979 score: false,
980 gates: HealthGateOptions::default(),
981 since: None,
982 min_commits: None,
983 explain: false,
984 summary: false,
985 save_snapshot: None,
986 trend: false,
987 coverage_inputs: HealthCoverageInputs::default(),
988 performance: false,
989 runtime_coverage: None,
990 churn_file: None,
991 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
992 group_by: None,
993 group_filter: None,
994 trend_from: None,
995 }
996 }
997 }
998
999 #[test]
1006 fn a_churn_file_that_fails_the_re_read_records_the_skip() {
1007 let project = tempfile::tempdir().expect("temp dir");
1008 let root = project.path();
1009 let churn_file = root.join("churn.json");
1010 std::fs::write(&churn_file, "{ not json").expect("churn file");
1011 let fixture = HealthExecutionOptionsFixture::new();
1012 let mut options = fixture.options(root);
1013 options.churn_file = Some(&churn_file);
1014
1015 assert!(
1016 hotspots::fetch_churn_data(&options, &root.join(".fallow")).is_none(),
1017 "an unreadable churn file yields no churn"
1018 );
1019
1020 let recorded = fallow_config::health_stage_workspace_diagnostics(root);
1021 let skip = recorded
1022 .iter()
1023 .find(|entry| entry.kind.id() == "hotspots-skipped")
1024 .expect("the skip is recorded");
1025 assert_eq!(
1026 skip.kind,
1027 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
1028 cause: "churn-file-unreadable".to_owned(),
1029 }
1030 );
1031 assert!(
1032 skip.message.contains("churn.json"),
1033 "the remedy names the file: {}",
1034 skip.message
1035 );
1036 }
1037
1038 #[test]
1039 fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
1040 let project = tempfile::tempdir().expect("temp dir");
1041 let fixture = HealthExecutionOptionsFixture::new();
1042 let options = fixture.options(project.path());
1043 let config = crate::project_config::default_project_config(project.path()).config;
1044
1045 assert!(should_precompute_dead_code_analysis(&options, &config));
1046 }
1047
1048 #[test]
1049 fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
1050 let project = tempfile::tempdir().expect("temp dir");
1051 let fixture = HealthExecutionOptionsFixture::new();
1052 let mut options = fixture.options(project.path());
1053 options.thresholds.max_crap = Some(0.0);
1054 let config = crate::project_config::default_project_config(project.path()).config;
1055
1056 assert!(!should_precompute_dead_code_analysis(&options, &config));
1057 }
1058
1059 #[test]
1060 fn standalone_health_precomputes_dead_code_for_target_sections() {
1061 let project = tempfile::tempdir().expect("temp dir");
1062 let fixture = HealthExecutionOptionsFixture::new();
1063 let mut options = fixture.options(project.path());
1064 options.thresholds.max_crap = Some(0.0);
1065 options.targets = true;
1066 let config = crate::project_config::default_project_config(project.path()).config;
1067
1068 assert!(should_precompute_dead_code_analysis(&options, &config));
1069 }
1070
1071 #[test]
1072 fn health_run_options_ownership_requires_hotspots() {
1073 let mut input = health_run_input();
1074 input.complexity = true;
1075 input.ownership = true;
1076
1077 let run = derive_health_run_options(input);
1078
1079 assert!(!run.sections.hotspots);
1080 assert!(!run.ownership);
1081
1082 let mut input = health_run_input();
1083 input.ownership = true;
1084 input.hotspots = true;
1085
1086 let run = derive_health_run_options(input);
1087
1088 assert!(run.sections.hotspots);
1089 assert!(run.ownership);
1090 }
1091
1092 #[test]
1093 fn health_run_options_score_gate_forces_score() {
1094 let mut input = health_run_input();
1095 input.gates.min_score = Some(90.0);
1096
1097 let run = derive_health_run_options(input);
1098
1099 assert!(run.sections.score);
1100 assert_eq!(run.gates.min_score, Some(90.0));
1101 }
1102
1103 #[test]
1104 fn coverage_root_accepts_posix_absolute() {
1105 assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
1106 assert!(
1107 validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
1108 );
1109 }
1110
1111 #[test]
1112 fn coverage_root_rejects_relative() {
1113 assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
1114 assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
1115 assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
1116 }
1117
1118 #[test]
1119 fn coverage_root_accepts_none() {
1120 assert!(validate_coverage_root_absolute(None).is_ok());
1121 }
1122
1123 #[test]
1124 fn coverage_root_accepts_windows_absolute_on_all_hosts() {
1125 assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
1126 }
1127}