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 cyclomatic_policy;
37mod derived_sections;
38pub(crate) mod diagnostics;
39mod execute;
40mod file_lines;
41mod file_scores;
42mod filters;
43mod finding_sort;
44mod findings;
45mod findings_pipeline;
46mod framework_health;
47mod grouping;
48pub use grouping::validate_group_filter;
49mod health_error;
50mod hotspots;
51pub(crate) mod ignore;
52mod inline;
53pub use inline::{InlineComplexity, inline_complexity};
54mod large_functions;
55mod output_build;
56pub mod ownership;
57mod package_json;
58mod pipeline;
59mod react_hooks;
60mod result;
61mod runner;
62mod runtime_filter;
63mod runtime_sections;
64mod scope;
65pub mod scoring;
68pub mod styling_score;
69mod tailwind_theme;
70mod targets;
71mod test_reach;
72mod threshold_overrides;
73mod timings;
74mod vital_data;
75mod vital_signs_scope;
76
77pub use crate::results::HealthAnalysisResult;
78pub use churn_file::validate_health_churn_file;
79pub use css_analytics::StylingAnalysisArtifacts;
80use derived_sections::{
81 HealthDerivedSectionInput, HealthDerivedSections, prepare_health_derived_sections,
82};
83use execute::HealthOptions;
84pub use execute::execute_health_inner;
85use file_scores::{
86 FileScoresAndChurnInput, compute_file_scores_and_churn, health_file_scores_slice,
87 print_slow_churn_note,
88};
89use finding_sort::sort_findings;
90pub use health_error::HealthError;
91pub use hotspots::{
92 TargetChurnEvidence, TargetChurnOptions, TargetChurnOutcome, analyze_target_churn,
93};
94pub use pipeline::{HealthPipelineInputs, HealthScopeInputs};
95pub use runner::{
96 UngroupedHealthSession, run_ungrouped_health_with_session,
97 run_ungrouped_health_with_session_artifacts,
98};
99pub use test_reach::TestReachGraph;
100use vital_data::{HealthVitalData, HealthVitalDataInput, prepare_health_vital_data};
101use vital_signs_scope::{
102 SubsetFilter, VitalSignsAndCountsInput, apply_duplication_metrics,
103 compute_vital_signs_and_counts,
104};
105
106pub(crate) fn build_styling_analysis_artifacts(
107 files: &[crate::discover::DiscoveredFile],
108 modules: &[crate::source::ModuleInfo],
109 config: &fallow_config::ResolvedConfig,
110) -> StylingAnalysisArtifacts {
111 css_analytics::build_styling_analysis_artifacts(files, modules, config)
112}
113
114#[must_use]
116pub fn shared_parse_data_from_artifacts(
117 results: &AnalysisResults,
118 graph: Option<RetainedModuleGraph>,
119 modules: Option<Vec<crate::source::ModuleInfo>>,
120 files: Option<Vec<crate::discover::DiscoveredFile>>,
121 workspaces: Vec<WorkspaceInfo>,
122 script_used_packages: impl IntoIterator<Item = String>,
123) -> Option<HealthSharedParseData> {
124 let (Some(modules), Some(files)) = (modules, files) else {
125 return None;
126 };
127 let script_used_packages: FxHashSet<String> = script_used_packages.into_iter().collect();
128 let mut results = results.clone();
132 results.restore_cascade_findings();
133 let analysis_output = graph.map(|graph| DeadCodeAnalysisArtifacts {
134 results: results.clone(),
135 timings: None,
136 graph: Some(graph),
137 modules: None,
138 files: None,
139 script_used_packages: script_used_packages.clone(),
140 trace_provenance: crate::trace::TraceProvenance::default(),
141 file_hashes: FxHashMap::default(),
142 });
143 Some(HealthSharedParseData {
144 files,
145 modules,
146 dead_code_results: Some(results),
147 workspaces,
148 analysis_output,
149 })
150}
151
152#[must_use]
158pub fn should_precompute_dead_code_analysis(
159 options: &HealthExecutionOptions<'_>,
160 config: &fallow_config::ResolvedConfig,
161) -> bool {
162 let max_crap = options
163 .thresholds
164 .max_crap
165 .unwrap_or(config.health.max_crap);
166 options.file_scores
167 || options.coverage_gaps
168 || options.config_activates_coverage_gaps
169 || options.hotspots
170 || options.targets
171 || options.force_full
172 || max_crap > 0.0
173 || options.runtime_coverage.is_some()
174}
175
176pub trait HealthGroupResolver {
182 fn mode_label(&self) -> &'static str;
184 fn group_of<'a>(&'a self, rel_path: &'a Path) -> PathGroup<'a>;
186}
187
188#[derive(Debug, Clone, Copy)]
190pub struct PathGroup<'a> {
191 pub key: &'a str,
193 pub section_owners: Option<&'a [String]>,
196}
197
198#[derive(Debug, Clone, Copy)]
201#[expect(
202 clippy::empty_enums,
203 reason = "NoGroupResolver must be uninhabited so that no code can construct it"
204)]
205pub enum NoGroupResolver {}
206
207#[expect(
208 clippy::uninhabited_references,
209 reason = "NoGroupResolver is uninhabited; these methods are unreachable and exist only to satisfy the trait bound for the group-less programmatic path"
210)]
211impl HealthGroupResolver for NoGroupResolver {
212 fn mode_label(&self) -> &'static str {
213 match *self {}
214 }
215 fn group_of<'a>(&'a self, _rel_path: &'a Path) -> PathGroup<'a> {
216 match *self {}
217 }
218}
219
220pub type RuntimeCoverageAnalyzer<'a> = dyn Fn(&RuntimeCoverageOptions, RuntimeCoverageSeamInput<'_>) -> Result<RuntimeCoverageReport, u8>
232 + 'a;
233
234pub struct RuntimeCoverageSeamInput<'a> {
236 pub root: &'a Path,
238 pub modules: &'a [fallow_types::extract::ModuleInfo],
240 pub analysis_output: &'a DeadCodeAnalysisArtifacts,
243 pub istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
245 pub file_paths: &'a rustc_hash::FxHashMap<fallow_types::discover::FileId, &'a PathBuf>,
247 pub ignore_set: &'a globset::GlobSet,
249 pub changed_files: Option<&'a rustc_hash::FxHashSet<PathBuf>>,
251 pub ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
253 pub top: Option<usize>,
255 pub codeowners_path: Option<&'a str>,
257 pub quiet: bool,
259 pub output: OutputFormat,
261 pub test_reach: Option<&'a TestReachGraph>,
264}
265
266pub struct HealthSeams<'a> {
270 pub runtime_coverage_analyzer: &'a RuntimeCoverageAnalyzer<'a>,
272 pub note_graph_structure: &'a dyn Fn(usize, usize),
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum HealthSort {
281 Severity,
284 Cyclomatic,
286 Cognitive,
288 Lines,
290}
291
292#[derive(Debug, Clone, Copy, Default, PartialEq)]
294pub struct HealthThresholdOverrides {
295 pub max_cyclomatic: Option<u16>,
297 pub max_cognitive: Option<u16>,
299 pub max_crap: Option<f64>,
302 pub max_file_lines: Option<u32>,
305}
306
307#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
309pub struct HealthCoverageInputs<'a> {
310 pub coverage: Option<&'a Path>,
312 pub coverage_root: Option<&'a Path>,
315 pub coverage_relocated: bool,
321}
322
323pub fn validate_coverage_root_absolute(coverage_root: Option<&Path>) -> Result<(), String> {
330 if let Some(path) = coverage_root
331 && !is_absolute_path_any_platform(path)
332 {
333 return Err(format!(
334 "--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'.",
335 path.display()
336 ));
337 }
338 Ok(())
339}
340
341#[derive(Debug, Clone, Copy, Default, PartialEq)]
343pub struct HealthGateOptions {
344 pub min_score: Option<f64>,
346 pub min_severity: Option<FindingSeverity>,
348 pub report_only: bool,
350 pub fail_on_stale_baseline: bool,
352 pub fail_on_parse_error: bool,
356 pub fail_on_issues: bool,
360}
361
362#[derive(Debug, Clone)]
364pub struct HealthSectionOptions {
365 output: OutputFormat,
366 complexity: bool,
367 file_scores: bool,
368 coverage_gaps: bool,
369 hotspots: bool,
370 targets: bool,
371 css: bool,
372 score: bool,
373 score_gate: bool,
374 snapshot_requested: bool,
375 trend: bool,
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub struct DerivedHealthSections {
381 pub any_section: bool,
384 pub complexity: bool,
386 pub file_scores: bool,
388 pub coverage_gaps: bool,
390 pub hotspots: bool,
392 pub targets: bool,
394 pub css: bool,
396 pub score: bool,
398 pub force_full: bool,
401 pub score_only_output: bool,
404}
405
406#[derive(Debug, Clone)]
409pub struct HealthRunOptionsInput<'a> {
410 pub output: OutputFormat,
412 pub thresholds: HealthThresholdOverrides,
414 pub top: Option<usize>,
416 pub sort: HealthSort,
418 pub complexity: bool,
420 pub file_scores: bool,
422 pub coverage_gaps: bool,
424 pub hotspots: bool,
426 pub ownership: bool,
428 pub ownership_emails: Option<EmailMode>,
430 pub targets: bool,
432 pub css: bool,
434 pub effort: Option<EffortEstimate>,
436 pub score: bool,
438 pub gates: HealthGateOptions,
440 pub snapshot_requested: bool,
442 pub trend: bool,
444 pub since: Option<&'a str>,
446 pub min_commits: Option<u32>,
448 pub coverage_inputs: HealthCoverageInputs<'a>,
450 pub runtime_coverage: Option<RuntimeCoverageOptions>,
452}
453
454#[derive(Debug, Clone)]
456pub struct HealthRunOptions<'a> {
457 pub thresholds: HealthThresholdOverrides,
459 pub top: Option<usize>,
461 pub sort: HealthSort,
463 pub sections: DerivedHealthSections,
465 pub ownership: bool,
467 pub ownership_emails: Option<EmailMode>,
469 pub effort: Option<EffortEstimate>,
471 pub gates: HealthGateOptions,
473 pub since: Option<&'a str>,
475 pub min_commits: Option<u32>,
477 pub coverage_inputs: HealthCoverageInputs<'a>,
479 pub runtime_coverage: Option<RuntimeCoverageOptions>,
481}
482
483#[derive(Debug, Clone)]
487pub struct HealthExecutionOptions<'a> {
488 pub root: &'a Path,
490 pub config_path: &'a Option<PathBuf>,
492 pub output: OutputFormat,
494 pub no_cache: bool,
496 pub threads: usize,
498 pub quiet: bool,
500 pub complexity_breakdown: bool,
505 pub thresholds: HealthThresholdOverrides,
507 pub top: Option<usize>,
509 pub sort: HealthSort,
511 pub production: bool,
514 pub production_override: Option<bool>,
517 pub allow_remote_extends: bool,
519 pub changed_since: Option<&'a str>,
521 pub diff_index: Option<&'a DiffIndex>,
523 pub use_shared_diff_index: bool,
526 pub workspace: Option<&'a [String]>,
528 pub changed_workspaces: Option<&'a str>,
530 pub scope: Option<PathBuf>,
535 pub baseline: Option<&'a Path>,
537 pub save_baseline: Option<&'a Path>,
539 pub baseline_mode: crate::baseline::HealthBaselineMode,
544 pub baseline_mode_explicit: bool,
550 pub complexity: bool,
552 pub file_scores: bool,
554 pub coverage_gaps: bool,
556 pub config_activates_coverage_gaps: bool,
559 pub hotspots: bool,
561 pub ownership: bool,
563 pub ownership_emails: Option<EmailMode>,
565 pub targets: bool,
567 pub css: bool,
569 pub css_deep: bool,
571 pub force_full: bool,
574 pub score_only_output: bool,
577 pub enforce_coverage_gap_gate: bool,
579 pub effort: Option<EffortEstimate>,
581 pub score: bool,
583 pub gates: HealthGateOptions,
585 pub since: Option<&'a str>,
587 pub min_commits: Option<u32>,
589 pub explain: bool,
591 pub summary: bool,
593 pub save_snapshot: Option<PathBuf>,
595 pub trend: bool,
597 pub coverage_inputs: HealthCoverageInputs<'a>,
599 pub performance: bool,
601 pub runtime_coverage: Option<RuntimeCoverageOptions>,
603 pub churn_file: Option<&'a Path>,
605 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
607 pub group_by: Option<GroupByMode>,
609 pub group_filter: Option<&'a [String]>,
612 pub trend_from: Option<&'a Path>,
615}
616
617#[must_use]
619fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
620 let score = options.score
621 || options.score_gate
622 || options.trend
623 || matches!(options.output, OutputFormat::Badge);
624 let any_section = options.complexity
625 || options.file_scores
626 || options.coverage_gaps
627 || options.hotspots
628 || options.targets
629 || score;
630 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
631 let force_full = options.snapshot_requested || effective_score;
632
633 DerivedHealthSections {
634 any_section,
635 complexity: if any_section {
636 options.complexity
637 } else {
638 true
639 },
640 file_scores: if any_section {
641 options.file_scores
642 } else {
643 true
644 } || force_full,
645 coverage_gaps: if any_section {
646 options.coverage_gaps
647 } else {
648 false
649 },
650 hotspots: if any_section { options.hotspots } else { true }
651 || options.snapshot_requested
652 || options.trend,
653 targets: if any_section { options.targets } else { true },
654 css: options.css,
655 score: effective_score,
656 force_full,
657 score_only_output: is_health_score_only_output(options, score),
658 }
659}
660
661#[must_use]
663pub fn derive_health_run_options(input: HealthRunOptionsInput<'_>) -> HealthRunOptions<'_> {
664 let targets = input.targets || input.effort.is_some();
665 let sections = derive_health_sections(&HealthSectionOptions {
666 output: input.output,
667 complexity: input.complexity,
668 file_scores: input.file_scores,
669 coverage_gaps: input.coverage_gaps,
670 hotspots: input.hotspots,
671 targets,
672 css: input.css,
673 score: input.score,
674 score_gate: input.gates.min_score.is_some(),
675 snapshot_requested: input.snapshot_requested,
676 trend: input.trend,
677 });
678
679 HealthRunOptions {
680 thresholds: input.thresholds,
681 top: input.top,
682 sort: input.sort,
683 sections,
684 ownership: input.ownership && sections.hotspots,
685 ownership_emails: input.ownership_emails,
686 effort: input.effort,
687 gates: input.gates,
688 since: input.since,
689 min_commits: input.min_commits,
690 coverage_inputs: input.coverage_inputs,
691 runtime_coverage: input.runtime_coverage,
692 }
693}
694
695fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
696 score
697 && !options.complexity
698 && !options.file_scores
699 && !options.coverage_gaps
700 && !options.hotspots
701 && !options.targets
702 && !options.trend
703}
704
705#[derive(Debug, Clone)]
707pub struct RuntimeCoverageOptions {
708 pub path: PathBuf,
710 pub min_invocations_hot: u64,
712 pub min_observation_volume: Option<u32>,
717 pub low_traffic_threshold: Option<f64>,
721 pub license_jwt: String,
723 pub watermark: Option<RuntimeCoverageWatermark>,
725}
726
727pub struct HealthSharedParseData {
729 pub files: Vec<fallow_types::discover::DiscoveredFile>,
731 pub modules: Vec<fallow_types::extract::ModuleInfo>,
733 pub dead_code_results: Option<AnalysisResults>,
735 pub workspaces: Vec<WorkspaceInfo>,
737 pub analysis_output: Option<DeadCodeAnalysisArtifacts>,
739}
740
741#[cfg(test)]
742mod tests {
743 use super::*;
744
745 fn health_run_input() -> HealthRunOptionsInput<'static> {
746 HealthRunOptionsInput {
747 output: OutputFormat::Json,
748 thresholds: HealthThresholdOverrides::default(),
749 top: None,
750 sort: HealthSort::Cyclomatic,
751 complexity: false,
752 file_scores: false,
753 coverage_gaps: false,
754 hotspots: false,
755 ownership: false,
756 ownership_emails: None,
757 targets: false,
758 css: false,
759 effort: None,
760 score: false,
761 gates: HealthGateOptions::default(),
762 snapshot_requested: false,
763 trend: false,
764 since: None,
765 min_commits: None,
766 coverage_inputs: HealthCoverageInputs::default(),
767 runtime_coverage: None,
768 }
769 }
770
771 #[test]
772 fn health_execution_options_own_shared_runner_scope() {
773 let root = Path::new("/project");
774 let config_path = None;
775 let workspace = vec!["packages/app".to_string()];
776 let diff = DiffIndex::from_unified_diff(
777 "diff --git a/src/a.ts b/src/a.ts\n\
778 --- a/src/a.ts\n\
779 +++ b/src/a.ts\n\
780 @@ -0,0 +1,1 @@\n\
781 +new line\n",
782 );
783 let runtime_coverage = RuntimeCoverageOptions {
784 path: PathBuf::from("coverage/v8"),
785 min_invocations_hot: 10,
786 min_observation_volume: Some(500),
787 low_traffic_threshold: Some(0.01),
788 license_jwt: "test.jwt".to_string(),
789 watermark: None,
790 };
791
792 let options = HealthExecutionOptions {
793 root,
794 config_path: &config_path,
795 output: OutputFormat::Json,
796 no_cache: true,
797 threads: 2,
798 quiet: true,
799 complexity_breakdown: true,
800 thresholds: HealthThresholdOverrides::default(),
801 top: Some(5),
802 sort: HealthSort::Cognitive,
803 production: true,
804 production_override: Some(true),
805 allow_remote_extends: false,
806 changed_since: Some("HEAD~1"),
807 diff_index: Some(&diff),
808 use_shared_diff_index: false,
809 workspace: Some(&workspace),
810 changed_workspaces: None,
811 scope: None,
812 baseline: Some(Path::new(".fallow/health-baseline.json")),
813 save_baseline: None,
814 baseline_mode: crate::baseline::HealthBaselineMode::Count,
815 baseline_mode_explicit: false,
816 complexity: true,
817 file_scores: true,
818 coverage_gaps: false,
819 config_activates_coverage_gaps: false,
820 hotspots: true,
821 ownership: false,
822 ownership_emails: None,
823 targets: true,
824 css: false,
825 css_deep: false,
826 force_full: true,
827 score_only_output: false,
828 enforce_coverage_gap_gate: true,
829 effort: Some(EffortEstimate::Low),
830 score: true,
831 gates: HealthGateOptions {
832 min_score: Some(80.0),
833 min_severity: None,
834 report_only: false,
835 fail_on_stale_baseline: false,
836 fail_on_parse_error: false,
837 fail_on_issues: false,
838 },
839 since: Some("30d"),
840 min_commits: Some(2),
841 explain: true,
842 summary: false,
843 save_snapshot: Some(PathBuf::from(".fallow/snapshots/health.json")),
844 trend: true,
845 coverage_inputs: HealthCoverageInputs::default(),
846 performance: true,
847 runtime_coverage: Some(runtime_coverage),
848 churn_file: Some(Path::new("churn.json")),
849 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
850 group_by: Some(GroupByMode::Directory),
851 group_filter: None,
852 trend_from: None,
853 };
854
855 assert_eq!(options.root, root);
856 assert!(
857 options
858 .diff_index
859 .is_some_and(|index| index.line_is_added("src/a.ts", 1))
860 );
861 assert_eq!(options.workspace, Some(workspace.as_slice()));
862 assert!(options.runtime_coverage.is_some());
863 assert_eq!(options.group_by, Some(GroupByMode::Directory));
864 assert_eq!(
865 options.save_snapshot.as_deref(),
866 Some(Path::new(".fallow/snapshots/health.json"))
867 );
868 }
869
870 #[test]
871 fn health_run_options_default_sections_match_health_defaults() {
872 let run = derive_health_run_options(health_run_input());
873
874 assert!(run.sections.complexity);
875 assert!(run.sections.file_scores);
876 assert!(run.sections.hotspots);
877 assert!(run.sections.targets);
878 assert!(run.sections.score);
879 assert!(!run.ownership);
880 }
881
882 #[test]
883 fn health_run_options_effort_requests_targets() {
884 let mut input = health_run_input();
885 input.effort = Some(EffortEstimate::Low);
886
887 let run = derive_health_run_options(input);
888
889 assert!(run.sections.targets);
890 assert_eq!(run.effort, Some(EffortEstimate::Low));
891 }
892
893 struct HealthExecutionOptionsFixture {
894 config_path: Option<PathBuf>,
895 }
896
897 impl HealthExecutionOptionsFixture {
898 const fn new() -> Self {
899 Self { config_path: None }
900 }
901
902 fn options<'a>(&'a self, root: &'a Path) -> HealthExecutionOptions<'a> {
903 HealthExecutionOptions {
904 root,
905 config_path: &self.config_path,
906 output: OutputFormat::Human,
907 no_cache: true,
908 threads: 1,
909 quiet: true,
910 complexity_breakdown: false,
911 thresholds: HealthThresholdOverrides::default(),
912 top: None,
913 sort: HealthSort::Cyclomatic,
914 production: false,
915 production_override: None,
916 allow_remote_extends: false,
917 changed_since: None,
918 diff_index: None,
919 use_shared_diff_index: false,
920 workspace: None,
921 changed_workspaces: None,
922 scope: None,
923 baseline: None,
924 save_baseline: None,
925 baseline_mode: crate::baseline::HealthBaselineMode::Count,
926 baseline_mode_explicit: false,
927 complexity: true,
928 file_scores: false,
929 coverage_gaps: false,
930 config_activates_coverage_gaps: false,
931 hotspots: false,
932 ownership: false,
933 ownership_emails: None,
934 targets: false,
935 css: false,
936 css_deep: false,
937 force_full: false,
938 score_only_output: false,
939 enforce_coverage_gap_gate: true,
940 effort: None,
941 score: false,
942 gates: HealthGateOptions::default(),
943 since: None,
944 min_commits: None,
945 explain: false,
946 summary: false,
947 save_snapshot: None,
948 trend: false,
949 coverage_inputs: HealthCoverageInputs::default(),
950 performance: false,
951 runtime_coverage: None,
952 churn_file: None,
953 analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity::default(),
954 group_by: None,
955 group_filter: None,
956 trend_from: None,
957 }
958 }
959 }
960
961 #[test]
968 fn a_churn_file_that_fails_the_re_read_records_the_skip() {
969 let project = tempfile::tempdir().expect("temp dir");
970 let root = project.path();
971 let churn_file = root.join("churn.json");
972 std::fs::write(&churn_file, "{ not json").expect("churn file");
973 let fixture = HealthExecutionOptionsFixture::new();
974 let mut options = fixture.options(root);
975 options.churn_file = Some(&churn_file);
976
977 assert!(
978 hotspots::fetch_churn_data(&options, &root.join(".fallow")).is_none(),
979 "an unreadable churn file yields no churn"
980 );
981
982 let recorded = fallow_config::health_stage_workspace_diagnostics(root);
983 let skip = recorded
984 .iter()
985 .find(|entry| entry.kind.id() == "hotspots-skipped")
986 .expect("the skip is recorded");
987 assert_eq!(
988 skip.kind,
989 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
990 cause: "churn-file-unreadable".to_owned(),
991 }
992 );
993 assert!(
994 skip.message.contains("churn.json"),
995 "the remedy names the file: {}",
996 skip.message
997 );
998 }
999
1000 #[test]
1001 fn standalone_health_precomputes_dead_code_when_default_crap_can_use_graph() {
1002 let project = tempfile::tempdir().expect("temp dir");
1003 let fixture = HealthExecutionOptionsFixture::new();
1004 let options = fixture.options(project.path());
1005 let config = crate::project_config::default_project_config(project.path()).config;
1006
1007 assert!(should_precompute_dead_code_analysis(&options, &config));
1008 }
1009
1010 #[test]
1011 fn standalone_health_skips_precompute_when_no_section_needs_analysis_artifacts() {
1012 let project = tempfile::tempdir().expect("temp dir");
1013 let fixture = HealthExecutionOptionsFixture::new();
1014 let mut options = fixture.options(project.path());
1015 options.thresholds.max_crap = Some(0.0);
1016 let config = crate::project_config::default_project_config(project.path()).config;
1017
1018 assert!(!should_precompute_dead_code_analysis(&options, &config));
1019 }
1020
1021 #[test]
1022 fn standalone_health_precomputes_dead_code_for_target_sections() {
1023 let project = tempfile::tempdir().expect("temp dir");
1024 let fixture = HealthExecutionOptionsFixture::new();
1025 let mut options = fixture.options(project.path());
1026 options.thresholds.max_crap = Some(0.0);
1027 options.targets = true;
1028 let config = crate::project_config::default_project_config(project.path()).config;
1029
1030 assert!(should_precompute_dead_code_analysis(&options, &config));
1031 }
1032
1033 #[test]
1034 fn health_run_options_ownership_requires_hotspots() {
1035 let mut input = health_run_input();
1036 input.complexity = true;
1037 input.ownership = true;
1038
1039 let run = derive_health_run_options(input);
1040
1041 assert!(!run.sections.hotspots);
1042 assert!(!run.ownership);
1043
1044 let mut input = health_run_input();
1045 input.ownership = true;
1046 input.hotspots = true;
1047
1048 let run = derive_health_run_options(input);
1049
1050 assert!(run.sections.hotspots);
1051 assert!(run.ownership);
1052 }
1053
1054 #[test]
1055 fn health_run_options_score_gate_forces_score() {
1056 let mut input = health_run_input();
1057 input.gates.min_score = Some(90.0);
1058
1059 let run = derive_health_run_options(input);
1060
1061 assert!(run.sections.score);
1062 assert_eq!(run.gates.min_score, Some(90.0));
1063 }
1064
1065 #[test]
1066 fn coverage_root_accepts_posix_absolute() {
1067 assert!(validate_coverage_root_absolute(Some(Path::new("/ci/workspace"))).is_ok());
1068 assert!(
1069 validate_coverage_root_absolute(Some(Path::new("/home/runner/work/myapp"))).is_ok()
1070 );
1071 }
1072
1073 #[test]
1074 fn coverage_root_rejects_relative() {
1075 assert!(validate_coverage_root_absolute(Some(Path::new("src"))).is_err());
1076 assert!(validate_coverage_root_absolute(Some(Path::new("./coverage"))).is_err());
1077 assert!(validate_coverage_root_absolute(Some(Path::new("a/b/c"))).is_err());
1078 }
1079
1080 #[test]
1081 fn coverage_root_accepts_none() {
1082 assert!(validate_coverage_root_absolute(None).is_ok());
1083 }
1084
1085 #[test]
1086 fn coverage_root_accepts_windows_absolute_on_all_hosts() {
1087 assert!(validate_coverage_root_absolute(Some(Path::new(r"C:\ci\workspace"))).is_ok());
1088 }
1089}