1#![allow(
2 clippy::print_stderr,
3 reason = "human stderr notes (no-git, bot patterns, CODEOWNERS) preserved verbatim from the CLI health path"
4)]
5
6use fallow_output::{ClockProvenance, ClockSource, FileHealthScore, HotspotEntry, HotspotSummary};
7
8use super::HealthOptions;
9use super::ownership::{OwnershipContext, compile_bot_globs, compute_ownership_with_identities};
10use crate::test_paths::is_test_path;
11
12pub struct ChurnFetchResult {
14 pub result: crate::churn::ChurnResult,
15 pub since: crate::churn::SinceDuration,
16 pub history: crate::churn::SinceDuration,
20 pub cache_hit: bool,
21 pub git_log_ms: f64,
22}
23
24pub struct TargetChurnOptions<'a> {
29 pub root: &'a std::path::Path,
31 pub target: &'a std::path::Path,
33 pub cache_dir: std::path::PathBuf,
35 pub no_cache: bool,
37 pub since: Option<&'a str>,
40 pub min_commits: Option<u32>,
42}
43
44#[derive(Debug)]
46pub struct TargetChurnEvidence {
47 pub file: crate::churn::FileChurn,
49 pub since: crate::churn::SinceDuration,
51 pub min_commits: u32,
53 pub shallow_clone: bool,
56}
57
58#[derive(Debug)]
60pub enum TargetChurnOutcome {
61 Found(TargetChurnEvidence),
63 NoQualifyingChurn {
65 observed_commits: Option<u32>,
67 since: crate::churn::SinceDuration,
69 min_commits: u32,
71 shallow_clone: bool,
74 },
75 Unavailable {
77 message: String,
79 },
80}
81
82pub fn analyze_target_churn(
88 options: &TargetChurnOptions<'_>,
89) -> Result<TargetChurnOutcome, String> {
90 analyze_target_churn_with(
91 options,
92 crate::churn::is_git_repo,
93 crate::churn::analyze_churn_cached,
94 )
95}
96
97fn analyze_target_churn_with<GitAvailable, Analyze>(
98 options: &TargetChurnOptions<'_>,
99 git_available: GitAvailable,
100 analyze: Analyze,
101) -> Result<TargetChurnOutcome, String>
102where
103 GitAvailable: FnOnce(&std::path::Path) -> bool,
104 Analyze: FnOnce(
105 &std::path::Path,
106 &crate::churn::SinceDuration,
107 &std::path::Path,
108 bool,
109 ) -> Option<(crate::churn::ChurnResult, bool)>,
110{
111 if !git_available(options.root) {
112 return Ok(TargetChurnOutcome::Unavailable {
113 message: "git repository unavailable at project root".to_string(),
114 });
115 }
116
117 let since = crate::churn::parse_since(options.since.unwrap_or("6m"))?;
118 let min_commits = options.min_commits.unwrap_or(3);
119 let Some((result, _cache_hit)) =
120 analyze(options.root, &since, &options.cache_dir, options.no_cache)
121 else {
122 return Err("git churn analysis failed".to_string());
123 };
124 let shallow_clone = result.shallow_clone;
125 let target = options.root.join(options.target);
126 let file = result.files.get(&target).cloned();
127
128 let observed_commits = file.as_ref().map(|file| file.commits);
129 if let Some(file) = file
130 && file.commits >= min_commits
131 {
132 return Ok(TargetChurnOutcome::Found(TargetChurnEvidence {
133 file,
134 since,
135 min_commits,
136 shallow_clone,
137 }));
138 }
139
140 Ok(TargetChurnOutcome::NoQualifyingChurn {
141 observed_commits,
142 since,
143 min_commits,
144 shallow_clone,
145 })
146}
147
148pub(super) fn fetch_churn_data(
156 opts: &HealthOptions<'_>,
157 cache_dir: &std::path::Path,
158) -> Option<ChurnFetchResult> {
159 if let Some(churn_file) = opts.churn_file {
165 let resolved =
166 crate::health::scoring::resolve_relative_to_root(churn_file, Some(opts.root));
167 let t = std::time::Instant::now();
168 let result = match crate::churn::analyze_churn_from_file(&resolved, opts.root) {
169 Ok(r) => r,
170 Err(e) => {
171 tracing::warn!("churn file became unreadable after validation: {e}");
178 super::diagnostics::record_health_diagnostic(
182 opts.root,
183 Some(&resolved),
184 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
185 cause: "churn-file-unreadable".to_owned(),
186 },
187 );
188 return None;
189 }
190 };
191 return Some(ChurnFetchResult {
192 result,
193 since: imported_since(),
194 history: imported_since(),
195 cache_hit: false,
196 git_log_ms: t.elapsed().as_secs_f64() * 1000.0,
197 });
198 }
199
200 if !crate::churn::is_git_repo(opts.root) {
201 if !opts.quiet {
202 eprintln!("note: hotspot analysis skipped: no git repository found at project root");
203 }
204 super::diagnostics::record_health_diagnostic(
207 opts.root,
208 None,
209 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
210 cause: "not-a-repository".to_owned(),
211 },
212 );
213 return None;
214 }
215
216 let since_input = opts.since.unwrap_or(DEFAULT_HOTSPOT_WINDOW);
217 if let Err(e) = crate::validate::validate_no_control_chars(since_input, "--since") {
218 tracing::warn!("hotspot analysis skipped: {e}");
225 record_invalid_since(opts.root);
226 return None;
227 }
228 let since = match crate::churn::parse_since(since_input) {
229 Ok(s) => s,
230 Err(e) => {
231 tracing::warn!("hotspot analysis skipped: invalid --since: {e}");
232 record_invalid_since(opts.root);
233 return None;
234 }
235 };
236
237 let history = if opts.since.is_some() {
241 since.clone()
242 } else {
243 crate::churn::SinceDuration::relative(
244 DEFAULT_HISTORY_MONTHS,
245 crate::churn::ChurnWindowUnit::Months,
246 format!("{DEFAULT_HISTORY_MONTHS} months"),
247 )
248 };
249
250 let t = std::time::Instant::now();
251 let Some((churn_result, cache_hit)) = crate::churn::analyze_churn_cached_with_history(
252 opts.root,
253 &since,
254 &history,
255 cache_dir,
256 opts.no_cache,
257 ) else {
258 record_unborn_head(opts);
259 return None;
260 };
261 let git_log_ms = t.elapsed().as_secs_f64() * 1000.0;
262
263 Some(ChurnFetchResult {
264 result: churn_result,
265 since,
266 history,
267 cache_hit,
268 git_log_ms,
269 })
270}
271
272const DEFAULT_HOTSPOT_WINDOW: &str = "6m";
274
275const DEFAULT_HISTORY_MONTHS: u64 = 12;
278
279fn record_unborn_head(opts: &HealthOptions<'_>) {
285 if !matches!(crate::repo_refs::head_sha(opts.root), Ok(None)) {
286 return;
287 }
288 if !opts.quiet {
289 eprintln!("note: hotspot analysis skipped: the current branch has no commits yet");
290 }
291 super::diagnostics::record_health_diagnostic(
292 opts.root,
293 None,
294 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
295 cause: "no-commits".to_owned(),
296 },
297 );
298}
299
300fn record_invalid_since(root: &std::path::Path) {
307 super::diagnostics::record_health_diagnostic(
308 root,
309 None,
310 fallow_types::workspace::WorkspaceDiagnosticKind::HotspotsSkipped {
311 cause: "invalid-since".to_owned(),
312 },
313 );
314}
315
316fn imported_since() -> crate::churn::SinceDuration {
320 crate::churn::SinceDuration {
321 window: crate::churn::ChurnWindow::Imported,
322 display: "imported churn".to_string(),
323 }
324}
325
326fn compute_normalization_maxima(
330 file_scores: &[FileHealthScore],
331 churn_files: &rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn>,
332 min_commits: u32,
333) -> (f64, f64) {
334 let mut max_weighted: f64 = 0.0;
335 let mut max_density: f64 = 0.0;
336 for score in file_scores {
337 if let Some(churn) = churn_files.get(&score.path)
338 && churn.commits >= min_commits
339 {
340 max_weighted = max_weighted.max(churn.weighted_commits);
341 max_density = max_density.max(score.complexity_density);
342 }
343 }
344 (max_weighted, max_density)
345}
346
347fn is_excluded_from_hotspots(
350 path: &std::path::Path,
351 root: &std::path::Path,
352 ignore_set: &globset::GlobSet,
353 ws_roots: Option<&crate::workspace_scope::WorkspaceScope>,
354) -> bool {
355 if let Some(ws) = ws_roots
356 && !ws.contains(path)
357 {
358 return true;
359 }
360 if !ignore_set.is_empty() {
361 let relative = path.strip_prefix(root).unwrap_or(path);
362 if ignore_set.is_match(relative) {
363 return true;
364 }
365 }
366 false
367}
368
369fn compute_hotspot_score(
374 weighted_commits: f64,
375 max_weighted: f64,
376 complexity_density: f64,
377 max_density: f64,
378) -> f64 {
379 let norm_churn = if max_weighted > 0.0 {
380 weighted_commits / max_weighted
381 } else {
382 0.0
383 };
384 let norm_complexity = if max_density > 0.0 {
385 complexity_density / max_density
386 } else {
387 0.0
388 };
389 (norm_churn * norm_complexity * 100.0 * 10.0).round() / 10.0
390}
391
392pub(super) struct HotspotComputationInput<'a> {
393 pub(super) opts: &'a HealthOptions<'a>,
394 pub(super) config: &'a fallow_config::ResolvedConfig,
395 pub(super) file_scores: &'a [FileHealthScore],
396 pub(super) ignore_set: &'a globset::GlobSet,
397 pub(super) ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
398 pub(super) churn_fetch: ChurnFetchResult,
399 pub(super) dispersion: Option<
401 &'a rustc_hash::FxHashMap<std::path::PathBuf, crate::change_coupling::FileDispersion>,
402 >,
403}
404
405pub(super) fn compute_hotspots(
410 input: HotspotComputationInput<'_>,
411) -> (Vec<HotspotEntry>, Option<HotspotSummary>) {
412 let HotspotComputationInput {
413 opts,
414 config,
415 file_scores,
416 ignore_set,
417 ws_roots,
418 churn_fetch,
419 dispersion,
420 } = input;
421 let churn_result = churn_fetch.result;
422 let since = churn_fetch.since;
423
424 let shallow_clone = churn_result.shallow_clone;
425 warn_shallow_clone(opts, shallow_clone);
426 warn_unpinned_clock(opts, churn_result.clock);
427
428 let min_commits = opts.min_commits.unwrap_or(3);
429 let (max_weighted, max_density) =
430 compute_normalization_maxima(file_scores, &churn_result.files, min_commits);
431
432 let ownership_cfg = &config.health.ownership;
433 let bot_globs_owned = load_ownership_bot_globs(opts, ownership_cfg);
434 let codeowners_owned = load_ownership_codeowners(opts, &config.root);
435 let now_secs = churn_result.clock.epoch_secs();
439 let ownership_ctx = bot_globs_owned.as_ref().map(|bot_globs| OwnershipContext {
440 author_pool: &churn_result.author_pool,
441 bot_globs,
442 codeowners: codeowners_owned.as_ref(),
443 email_mode: opts.ownership_emails.unwrap_or(ownership_cfg.email_mode),
444 now_secs,
445 });
446
447 let (mut hotspot_entries, files_excluded) = collect_hotspot_entries(&HotspotEntryCtx {
448 file_scores,
449 root: &config.root,
450 ignore_set,
451 ws_roots,
452 churn_files: &churn_result.files,
453 min_commits,
454 max_weighted,
455 max_density,
456 ownership_ctx: ownership_ctx.as_ref(),
457 dispersion,
458 });
459
460 hotspot_entries.sort_by(|a, b| {
461 b.score
462 .partial_cmp(&a.score)
463 .unwrap_or(std::cmp::Ordering::Equal)
464 });
465
466 let files_analyzed = hotspot_entries.len();
467 let summary = HotspotSummary {
468 since: since.display,
469 min_commits,
470 files_analyzed,
471 files_excluded,
472 shallow_clone,
473 clock: Some(clock_provenance(churn_result.clock)),
474 };
475
476 (hotspot_entries, Some(summary))
477}
478
479fn clock_provenance(clock: crate::clock::AnalysisClock) -> ClockProvenance {
485 ClockProvenance {
486 source: match clock.source() {
487 crate::clock::AnalysisClockSource::Environment => ClockSource::Environment,
488 crate::clock::AnalysisClockSource::HeadCommit => ClockSource::HeadCommit,
489 crate::clock::AnalysisClockSource::WallClock => ClockSource::WallClock,
490 },
491 epoch_secs: clock.epoch_secs(),
492 reproducible: clock.is_reproducible(),
493 }
494}
495
496fn warn_unpinned_clock(opts: &HealthOptions<'_>, clock: crate::clock::AnalysisClock) {
505 if clock.is_reproducible() {
506 return;
507 }
508 if !opts.quiet {
509 eprintln!(
510 "Warning: no commit timestamp available, so churn recency and \
511 ownership staleness were measured against the wall clock and will \
512 drift between runs. Set FALLOW_CLOCK_EPOCH to pin them."
513 );
514 }
515 super::diagnostics::record_health_diagnostic(
516 opts.root,
517 None,
518 fallow_types::workspace::WorkspaceDiagnosticKind::UnpinnedClock,
519 );
520}
521
522fn warn_shallow_clone(opts: &HealthOptions<'_>, shallow_clone: bool) {
524 if !shallow_clone {
525 return;
526 }
527 if !opts.quiet {
528 eprintln!(
529 "Warning: shallow clone detected. Hotspot analysis may be incomplete. \
530 Use `git fetch --unshallow` for full history."
531 );
532 if opts.ownership {
533 eprintln!(
534 "Warning: shallow clones inflate single-author dominance, so \
535 ownership signals will be skewed."
536 );
537 }
538 }
539 super::diagnostics::record_health_diagnostic(
540 opts.root,
541 None,
542 fallow_types::workspace::WorkspaceDiagnosticKind::ShallowClone {
543 ownership_requested: opts.ownership,
544 },
545 );
546}
547
548fn load_ownership_bot_globs(
550 opts: &HealthOptions<'_>,
551 ownership_cfg: &fallow_config::OwnershipConfig,
552) -> Option<globset::GlobSet> {
553 opts.ownership.then(|| {
554 compile_bot_globs(&ownership_cfg.bot_patterns).unwrap_or_else(|e| {
555 if !opts.quiet {
556 eprintln!("Warning: invalid bot pattern in health.ownership.botPatterns: {e}");
557 }
558 super::diagnostics::record_health_diagnostic(
559 opts.root,
560 None,
561 fallow_types::workspace::WorkspaceDiagnosticKind::OwnershipUnavailable {
562 cause: "invalid-bot-pattern".to_owned(),
563 error: e.to_string(),
564 },
565 );
566 globset::GlobSet::empty()
567 })
568 })
569}
570
571fn load_ownership_codeowners(
573 opts: &HealthOptions<'_>,
574 root: &std::path::Path,
575) -> Option<crate::codeowners::CodeOwners> {
576 opts.ownership
577 .then(|| match crate::codeowners::CodeOwners::load(root, None) {
578 Ok(co) => Some(co),
579 Err(e) => {
580 if !e.contains("no CODEOWNERS file found") {
584 if !opts.quiet {
585 eprintln!("Warning: failed to parse CODEOWNERS: {e}");
586 }
587 super::diagnostics::record_health_diagnostic(
588 root,
589 None,
590 fallow_types::workspace::WorkspaceDiagnosticKind::OwnershipUnavailable {
591 cause: "codeowners-parse-failed".to_owned(),
592 error: e,
593 },
594 );
595 }
596 None
597 }
598 })
599 .flatten()
600}
601
602struct HotspotEntryCtx<'a> {
604 file_scores: &'a [FileHealthScore],
605 root: &'a std::path::Path,
606 ignore_set: &'a globset::GlobSet,
607 ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
608 churn_files: &'a rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn>,
609 min_commits: u32,
610 max_weighted: f64,
611 max_density: f64,
612 ownership_ctx: Option<&'a OwnershipContext<'a>>,
613 dispersion: Option<
614 &'a rustc_hash::FxHashMap<std::path::PathBuf, crate::change_coupling::FileDispersion>,
615 >,
616}
617
618fn collect_hotspot_entries(ctx: &HotspotEntryCtx<'_>) -> (Vec<HotspotEntry>, usize) {
621 let mut hotspot_entries = Vec::new();
622 let mut files_excluded: usize = 0;
623
624 for score in ctx.file_scores {
625 if is_excluded_from_hotspots(&score.path, ctx.root, ctx.ignore_set, ctx.ws_roots) {
626 continue;
627 }
628
629 let Some(churn) = ctx.churn_files.get(&score.path) else {
630 continue;
631 };
632 if churn.commits < ctx.min_commits {
633 files_excluded += 1;
634 continue;
635 }
636
637 let relative = score.path.strip_prefix(ctx.root).unwrap_or(&score.path);
638 let ownership = ctx
639 .ownership_ctx
640 .and_then(|own| compute_ownership_with_identities(churn, relative, own))
641 .map(|owned| owned.metrics);
642 let dispersion = ctx.dispersion.and_then(|map| map.get(&score.path));
643
644 hotspot_entries.push(HotspotEntry {
645 path: score.path.clone(),
646 score: compute_hotspot_score(
647 churn.weighted_commits,
648 ctx.max_weighted,
649 score.complexity_density,
650 ctx.max_density,
651 ),
652 commits: churn.commits,
653 weighted_commits: churn.weighted_commits,
654 lines_added: churn.lines_added,
655 lines_deleted: churn.lines_deleted,
656 complexity_density: score.complexity_density,
657 fan_in: score.fan_in,
658 trend: churn.trend,
659 median_files_per_commit: dispersion
660 .map(|d| round_one_decimal(d.median_files_per_commit)),
661 median_lines_per_commit: dispersion
662 .map(|d| round_one_decimal(d.median_lines_per_commit)),
663 ownership,
664 is_test_path: is_test_path(ctx.root, relative),
665 });
666 }
667
668 (hotspot_entries, files_excluded)
669}
670
671fn round_one_decimal(value: f64) -> f64 {
672 (value * 10.0).round() / 10.0
673}
674
675#[cfg(test)]
676mod tests {
677 use super::*;
678
679 fn target_churn_options(root: &std::path::Path) -> TargetChurnOptions<'_> {
680 TargetChurnOptions {
681 root,
682 target: std::path::Path::new("src/app.ts"),
683 cache_dir: root.join(".fallow"),
684 no_cache: true,
685 since: None,
686 min_commits: None,
687 }
688 }
689
690 fn churn_result(root: &std::path::Path, commits: u32) -> crate::churn::ChurnResult {
691 let path = root.join("src/app.ts");
692 let mut files = rustc_hash::FxHashMap::default();
693 files.insert(
694 path.clone(),
695 crate::churn::FileChurn {
696 path,
697 commits,
698 weighted_commits: 2.5,
699 lines_added: 20,
700 lines_deleted: 5,
701 trend: crate::churn::ChurnTrend::Accelerating,
702 authors: rustc_hash::FxHashMap::default(),
703 },
704 );
705 crate::churn::ChurnResult {
706 files,
707 shallow_clone: false,
708 author_pool: Vec::new(),
709 clock: crate::clock::AnalysisClock::pinned(1_788_782_400),
710 git_log_bytes: 0,
711 commits: Vec::new(),
712 }
713 }
714
715 #[test]
716 fn target_churn_returns_only_the_requested_qualifying_file() {
717 let root = std::path::Path::new("/project");
718 let options = target_churn_options(root);
719
720 let outcome = analyze_target_churn_with(
721 &options,
722 |_| true,
723 |_, _, _, _| Some((churn_result(root, 4), false)),
724 )
725 .unwrap();
726
727 let TargetChurnOutcome::Found(evidence) = outcome else {
728 panic!("expected qualifying churn evidence");
729 };
730 assert_eq!(evidence.file.path, root.join("src/app.ts"));
731 assert_eq!(evidence.file.commits, 4);
732 assert_eq!(evidence.min_commits, 3);
733 assert_eq!(evidence.since.display, "6 months");
734 }
735
736 #[test]
737 fn target_churn_distinguishes_no_qualifying_history() {
738 let root = std::path::Path::new("/project");
739 let options = target_churn_options(root);
740
741 let outcome = analyze_target_churn_with(
742 &options,
743 |_| true,
744 |_, _, _, _| Some((churn_result(root, 2), false)),
745 )
746 .unwrap();
747
748 assert!(matches!(
749 outcome,
750 TargetChurnOutcome::NoQualifyingChurn {
751 observed_commits: Some(2),
752 min_commits: 3,
753 ..
754 }
755 ));
756 }
757
758 #[test]
759 fn target_churn_distinguishes_git_unavailable() {
760 let root = std::path::Path::new("/project");
761 let options = target_churn_options(root);
762
763 let outcome = analyze_target_churn_with(
764 &options,
765 |_| false,
766 |_, _, _, _| panic!("churn analysis must not run without git"),
767 )
768 .unwrap();
769
770 assert!(matches!(outcome, TargetChurnOutcome::Unavailable { .. }));
771 }
772
773 #[test]
774 fn target_churn_surfaces_analysis_failure() {
775 let root = std::path::Path::new("/project");
776 let options = target_churn_options(root);
777
778 let error = analyze_target_churn_with(&options, |_| true, |_, _, _, _| None)
779 .expect_err("failed git analysis must remain explicit");
780
781 assert!(error.contains("git churn analysis failed"));
782 }
783
784 #[test]
785 fn hotspot_score_both_maxima_zero() {
786 assert!((compute_hotspot_score(0.0, 0.0, 0.0, 0.0)).abs() < f64::EPSILON);
787 }
788
789 #[test]
790 fn hotspot_score_max_weighted_zero() {
791 assert!((compute_hotspot_score(5.0, 0.0, 0.5, 1.0)).abs() < f64::EPSILON);
792 }
793
794 #[test]
795 fn hotspot_score_max_density_zero() {
796 assert!((compute_hotspot_score(5.0, 10.0, 0.0, 0.0)).abs() < f64::EPSILON);
797 }
798
799 #[test]
800 fn hotspot_score_equal_normalization() {
801 let score = compute_hotspot_score(10.0, 10.0, 2.0, 2.0);
802 assert!((score - 100.0).abs() < f64::EPSILON);
803 }
804
805 #[test]
806 fn hotspot_score_half_values() {
807 let score = compute_hotspot_score(5.0, 10.0, 1.0, 2.0);
808 assert!((score - 25.0).abs() < f64::EPSILON);
809 }
810
811 #[test]
812 fn excluded_no_filters() {
813 let path = std::path::Path::new("/project/src/foo.ts");
814 let root = std::path::Path::new("/project");
815 let ignore_set = globset::GlobSet::empty();
816
817 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
818 }
819
820 #[test]
821 fn excluded_workspace_filter_mismatch() {
822 let path = std::path::Path::new("/project/packages/b/src/foo.ts");
823 let root = std::path::Path::new("/project");
824 let ws_roots: crate::workspace_scope::WorkspaceScope =
825 vec![std::path::PathBuf::from("/project/packages/a")].into();
826 let ignore_set = globset::GlobSet::empty();
827
828 assert!(is_excluded_from_hotspots(
829 path,
830 root,
831 &ignore_set,
832 Some(&ws_roots)
833 ));
834 }
835
836 #[test]
837 fn excluded_workspace_filter_match() {
838 let path = std::path::Path::new("/project/packages/a/src/foo.ts");
839 let root = std::path::Path::new("/project");
840 let ws_roots: crate::workspace_scope::WorkspaceScope =
841 vec![std::path::PathBuf::from("/project/packages/a")].into();
842 let ignore_set = globset::GlobSet::empty();
843
844 assert!(!is_excluded_from_hotspots(
845 path,
846 root,
847 &ignore_set,
848 Some(&ws_roots)
849 ));
850 }
851
852 #[test]
853 fn excluded_matching_glob() {
854 let path = std::path::Path::new("/project/src/generated/types.ts");
855 let root = std::path::Path::new("/project");
856 let mut builder = globset::GlobSetBuilder::new();
857 builder.add(globset::Glob::new("src/generated/**").unwrap());
858 let ignore_set = builder.build().unwrap();
859
860 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
861 }
862
863 #[test]
864 fn excluded_non_matching_glob() {
865 let path = std::path::Path::new("/project/src/components/Button.tsx");
866 let root = std::path::Path::new("/project");
867 let mut builder = globset::GlobSetBuilder::new();
868 builder.add(globset::Glob::new("src/generated/**").unwrap());
869 let ignore_set = builder.build().unwrap();
870
871 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
872 }
873
874 #[test]
875 fn normalization_maxima_empty_input() {
876 let scores: Vec<FileHealthScore> = vec![];
877 let churn_files = rustc_hash::FxHashMap::default();
878
879 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
880 assert!((max_w).abs() < f64::EPSILON);
881 assert!((max_d).abs() < f64::EPSILON);
882 }
883
884 #[test]
885 fn normalization_maxima_single_file() {
886 let scores = vec![FileHealthScore {
887 path: std::path::PathBuf::from("/src/foo.ts"),
888 fan_in: 0,
889 fan_out: 0,
890 dead_code_ratio: 0.0,
891 complexity_density: 0.75,
892 maintainability_index: 80.0,
893 total_cyclomatic: 15,
894 total_cognitive: 10,
895 function_count: 3,
896 lines: 20,
897 crap_max: 0.0,
898 crap_above_threshold: 0,
899 crap_exempted: 0,
900 crap_suppressed: 0,
901 crap_unsuppressed_max: None,
902 crap_unsuppressed_effective_threshold: None,
903 crap_effective_threshold: None,
904 }];
905 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
906 rustc_hash::FxHashMap::default();
907 churn_files.insert(
908 std::path::PathBuf::from("/src/foo.ts"),
909 crate::churn::FileChurn {
910 path: std::path::PathBuf::from("/src/foo.ts"),
911 commits: 5,
912 weighted_commits: 4.2,
913 lines_added: 100,
914 lines_deleted: 20,
915 trend: crate::churn::ChurnTrend::Stable,
916 authors: rustc_hash::FxHashMap::default(),
917 },
918 );
919
920 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
921 assert!((max_w - 4.2).abs() < f64::EPSILON);
922 assert!((max_d - 0.75).abs() < f64::EPSILON);
923 }
924
925 #[test]
929 fn normalization_maxima_ignore_crap_exemption_fields() {
930 let base = FileHealthScore {
931 path: std::path::PathBuf::from("/src/foo.ts"),
932 fan_in: 0,
933 fan_out: 0,
934 dead_code_ratio: 0.0,
935 complexity_density: 0.75,
936 maintainability_index: 80.0,
937 total_cyclomatic: 15,
938 total_cognitive: 10,
939 function_count: 3,
940 lines: 20,
941 crap_max: 110.0,
942 crap_above_threshold: 2,
943 crap_exempted: 0,
944 crap_suppressed: 0,
945 crap_unsuppressed_max: None,
946 crap_unsuppressed_effective_threshold: None,
947 crap_effective_threshold: None,
948 };
949 let exempt = FileHealthScore {
950 crap_above_threshold: 0,
951 crap_exempted: 2,
952 crap_effective_threshold: Some(500.0),
953 ..base.clone()
954 };
955 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
956 rustc_hash::FxHashMap::default();
957 churn_files.insert(
958 std::path::PathBuf::from("/src/foo.ts"),
959 crate::churn::FileChurn {
960 path: std::path::PathBuf::from("/src/foo.ts"),
961 commits: 5,
962 weighted_commits: 4.2,
963 lines_added: 100,
964 lines_deleted: 20,
965 trend: crate::churn::ChurnTrend::Stable,
966 authors: rustc_hash::FxHashMap::default(),
967 },
968 );
969
970 let flagged = compute_normalization_maxima(&[base], &churn_files, 3);
971 let exempted = compute_normalization_maxima(&[exempt], &churn_files, 3);
972 assert_eq!(flagged, exempted);
973 }
974
975 #[test]
976 fn normalization_maxima_below_min_commits() {
977 let scores = vec![FileHealthScore {
978 path: std::path::PathBuf::from("/src/foo.ts"),
979 fan_in: 0,
980 fan_out: 0,
981 dead_code_ratio: 0.0,
982 complexity_density: 0.75,
983 maintainability_index: 80.0,
984 total_cyclomatic: 15,
985 total_cognitive: 10,
986 function_count: 3,
987 lines: 20,
988 crap_max: 0.0,
989 crap_above_threshold: 0,
990 crap_exempted: 0,
991 crap_suppressed: 0,
992 crap_unsuppressed_max: None,
993 crap_unsuppressed_effective_threshold: None,
994 crap_effective_threshold: None,
995 }];
996 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
997 rustc_hash::FxHashMap::default();
998 churn_files.insert(
999 std::path::PathBuf::from("/src/foo.ts"),
1000 crate::churn::FileChurn {
1001 path: std::path::PathBuf::from("/src/foo.ts"),
1002 commits: 2, weighted_commits: 4.2,
1004 lines_added: 100,
1005 lines_deleted: 20,
1006 trend: crate::churn::ChurnTrend::Stable,
1007 authors: rustc_hash::FxHashMap::default(),
1008 },
1009 );
1010
1011 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1012 assert!((max_w).abs() < f64::EPSILON);
1013 assert!((max_d).abs() < f64::EPSILON);
1014 }
1015
1016 #[test]
1017 fn normalization_maxima_all_zeros() {
1018 let scores = vec![FileHealthScore {
1019 path: std::path::PathBuf::from("/src/foo.ts"),
1020 fan_in: 0,
1021 fan_out: 0,
1022 dead_code_ratio: 0.0,
1023 complexity_density: 0.0,
1024 maintainability_index: 100.0,
1025 total_cyclomatic: 0,
1026 total_cognitive: 0,
1027 function_count: 1,
1028 lines: 10,
1029 crap_max: 0.0,
1030 crap_above_threshold: 0,
1031 crap_exempted: 0,
1032 crap_suppressed: 0,
1033 crap_unsuppressed_max: None,
1034 crap_unsuppressed_effective_threshold: None,
1035 crap_effective_threshold: None,
1036 }];
1037 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1038 rustc_hash::FxHashMap::default();
1039 churn_files.insert(
1040 std::path::PathBuf::from("/src/foo.ts"),
1041 crate::churn::FileChurn {
1042 path: std::path::PathBuf::from("/src/foo.ts"),
1043 commits: 5,
1044 weighted_commits: 0.0,
1045 lines_added: 0,
1046 lines_deleted: 0,
1047 trend: crate::churn::ChurnTrend::Stable,
1048 authors: rustc_hash::FxHashMap::default(),
1049 },
1050 );
1051
1052 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1053 assert!((max_w).abs() < f64::EPSILON);
1054 assert!((max_d).abs() < f64::EPSILON);
1055 }
1056
1057 #[test]
1058 fn hotspot_score_high_churn_low_complexity() {
1059 let score = compute_hotspot_score(10.0, 10.0, 0.1, 1.0);
1060 assert!((score - 10.0).abs() < f64::EPSILON);
1061 }
1062
1063 #[test]
1064 fn hotspot_score_low_churn_high_complexity() {
1065 let score = compute_hotspot_score(1.0, 10.0, 2.0, 2.0);
1066 assert!((score - 10.0).abs() < f64::EPSILON);
1067 }
1068
1069 #[test]
1070 fn hotspot_score_rounding() {
1071 let score = compute_hotspot_score(1.0, 3.0, 1.0, 3.0);
1072 assert!((score - 11.1).abs() < f64::EPSILON);
1073 }
1074
1075 #[test]
1076 fn hotspot_score_very_small_values() {
1077 let score = compute_hotspot_score(0.01, 100.0, 0.001, 10.0);
1078 assert!((score).abs() < 0.1);
1079 }
1080
1081 #[test]
1082 fn hotspot_score_weighted_exceeds_max() {
1083 let score = compute_hotspot_score(15.0, 10.0, 1.0, 2.0);
1084 assert!((score - 75.0).abs() < f64::EPSILON);
1085 }
1086
1087 #[test]
1088 fn normalization_maxima_multiple_files_picks_max() {
1089 let scores = vec![
1090 FileHealthScore {
1091 path: std::path::PathBuf::from("/src/a.ts"),
1092 fan_in: 0,
1093 fan_out: 0,
1094 dead_code_ratio: 0.0,
1095 complexity_density: 0.5,
1096 maintainability_index: 80.0,
1097 total_cyclomatic: 10,
1098 total_cognitive: 5,
1099 function_count: 2,
1100 lines: 50,
1101 crap_max: 0.0,
1102 crap_above_threshold: 0,
1103 crap_exempted: 0,
1104 crap_suppressed: 0,
1105 crap_unsuppressed_max: None,
1106 crap_unsuppressed_effective_threshold: None,
1107 crap_effective_threshold: None,
1108 },
1109 FileHealthScore {
1110 path: std::path::PathBuf::from("/src/b.ts"),
1111 fan_in: 0,
1112 fan_out: 0,
1113 dead_code_ratio: 0.0,
1114 complexity_density: 1.2, maintainability_index: 60.0,
1116 total_cyclomatic: 30,
1117 total_cognitive: 20,
1118 function_count: 5,
1119 lines: 100,
1120 crap_max: 0.0,
1121 crap_above_threshold: 0,
1122 crap_exempted: 0,
1123 crap_suppressed: 0,
1124 crap_unsuppressed_max: None,
1125 crap_unsuppressed_effective_threshold: None,
1126 crap_effective_threshold: None,
1127 },
1128 FileHealthScore {
1129 path: std::path::PathBuf::from("/src/c.ts"),
1130 fan_in: 0,
1131 fan_out: 0,
1132 dead_code_ratio: 0.0,
1133 complexity_density: 0.8,
1134 maintainability_index: 70.0,
1135 total_cyclomatic: 20,
1136 total_cognitive: 15,
1137 function_count: 4,
1138 lines: 80,
1139 crap_max: 0.0,
1140 crap_above_threshold: 0,
1141 crap_exempted: 0,
1142 crap_suppressed: 0,
1143 crap_unsuppressed_max: None,
1144 crap_unsuppressed_effective_threshold: None,
1145 crap_effective_threshold: None,
1146 },
1147 ];
1148 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1149 rustc_hash::FxHashMap::default();
1150 churn_files.insert(
1151 std::path::PathBuf::from("/src/a.ts"),
1152 crate::churn::FileChurn {
1153 path: std::path::PathBuf::from("/src/a.ts"),
1154 commits: 5,
1155 weighted_commits: 3.0,
1156 lines_added: 50,
1157 lines_deleted: 10,
1158 trend: crate::churn::ChurnTrend::Stable,
1159 authors: rustc_hash::FxHashMap::default(),
1160 },
1161 );
1162 churn_files.insert(
1163 std::path::PathBuf::from("/src/b.ts"),
1164 crate::churn::FileChurn {
1165 path: std::path::PathBuf::from("/src/b.ts"),
1166 commits: 10,
1167 weighted_commits: 8.5, lines_added: 200,
1169 lines_deleted: 50,
1170 trend: crate::churn::ChurnTrend::Accelerating,
1171 authors: rustc_hash::FxHashMap::default(),
1172 },
1173 );
1174 churn_files.insert(
1175 std::path::PathBuf::from("/src/c.ts"),
1176 crate::churn::FileChurn {
1177 path: std::path::PathBuf::from("/src/c.ts"),
1178 commits: 7,
1179 weighted_commits: 5.0,
1180 lines_added: 100,
1181 lines_deleted: 30,
1182 trend: crate::churn::ChurnTrend::Cooling,
1183 authors: rustc_hash::FxHashMap::default(),
1184 },
1185 );
1186
1187 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1188 assert!((max_w - 8.5).abs() < f64::EPSILON);
1189 assert!((max_d - 1.2).abs() < f64::EPSILON);
1190 }
1191
1192 #[test]
1193 fn normalization_maxima_mixed_above_and_below_threshold() {
1194 let scores = vec![
1195 FileHealthScore {
1196 path: std::path::PathBuf::from("/src/frequent.ts"),
1197 fan_in: 0,
1198 fan_out: 0,
1199 dead_code_ratio: 0.0,
1200 complexity_density: 0.4,
1201 maintainability_index: 85.0,
1202 total_cyclomatic: 8,
1203 total_cognitive: 4,
1204 function_count: 2,
1205 lines: 40,
1206 crap_max: 0.0,
1207 crap_above_threshold: 0,
1208 crap_exempted: 0,
1209 crap_suppressed: 0,
1210 crap_unsuppressed_max: None,
1211 crap_unsuppressed_effective_threshold: None,
1212 crap_effective_threshold: None,
1213 },
1214 FileHealthScore {
1215 path: std::path::PathBuf::from("/src/rare.ts"),
1216 fan_in: 0,
1217 fan_out: 0,
1218 dead_code_ratio: 0.0,
1219 complexity_density: 2.0, maintainability_index: 50.0,
1221 total_cyclomatic: 40,
1222 total_cognitive: 30,
1223 function_count: 8,
1224 lines: 200,
1225 crap_max: 0.0,
1226 crap_above_threshold: 0,
1227 crap_exempted: 0,
1228 crap_suppressed: 0,
1229 crap_unsuppressed_max: None,
1230 crap_unsuppressed_effective_threshold: None,
1231 crap_effective_threshold: None,
1232 },
1233 ];
1234 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1235 rustc_hash::FxHashMap::default();
1236 churn_files.insert(
1237 std::path::PathBuf::from("/src/frequent.ts"),
1238 crate::churn::FileChurn {
1239 path: std::path::PathBuf::from("/src/frequent.ts"),
1240 commits: 10,
1241 weighted_commits: 7.0,
1242 lines_added: 150,
1243 lines_deleted: 40,
1244 trend: crate::churn::ChurnTrend::Stable,
1245 authors: rustc_hash::FxHashMap::default(),
1246 },
1247 );
1248 churn_files.insert(
1249 std::path::PathBuf::from("/src/rare.ts"),
1250 crate::churn::FileChurn {
1251 path: std::path::PathBuf::from("/src/rare.ts"),
1252 commits: 1, weighted_commits: 0.9,
1254 lines_added: 10,
1255 lines_deleted: 2,
1256 trend: crate::churn::ChurnTrend::Cooling,
1257 authors: rustc_hash::FxHashMap::default(),
1258 },
1259 );
1260
1261 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 5);
1262 assert!((max_w - 7.0).abs() < f64::EPSILON);
1263 assert!((max_d - 0.4).abs() < f64::EPSILON);
1264 }
1265
1266 #[test]
1267 fn normalization_maxima_file_score_without_churn() {
1268 let scores = vec![FileHealthScore {
1269 path: std::path::PathBuf::from("/src/no_churn.ts"),
1270 fan_in: 0,
1271 fan_out: 0,
1272 dead_code_ratio: 0.0,
1273 complexity_density: 5.0,
1274 maintainability_index: 30.0,
1275 total_cyclomatic: 100,
1276 total_cognitive: 80,
1277 function_count: 20,
1278 lines: 500,
1279 crap_max: 0.0,
1280 crap_above_threshold: 0,
1281 crap_exempted: 0,
1282 crap_suppressed: 0,
1283 crap_unsuppressed_max: None,
1284 crap_unsuppressed_effective_threshold: None,
1285 crap_effective_threshold: None,
1286 }];
1287 let churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1288 rustc_hash::FxHashMap::default();
1289
1290 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 1);
1291 assert!((max_w).abs() < f64::EPSILON);
1292 assert!((max_d).abs() < f64::EPSILON);
1293 }
1294
1295 #[test]
1296 fn normalization_maxima_min_commits_zero() {
1297 let scores = vec![FileHealthScore {
1298 path: std::path::PathBuf::from("/src/foo.ts"),
1299 fan_in: 0,
1300 fan_out: 0,
1301 dead_code_ratio: 0.0,
1302 complexity_density: 0.3,
1303 maintainability_index: 90.0,
1304 total_cyclomatic: 3,
1305 total_cognitive: 2,
1306 function_count: 1,
1307 lines: 10,
1308 crap_max: 0.0,
1309 crap_above_threshold: 0,
1310 crap_exempted: 0,
1311 crap_suppressed: 0,
1312 crap_unsuppressed_max: None,
1313 crap_unsuppressed_effective_threshold: None,
1314 crap_effective_threshold: None,
1315 }];
1316 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1317 rustc_hash::FxHashMap::default();
1318 churn_files.insert(
1319 std::path::PathBuf::from("/src/foo.ts"),
1320 crate::churn::FileChurn {
1321 path: std::path::PathBuf::from("/src/foo.ts"),
1322 commits: 0,
1323 weighted_commits: 0.0,
1324 lines_added: 0,
1325 lines_deleted: 0,
1326 trend: crate::churn::ChurnTrend::Stable,
1327 authors: rustc_hash::FxHashMap::default(),
1328 },
1329 );
1330
1331 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 0);
1332 assert!((max_w).abs() < f64::EPSILON);
1333 assert!((max_d - 0.3).abs() < f64::EPSILON);
1334 }
1335
1336 #[test]
1337 fn normalization_maxima_exactly_at_threshold() {
1338 let scores = vec![FileHealthScore {
1339 path: std::path::PathBuf::from("/src/foo.ts"),
1340 fan_in: 0,
1341 fan_out: 0,
1342 dead_code_ratio: 0.0,
1343 complexity_density: 1.5,
1344 maintainability_index: 65.0,
1345 total_cyclomatic: 25,
1346 total_cognitive: 18,
1347 function_count: 5,
1348 lines: 120,
1349 crap_max: 0.0,
1350 crap_above_threshold: 0,
1351 crap_exempted: 0,
1352 crap_suppressed: 0,
1353 crap_unsuppressed_max: None,
1354 crap_unsuppressed_effective_threshold: None,
1355 crap_effective_threshold: None,
1356 }];
1357 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1358 rustc_hash::FxHashMap::default();
1359 churn_files.insert(
1360 std::path::PathBuf::from("/src/foo.ts"),
1361 crate::churn::FileChurn {
1362 path: std::path::PathBuf::from("/src/foo.ts"),
1363 commits: 3, weighted_commits: 2.8,
1365 lines_added: 60,
1366 lines_deleted: 15,
1367 trend: crate::churn::ChurnTrend::Stable,
1368 authors: rustc_hash::FxHashMap::default(),
1369 },
1370 );
1371
1372 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1373 assert!((max_w - 2.8).abs() < f64::EPSILON);
1374 assert!((max_d - 1.5).abs() < f64::EPSILON);
1375 }
1376
1377 #[test]
1378 fn excluded_workspace_and_glob_combined() {
1379 let path = std::path::Path::new("/project/packages/a/src/generated/types.ts");
1380 let root = std::path::Path::new("/project");
1381 let ws_roots: crate::workspace_scope::WorkspaceScope =
1382 vec![std::path::PathBuf::from("/project/packages/a")].into();
1383 let mut builder = globset::GlobSetBuilder::new();
1384 builder.add(globset::Glob::new("**/generated/**").unwrap());
1385 let ignore_set = builder.build().unwrap();
1386
1387 assert!(is_excluded_from_hotspots(
1388 path,
1389 root,
1390 &ignore_set,
1391 Some(&ws_roots)
1392 ));
1393 }
1394
1395 #[test]
1396 fn excluded_workspace_match_but_glob_no_match() {
1397 let path = std::path::Path::new("/project/packages/a/src/index.ts");
1398 let root = std::path::Path::new("/project");
1399 let ws_roots: crate::workspace_scope::WorkspaceScope =
1400 vec![std::path::PathBuf::from("/project/packages/a")].into();
1401 let mut builder = globset::GlobSetBuilder::new();
1402 builder.add(globset::Glob::new("**/generated/**").unwrap());
1403 let ignore_set = builder.build().unwrap();
1404
1405 assert!(!is_excluded_from_hotspots(
1406 path,
1407 root,
1408 &ignore_set,
1409 Some(&ws_roots)
1410 ));
1411 }
1412
1413 #[test]
1414 fn excluded_path_equals_root() {
1415 let path = std::path::Path::new("/project");
1416 let root = std::path::Path::new("/project");
1417 let ignore_set = globset::GlobSet::empty();
1418
1419 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1420 }
1421
1422 #[test]
1423 fn excluded_path_outside_root() {
1424 let path = std::path::Path::new("/other/src/foo.ts");
1425 let root = std::path::Path::new("/project");
1426 let mut builder = globset::GlobSetBuilder::new();
1427 builder.add(globset::Glob::new("src/foo.ts").unwrap());
1428 let ignore_set = builder.build().unwrap();
1429
1430 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1431 }
1432
1433 #[test]
1434 fn excluded_multiple_globs_first_matches() {
1435 let path = std::path::Path::new("/project/dist/bundle.js");
1436 let root = std::path::Path::new("/project");
1437 let mut builder = globset::GlobSetBuilder::new();
1438 builder.add(globset::Glob::new("dist/**").unwrap());
1439 builder.add(globset::Glob::new("node_modules/**").unwrap());
1440 let ignore_set = builder.build().unwrap();
1441
1442 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
1443 }
1444
1445 #[test]
1446 fn excluded_multiple_globs_second_matches() {
1447 let path = std::path::Path::new("/project/node_modules/lodash/index.js");
1448 let root = std::path::Path::new("/project");
1449 let mut builder = globset::GlobSetBuilder::new();
1450 builder.add(globset::Glob::new("dist/**").unwrap());
1451 builder.add(globset::Glob::new("node_modules/**").unwrap());
1452 let ignore_set = builder.build().unwrap();
1453
1454 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
1455 }
1456
1457 #[test]
1458 fn excluded_multiple_globs_none_matches() {
1459 let path = std::path::Path::new("/project/src/app.ts");
1460 let root = std::path::Path::new("/project");
1461 let mut builder = globset::GlobSetBuilder::new();
1462 builder.add(globset::Glob::new("dist/**").unwrap());
1463 builder.add(globset::Glob::new("node_modules/**").unwrap());
1464 let ignore_set = builder.build().unwrap();
1465
1466 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1467 }
1468}