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 dependency_classes;
56mod large_functions;
57mod output_build;
58pub mod ownership;
59mod package_json;
60mod pipeline;
61mod react_hooks;
62mod result;
63mod runner;
64mod runtime_filter;
65mod runtime_sections;
66mod scope;
67pub mod scoring;
70mod shallow_directories;
71pub mod styling_score;
72mod subset_filter;
73mod tailwind_theme;
74mod targets;
75mod test_reach;
76mod threshold_overrides;
77mod timings;
78mod vital_data;
79mod vital_signs_scope;
80
81pub use crate::results::HealthAnalysisResult;
82pub use churn_file::validate_health_churn_file;
83pub use css_analytics::StylingAnalysisArtifacts;
84use derived_sections::{
85 HealthDerivedSectionInput, HealthDerivedSections, prepare_health_derived_sections,
86};
87use execute::HealthOptions;
88pub use execute::{execute_health_inner, execute_health_inner_with_baseline};
89use file_scores::{
90 FileScoresAndChurnInput, compute_file_scores_and_churn, health_file_scores_slice,
91 print_slow_churn_note,
92};
93use finding_sort::sort_findings;
94pub use health_error::HealthError;
95pub use hotspots::{
96 TargetChurnEvidence, TargetChurnOptions, TargetChurnOutcome, analyze_target_churn,
97};
98pub use pipeline::{HealthPipelineInputs, HealthScopeInputs};
99pub use runner::{
100 UngroupedHealthSession, run_ungrouped_health_with_session,
101 run_ungrouped_health_with_session_artifacts,
102};
103pub use test_reach::TestReachGraph;
104use vital_data::{HealthVitalData, HealthVitalDataInput, prepare_health_vital_data};
105use vital_signs_scope::{
106 VitalSignsAndCountsInput, apply_duplication_metrics, compute_vital_signs_and_counts,
107};
108
109pub(crate) fn build_styling_analysis_artifacts(
110 files: &[crate::discover::DiscoveredFile],
111 modules: &[crate::source::ModuleInfo],
112 config: &fallow_config::ResolvedConfig,
113) -> StylingAnalysisArtifacts {
114 css_analytics::build_styling_analysis_artifacts(files, modules, config)
115}
116
117#[must_use]
119pub fn shared_parse_data_from_artifacts(
120 results: &AnalysisResults,
121 graph: Option<RetainedModuleGraph>,
122 modules: Option<Vec<crate::source::ModuleInfo>>,
123 files: Option<Vec<crate::discover::DiscoveredFile>>,
124 workspaces: Vec<WorkspaceInfo>,
125 script_used_packages: impl IntoIterator<Item = String>,
126) -> Option<HealthSharedParseData> {
127 let (Some(modules), Some(files)) = (modules, files) else {
128 return None;
129 };
130 let script_used_packages: FxHashSet<String> = script_used_packages.into_iter().collect();
131 let mut results = results.clone();
135 results.restore_cascade_findings();
136 let analysis_output = graph.map(|graph| DeadCodeAnalysisArtifacts {
137 results: results.clone(),
138 timings: None,
139 graph: Some(graph),
140 modules: None,
141 files: None,
142 script_used_packages: script_used_packages.clone(),
143 trace_provenance: crate::trace::TraceProvenance::default(),
144 file_hashes: FxHashMap::default(),
145 });
146 Some(HealthSharedParseData {
147 files,
148 modules,
149 dead_code_results: Some(results),
150 workspaces,
151 analysis_output,
152 })
153}
154
155#[must_use]
161pub fn should_precompute_dead_code_analysis(
162 options: &HealthExecutionOptions<'_>,
163 config: &fallow_config::ResolvedConfig,
164) -> bool {
165 let max_crap = options
166 .thresholds
167 .max_crap
168 .unwrap_or(config.health.max_crap);
169 options.file_scores
170 || options.coverage_gaps
171 || options.shallow_directories
172 || options.config_activates_coverage_gaps
173 || options.hotspots
174 || options.targets
175 || options.force_full
176 || max_crap > 0.0
177 || options.runtime_coverage.is_some()
178}
179
180pub trait HealthGroupResolver {
186 fn mode_label(&self) -> &'static str;
188 fn group_of<'a>(&'a self, rel_path: &'a Path) -> PathGroup<'a>;
190}
191
192#[derive(Debug, Clone, Copy)]
194pub struct PathGroup<'a> {
195 pub key: &'a str,
197 pub section_owners: Option<&'a [String]>,
200}
201
202#[derive(Debug, Clone, Copy)]
205#[expect(
206 clippy::empty_enums,
207 reason = "NoGroupResolver must be uninhabited so that no code can construct it"
208)]
209pub enum NoGroupResolver {}
210
211#[expect(
212 clippy::uninhabited_references,
213 reason = "NoGroupResolver is uninhabited; these methods are unreachable and exist only to satisfy the trait bound for the group-less programmatic path"
214)]
215impl HealthGroupResolver for NoGroupResolver {
216 fn mode_label(&self) -> &'static str {
217 match *self {}
218 }
219 fn group_of<'a>(&'a self, _rel_path: &'a Path) -> PathGroup<'a> {
220 match *self {}
221 }
222}
223
224pub type RuntimeCoverageAnalyzer<'a> = dyn Fn(&RuntimeCoverageOptions, RuntimeCoverageSeamInput<'_>) -> Result<RuntimeCoverageReport, u8>
236 + 'a;
237
238pub struct RuntimeCoverageSeamInput<'a> {
240 pub root: &'a Path,
242 pub modules: &'a [fallow_types::extract::ModuleInfo],
244 pub analysis_output: &'a DeadCodeAnalysisArtifacts,
247 pub istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
249 pub file_paths: &'a rustc_hash::FxHashMap<fallow_types::discover::FileId, &'a PathBuf>,
251 pub ignore_set: &'a globset::GlobSet,
253 pub changed_files: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
255 pub ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
257 pub top: Option<usize>,
259 pub codeowners_path: Option<&'a str>,
261 pub quiet: bool,
263 pub output: OutputFormat,
265 pub test_reach: Option<&'a TestReachGraph>,
268}
269
270pub struct HealthSeams<'a> {
274 pub runtime_coverage_analyzer: &'a RuntimeCoverageAnalyzer<'a>,
276 pub note_graph_structure: &'a dyn Fn(usize, usize),
280}
281
282#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub enum HealthSort {
285 Severity,
288 Cyclomatic,
290 Cognitive,
292 Lines,
294}
295
296#[derive(Debug, Clone, Copy, Default, PartialEq)]
298pub struct HealthThresholdOverrides {
299 pub max_cyclomatic: Option<u16>,
301 pub max_cognitive: Option<u16>,
303 pub max_crap: Option<f64>,
306 pub max_file_lines: Option<u32>,
309}
310
311#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
313pub struct HealthCoverageInputs<'a> {
314 pub coverage: Option<&'a Path>,
316 pub coverage_root: Option<&'a Path>,
319 pub coverage_relocated: bool,
325}
326
327pub fn validate_coverage_root_absolute(coverage_root: Option<&Path>) -> Result<(), String> {
334 if let Some(path) = coverage_root
335 && !is_absolute_path_any_platform(path)
336 {
337 return Err(format!(
338 "--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'.",
339 path.display()
340 ));
341 }
342 Ok(())
343}
344
345#[derive(Debug, Clone, Copy, Default, PartialEq)]
347pub struct HealthGateOptions {
348 pub min_score: Option<f64>,
350 pub min_severity: Option<FindingSeverity>,
352 pub report_only: bool,
354 pub fail_on_stale_baseline: bool,
356 pub fail_on_parse_error: bool,
360 pub fail_on_issues: bool,
364}
365
366#[derive(Debug, Clone)]
368pub struct HealthSectionOptions {
369 output: OutputFormat,
370 complexity: bool,
371 file_scores: bool,
372 coverage_gaps: bool,
373 shallow_directories: bool,
374 hotspots: bool,
375 targets: bool,
376 css: bool,
377 score: bool,
378 score_gate: bool,
379 snapshot_requested: bool,
380 trend: bool,
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385pub struct DerivedHealthSections {
386 pub any_section: bool,
389 pub complexity: bool,
391 pub file_scores: bool,
393 pub coverage_gaps: bool,
395 pub shallow_directories: bool,
397 pub hotspots: bool,
399 pub targets: bool,
401 pub css: bool,
403 pub score: bool,
405 pub force_full: bool,
408 pub score_only_output: bool,
411}
412
413impl DerivedHealthSections {
414 pub const NONE: Self = Self {
416 any_section: false,
417 complexity: false,
418 file_scores: false,
419 coverage_gaps: false,
420 shallow_directories: false,
421 hotspots: false,
422 targets: false,
423 css: false,
424 score: false,
425 force_full: false,
426 score_only_output: false,
427 };
428}
429
430#[derive(Debug, Clone)]
433pub struct HealthRunOptionsInput<'a> {
434 pub output: OutputFormat,
436 pub thresholds: HealthThresholdOverrides,
438 pub top: Option<usize>,
440 pub sort: HealthSort,
442 pub complexity: bool,
444 pub file_scores: bool,
446 pub coverage_gaps: bool,
448 pub shallow_directories: bool,
450 pub hotspots: bool,
452 pub ownership: bool,
454 pub ownership_emails: Option<EmailMode>,
456 pub targets: bool,
458 pub css: bool,
460 pub effort: Option<EffortEstimate>,
462 pub score: bool,
464 pub gates: HealthGateOptions,
466 pub snapshot_requested: bool,
468 pub trend: bool,
470 pub since: Option<&'a str>,
472 pub min_commits: Option<u32>,
474 pub coverage_inputs: HealthCoverageInputs<'a>,
476 pub runtime_coverage: Option<RuntimeCoverageOptions>,
478}
479
480#[derive(Debug, Clone)]
482pub struct HealthRunOptions<'a> {
483 pub thresholds: HealthThresholdOverrides,
485 pub top: Option<usize>,
487 pub sort: HealthSort,
489 pub sections: DerivedHealthSections,
491 pub ownership: bool,
493 pub ownership_emails: Option<EmailMode>,
495 pub effort: Option<EffortEstimate>,
497 pub gates: HealthGateOptions,
499 pub since: Option<&'a str>,
501 pub min_commits: Option<u32>,
503 pub coverage_inputs: HealthCoverageInputs<'a>,
505 pub runtime_coverage: Option<RuntimeCoverageOptions>,
507}
508
509#[derive(Debug, Clone)]
513pub struct HealthExecutionOptions<'a> {
514 pub root: &'a Path,
516 pub config_path: &'a Option<PathBuf>,
518 pub output: OutputFormat,
520 pub no_cache: bool,
522 pub threads: usize,
524 pub quiet: bool,
526 pub complexity_breakdown: bool,
531 pub thresholds: HealthThresholdOverrides,
533 pub top: Option<usize>,
535 pub sort: HealthSort,
537 pub production: bool,
540 pub production_override: Option<bool>,
543 pub allow_remote_extends: bool,
545 pub changed_since: Option<&'a str>,
547 pub diff_index: Option<&'a DiffIndex>,
549 pub use_shared_diff_index: bool,
552 pub workspace: Option<&'a [String]>,
554 pub changed_workspaces: Option<&'a str>,
556 pub scope: Option<PathBuf>,
561 pub baseline: Option<&'a Path>,
563 pub save_baseline: Option<&'a Path>,
565 pub baseline_mode: crate::baseline::HealthBaselineMode,
570 pub baseline_mode_explicit: bool,
576 pub complexity: bool,
578 pub file_scores: bool,
580 pub coverage_gaps: bool,
582 pub config_activates_coverage_gaps: bool,
585 pub shallow_directories: bool,
587 pub hotspots: bool,
589 pub ownership: bool,
591 pub ownership_emails: Option<EmailMode>,
593 pub targets: bool,
595 pub css: bool,
597 pub css_deep: bool,
599 pub force_full: bool,
602 pub score_only_output: bool,
605 pub enforce_coverage_gap_gate: bool,
607 pub effort: Option<EffortEstimate>,
609 pub score: bool,
611 pub gates: HealthGateOptions,
613 pub since: Option<&'a str>,
615 pub min_commits: Option<u32>,
617 pub explain: bool,
619 pub summary: bool,
621 pub save_snapshot: Option<PathBuf>,
623 pub trend: bool,
625 pub coverage_inputs: HealthCoverageInputs<'a>,
627 pub performance: bool,
629 pub runtime_coverage: Option<RuntimeCoverageOptions>,
631 pub churn_file: Option<&'a Path>,
633 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
635 pub group_by: Option<GroupByMode>,
637 pub group_filter: Option<&'a [String]>,
640 pub trend_from: Option<&'a Path>,
643}
644
645#[must_use]
647fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
648 let score = options.score
649 || options.score_gate
650 || options.trend
651 || matches!(options.output, OutputFormat::Badge);
652 let any_section = score || requests_a_section(options);
653 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
654 let force_full = options.snapshot_requested || effective_score;
655
656 DerivedHealthSections {
657 any_section,
658 complexity: if any_section {
659 options.complexity
660 } else {
661 true
662 },
663 file_scores: if any_section {
664 options.file_scores
665 } else {
666 true
667 } || force_full,
668 coverage_gaps: if any_section {
669 options.coverage_gaps
670 } else {
671 false
672 },
673 shallow_directories: options.shallow_directories,
674 hotspots: if any_section { options.hotspots } else { true }
675 || options.snapshot_requested
676 || options.trend,
677 targets: if any_section { options.targets } else { true },
678 css: options.css,
679 score: effective_score,
680 force_full,
681 score_only_output: is_health_score_only_output(options, score),
682 }
683}
684
685fn requests_a_section(options: &HealthSectionOptions) -> bool {
687 options.complexity
688 || options.file_scores
689 || options.coverage_gaps
690 || options.shallow_directories
691 || options.hotspots
692 || options.targets
693}
694
695#[must_use]
697pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
698 let targets = input.targets || input.effort.is_some();
699 let sections = derive_health_sections(&HealthSectionOptions {
700 output: input.output,
701 complexity: input.complexity,
702 file_scores: input.file_scores,
703 coverage_gaps: input.coverage_gaps,
704 shallow_directories: input.shallow_directories,
705 hotspots: input.hotspots,
706 targets,
707 css: input.css,
708 score: input.score,
709 score_gate: input.gates.min_score.is_some(),
710 snapshot_requested: input.snapshot_requested,
711 trend: input.trend,
712 });
713
714 HealthRunOptions {
715 thresholds: input.thresholds,
716 top: input.top,
717 sort: input.sort,
718 sections,
719 ownership: input.ownership && sections.hotspots,
720 ownership_emails: input.ownership_emails,
721 effort: input.effort,
722 gates: input.gates,
723 since: input.since,
724 min_commits: input.min_commits,
725 coverage_inputs: input.coverage_inputs,
726 runtime_coverage: input.runtime_coverage,
727 }
728}
729
730fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
731 score
732 && !options.complexity
733 && !options.file_scores
734 && !options.coverage_gaps
735 && !options.shallow_directories
736 && !options.hotspots
737 && !options.targets
738 && !options.trend
739}
740
741#[derive(Debug, Clone)]
743pub struct RuntimeCoverageOptions {
744 pub path: PathBuf,
746 pub min_invocations_hot: u64,
748 pub min_observation_volume: Option<u32>,
753 pub low_traffic_threshold: Option<f64>,
757 pub license_jwt: String,
759 pub watermark: Option<RuntimeCoverageWatermark>,
761}
762
763pub struct HealthSharedParseData {
765 pub files: Vec<fallow_types::discover::DiscoveredFile>,
767 pub modules: Vec<fallow_types::extract::ModuleInfo>,
769 pub dead_code_results: Option<AnalysisResults>,
771 pub workspaces: Vec<WorkspaceInfo>,
773 pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
775}
776
777#[cfg(test)]
778mod tests {
779 use super::*;
780
781 fn health_run_input() -> HealthRunOptionsInput<'static> {
782 HealthRunOptionsInput {
783 output: OutputFormat::Json,
784 thresholds: HealthThresholdOverrides::default(),
785 top: None,
786 sort: HealthSort::Cyclomatic,
787 complexity: false,
788 file_scores: false,
789 coverage_gaps: false,
790 shallow_directories: false,
791 hotspots: false,
792 ownership: false,
793 ownership_emails: None,
794 targets: false,
795 css: false,
796 effort: None,
797 score: false,
798 gates: HealthGateOptions::default(),
799 snapshot_requested: false,
800 trend: false,
801 since: None,
802 min_commits: None,
803 coverage_inputs: HealthCoverageInputs::default(),
804 runtime_coverage: None,
805 }
806 }
807
808 #[test]
809 fn health_execution_options_own_shared_runner_scope() {
810 let root = Path::new("/project");
811 let config_path = None;
812 let workspace = vec!["packages/app".to_string()];
813 let diff = DiffIndex::from_unified_diff(
814 "diff --git a/src/a.ts b/src/a.ts\n\
815 --- a/src/a.ts\n\
816 +++ b/src/a.ts\n\
817 @@ -0,0 +1,1 @@\n\
818 +new line\n",
819 );
820 let runtime_coverage = RuntimeCoverageOptions {
821 path: PathBuf::from("coverage/v8"),
822 min_invocations_hot: 10,
823 min_observation_volume: Some(500),
824 low_traffic_threshold: Some(0.01),
825 license_jwt: "test.jwt".to_string(),
826 watermark: None,
827 };
828
829 let options = HealthExecutionOptions {
830 root,
831 config_path: &config_path,
832 output: OutputFormat::Json,
833 no_cache: true,
834 threads: 2,
835 quiet: true,
836 complexity_breakdown: true,
837 thresholds: HealthThresholdOverrides::default(),
838 top: Some(5),
839 sort: HealthSort::Cognitive,
840 production: true,
841 production_override: Some(true),
842 allow_remote_extends: false,
843 changed_since: Some("HEAD~1"),
844 diff_index: Some(&diff),
845 use_shared_diff_index: false,
846 workspace: Some(&workspace),
847 changed_workspaces: None,
848 scope: None,
849 baseline: Some(Path::new(".fallow/health-baseline.json")),
850 save_baseline: None,
851 baseline_mode: crate::baseline::HealthBaselineMode::Count,
852 baseline_mode_explicit: false,
853 complexity: true,
854 file_scores: true,
855 coverage_gaps: false,
856 shallow_directories: false,
857 config_activates_coverage_gaps: false,
858 hotspots: true,
859 ownership: false,
860 ownership_emails: None,
861 targets: true,
862 css: false,
863 css_deep: false,
864 force_full: true,
865 score_only_output: false,
866 enforce_coverage_gap_gate: true,
867 effort: Some(EffortEstimate::Low),
868 score: true,
869 gates: HealthGateOptions {
870 min_score: Some(80.0),
871 min_severity: None,
872 report_only: false,
873 fail_on_stale_baseline: false,
874 fail_on_parse_error: false,
875 fail_on_issues: false,
876 },
877 since: Some("30d"),
878 min_commits: Some(2),
879 explain: true,
880 summary: false,
881 save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
882 trend: true,
883 coverage_inputs: HealthCoverageInputs::default(),
884 performance: true,
885 runtime_coverage: Some(runtime_coverage),
886 churn_file: Some(Path::new("churn.json")),
887 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
888 group_by: Some(GroupByMode::Directory),
889 group_filter: None,
890 trend_from: None,
891 };
892
893 assert_eq!(options.root, root);
894 assert!(
895 options
896 .diff_index
897 .is_some_and(|index| index.line_is_added("src/a.ts", 1))
898 );
899 assert_eq!(options.workspace, Some(workspace.as_slice()));
900 assert!(options.runtime_coverage.is_some());
901 assert_eq!(options.group_by, Some(GroupByMode::Directory));
902 assert_eq!(
903 options.save_snapshot.as_deref(),
904 Some(Path::new(".fallow/snapshots/health.json"))
905 );
906 }
907
908 #[test]
909 fn health_run_options_default_sections_match_health_defaults() {
910 let run = derive_health_run_options(health_run_input());
911
912 assert!(run.sections.complexity);
913 assert!(run.sections.file_scores);
914 assert!(run.sections.hotspots);
915 assert!(run.sections.targets);
916 assert!(run.sections.score);
917 assert!(!run.ownership);
918 }
919
920 #[test]
921 fn health_run_options_effort_requests_targets() {
922 let mut input = health_run_input();
923 input.effort = Some(EffortEstimate::Low);
924
925 let run = derive_health_run_options(input);
926
927 assert!(run.sections.targets);
928 assert_eq!(run.effort, Some(EffortEstimate::Low));
929 }
930
931 struct HealthExecutionOptionsFixture {
932 config_path: Option<PathBuf>,
933 }
934
935 impl HealthExecutionOptionsFixture {
936 const fn new() -> Self {
937 Self { config_path: None }
938 }
939
940 fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
941 HealthExecutionOptions {
942 root,
943 config_path: &self.config_path,
944 output: OutputFormat::Human,
945 no_cache: true,
946 threads: 1,
947 quiet: true,
948 complexity_breakdown: false,
949 thresholds: HealthThresholdOverrides::default(),
950 top: None,
951 sort: HealthSort::Cyclomatic,
952 production: false,
953 production_override: None,
954 allow_remote_extends: false,
955 changed_since: None,
956 diff_index: None,
957 use_shared_diff_index: false,
958 workspace: None,
959 changed_workspaces: None,
960 scope: None,
961 baseline: None,
962 save_baseline: None,
963 baseline_mode: crate::baseline::HealthBaselineMode::Count,
964 baseline_mode_explicit: false,
965 complexity: true,
966 file_scores: false,
967 coverage_gaps: false,
968 shallow_directories: false,
969 config_activates_coverage_gaps: false,
970 hotspots: false,
971 ownership: false,
972 ownership_emails: None,
973 targets: false,
974 css: false,
975 css_deep: false,
976 force_full: false,
977 score_only_output: false,
978 enforce_coverage_gap_gate: true,
979 effort: None,
980 score: false,
981 gates: HealthGateOptions::default(),
982 since: None,
983 min_commits: None,
984 explain: false,
985 summary: false,
986 save_snapshot: None,
987 trend: false,
988 coverage_inputs: HealthCoverageInputs::default(),
989 performance: false,
990 runtime_coverage: None,
991 churn_file: None,
992 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
993 group_by: None,
994 group_filter: None,
995 trend_from: None,
996 }
997 }
998 }
999
1000 #[test]
1007 fn a_churn_file_that_fails_the_re_read_records_the_skip() {
1008 let project = tempfile::tempdir().expect("temp dir");
1009 let root = project.path();
1010 let churn_file = root.join("churn.json");
1011 std::fs::write(&churn_file, "{ not json").expect("churn file");
1012 let fixture = HealthExecutionOptionsFixture::new();
1013 let mut options = fixture.options(root);
1014 options.churn_file = Some(&churn_file);
1015
1016 assert!(
1017 hotspots::fetch_churn_data(&options, &root.join(".fallow")).is_none(),
1018 "an unreadable churn file yields no churn"
1019 );
1020
1021 let recorded = fallow_config::health_stage_workspace_diagnostics(root);
1022 let skip = recorded
1023 .iter()
1024 .find(|entry| entry.kind.id() == "hotspots-skipped")
1025 .expect("the skip is recorded");
1026 assert_eq!(
1027 skip.kind,
1028 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
1029 cause: "churn-file-unreadable".to_owned(),
1030 }
1031 );
1032 assert!(
1033 skip.message.contains("churn.json"),
1034 "the remedy names the file: {}",
1035 skip.message
1036 );
1037 }
1038
1039 #[test]
1040 fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
1041 let project = tempfile::tempdir().expect("temp dir");
1042 let fixture = HealthExecutionOptionsFixture::new();
1043 let options = fixture.options(project.path());
1044 let config = crate::project_config::default_project_config(project.path()).config;
1045
1046 assert!(should_precompute_dead_code_analysis(&options, &config));
1047 }
1048
1049 #[test]
1050 fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
1051 let project = tempfile::tempdir().expect("temp dir");
1052 let fixture = HealthExecutionOptionsFixture::new();
1053 let mut options = fixture.options(project.path());
1054 options.thresholds.max_crap = Some(0.0);
1055 let config = crate::project_config::default_project_config(project.path()).config;
1056
1057 assert!(!should_precompute_dead_code_analysis(&options, &config));
1058 }
1059
1060 #[test]
1061 fn standalone_health_precomputes_dead_code_for_target_sections() {
1062 let project = tempfile::tempdir().expect("temp dir");
1063 let fixture = HealthExecutionOptionsFixture::new();
1064 let mut options = fixture.options(project.path());
1065 options.thresholds.max_crap = Some(0.0);
1066 options.targets = true;
1067 let config = crate::project_config::default_project_config(project.path()).config;
1068
1069 assert!(should_precompute_dead_code_analysis(&options, &config));
1070 }
1071
1072 #[test]
1073 fn health_run_options_ownership_requires_hotspots() {
1074 let mut input = health_run_input();
1075 input.complexity = true;
1076 input.ownership = true;
1077
1078 let run = derive_health_run_options(input);
1079
1080 assert!(!run.sections.hotspots);
1081 assert!(!run.ownership);
1082
1083 let mut input = health_run_input();
1084 input.ownership = true;
1085 input.hotspots = true;
1086
1087 let run = derive_health_run_options(input);
1088
1089 assert!(run.sections.hotspots);
1090 assert!(run.ownership);
1091 }
1092
1093 #[test]
1094 fn health_run_options_score_gate_forces_score() {
1095 let mut input = health_run_input();
1096 input.gates.min_score = Some(90.0);
1097
1098 let run = derive_health_run_options(input);
1099
1100 assert!(run.sections.score);
1101 assert_eq!(run.gates.min_score, Some(90.0));
1102 }
1103
1104 #[test]
1105 fn coverage_root_accepts_posix_absolute() {
1106 assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
1107 assert!(
1108 validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
1109 );
1110 }
1111
1112 #[test]
1113 fn coverage_root_rejects_relative() {
1114 assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
1115 assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
1116 assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
1117 }
1118
1119 #[test]
1120 fn coverage_root_accepts_none() {
1121 assert!(validate_coverage_root_absolute(None).is_ok());
1122 }
1123
1124 #[test]
1125 fn coverage_root_accepts_windows_absolute_on_all_hosts() {
1126 assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
1127 }
1128}