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 =
435 load_ownership_codeowners(opts, &config.root, config.codeowners.as_deref());
436 let now_secs = churn_result.clock.epoch_secs();
440 let ownership_ctx = bot_globs_owned.as_ref().map(|bot_globs| OwnershipContext {
441 author_pool: &churn_result.author_pool,
442 bot_globs,
443 codeowners: codeowners_owned.as_ref(),
444 email_mode: opts.ownership_emails.unwrap_or(ownership_cfg.email_mode),
445 now_secs,
446 });
447
448 let (mut hotspot_entries, files_excluded) = collect_hotspot_entries(&HotspotEntryCtx {
449 file_scores,
450 root: &config.root,
451 ignore_set,
452 ws_roots,
453 churn_files: &churn_result.files,
454 min_commits,
455 max_weighted,
456 max_density,
457 ownership_ctx: ownership_ctx.as_ref(),
458 dispersion,
459 });
460
461 hotspot_entries.sort_by(|a, b| {
462 b.score
463 .partial_cmp(&a.score)
464 .unwrap_or(std::cmp::Ordering::Equal)
465 });
466
467 let files_analyzed = hotspot_entries.len();
468 let summary = HotspotSummary {
469 since: since.display,
470 min_commits,
471 files_analyzed,
472 files_excluded,
473 shallow_clone,
474 clock: Some(clock_provenance(churn_result.clock)),
475 };
476
477 (hotspot_entries, Some(summary))
478}
479
480fn clock_provenance(clock: crate::clock::AnalysisClock) -> ClockProvenance {
486 ClockProvenance {
487 source: match clock.source() {
488 crate::clock::AnalysisClockSource::Environment => ClockSource::Environment,
489 crate::clock::AnalysisClockSource::HeadCommit => ClockSource::HeadCommit,
490 crate::clock::AnalysisClockSource::WallClock => ClockSource::WallClock,
491 },
492 epoch_secs: clock.epoch_secs(),
493 reproducible: clock.is_reproducible(),
494 }
495}
496
497fn warn_unpinned_clock(opts: &HealthOptions<'_>, clock: crate::clock::AnalysisClock) {
506 if clock.is_reproducible() {
507 return;
508 }
509 if !opts.quiet {
510 eprintln!(
511 "Warning: no commit timestamp available, so churn recency and \
512 ownership staleness were measured against the wall clock and will \
513 drift between runs. Set FALLOW_CLOCK_EPOCH to pin them."
514 );
515 }
516 super::diagnostics::record_health_diagnostic(
517 opts.root,
518 None,
519 fallow_types::workspace::WorkspaceDiagnosticKind::UnpinnedClock,
520 );
521}
522
523fn warn_shallow_clone(opts: &HealthOptions<'_>, shallow_clone: bool) {
525 if !shallow_clone {
526 return;
527 }
528 if !opts.quiet {
529 eprintln!(
530 "Warning: shallow clone detected. Hotspot analysis may be incomplete. \
531 Use `git fetch --unshallow` for full history."
532 );
533 if opts.ownership {
534 eprintln!(
535 "Warning: shallow clones inflate single-author dominance, so \
536 ownership signals will be skewed."
537 );
538 }
539 }
540 super::diagnostics::record_health_diagnostic(
541 opts.root,
542 None,
543 fallow_types::workspace::WorkspaceDiagnosticKind::ShallowClone {
544 ownership_requested: opts.ownership,
545 },
546 );
547}
548
549fn load_ownership_bot_globs(
551 opts: &HealthOptions<'_>,
552 ownership_cfg: &fallow_config::OwnershipConfig,
553) -> Option<globset::GlobSet> {
554 opts.ownership.then(|| {
555 compile_bot_globs(&ownership_cfg.bot_patterns).unwrap_or_else(|e| {
556 if !opts.quiet {
557 eprintln!("Warning: invalid bot pattern in health.ownership.botPatterns: {e}");
558 }
559 super::diagnostics::record_health_diagnostic(
560 opts.root,
561 None,
562 fallow_types::workspace::WorkspaceDiagnosticKind::OwnershipUnavailable {
563 cause: "invalid-bot-pattern".to_owned(),
564 error: e.to_string(),
565 },
566 );
567 globset::GlobSet::empty()
568 })
569 })
570}
571
572fn load_ownership_codeowners(
577 opts: &HealthOptions<'_>,
578 root: &std::path::Path,
579 configured: Option<&str>,
580) -> Option<crate::codeowners::CodeOwners> {
581 opts.ownership
582 .then(
583 || match crate::codeowners::CodeOwners::load(root, configured) {
584 Ok(co) => Some(co),
585 Err(e) => {
586 if !e.contains("no CODEOWNERS file found") {
590 if !opts.quiet {
591 eprintln!("Warning: failed to parse CODEOWNERS: {e}");
592 }
593 super::diagnostics::record_health_diagnostic(
594 root,
595 None,
596 fallow_types::workspace::WorkspaceDiagnosticKind::OwnershipUnavailable {
597 cause: "codeowners-parse-failed".to_owned(),
598 error: e,
599 },
600 );
601 }
602 None
603 }
604 },
605 )
606 .flatten()
607}
608
609struct HotspotEntryCtx<'a> {
611 file_scores: &'a [FileHealthScore],
612 root: &'a std::path::Path,
613 ignore_set: &'a globset::GlobSet,
614 ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
615 churn_files: &'a rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn>,
616 min_commits: u32,
617 max_weighted: f64,
618 max_density: f64,
619 ownership_ctx: Option<&'a OwnershipContext<'a>>,
620 dispersion: Option<
621 &'a rustc_hash::FxHashMap<std::path::PathBuf, crate::change_coupling::FileDispersion>,
622 >,
623}
624
625fn collect_hotspot_entries(ctx: &HotspotEntryCtx<'_>) -> (Vec<HotspotEntry>, usize) {
628 let mut hotspot_entries = Vec::new();
629 let mut files_excluded: usize = 0;
630
631 for score in ctx.file_scores {
632 if is_excluded_from_hotspots(&score.path, ctx.root, ctx.ignore_set, ctx.ws_roots) {
633 continue;
634 }
635
636 let Some(churn) = ctx.churn_files.get(&score.path) else {
637 continue;
638 };
639 if churn.commits < ctx.min_commits {
640 files_excluded += 1;
641 continue;
642 }
643
644 let relative = score.path.strip_prefix(ctx.root).unwrap_or(&score.path);
645 let ownership = ctx
646 .ownership_ctx
647 .and_then(|own| compute_ownership_with_identities(churn, relative, own))
648 .map(|owned| owned.metrics);
649 let dispersion = ctx.dispersion.and_then(|map| map.get(&score.path));
650
651 hotspot_entries.push(HotspotEntry {
652 path: score.path.clone(),
653 score: compute_hotspot_score(
654 churn.weighted_commits,
655 ctx.max_weighted,
656 score.complexity_density,
657 ctx.max_density,
658 ),
659 commits: churn.commits,
660 weighted_commits: churn.weighted_commits,
661 lines_added: churn.lines_added,
662 lines_deleted: churn.lines_deleted,
663 complexity_density: score.complexity_density,
664 fan_in: score.fan_in,
665 trend: churn.trend,
666 median_files_per_commit: dispersion
667 .map(|d| round_one_decimal(d.median_files_per_commit)),
668 median_lines_per_commit: dispersion
669 .map(|d| round_one_decimal(d.median_lines_per_commit)),
670 ownership,
671 is_test_path: is_test_path(ctx.root, relative),
672 });
673 }
674
675 (hotspot_entries, files_excluded)
676}
677
678fn round_one_decimal(value: f64) -> f64 {
679 (value * 10.0).round() / 10.0
680}
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685
686 fn target_churn_options(root: &std::path::Path) -> TargetChurnOptions<'_> {
687 TargetChurnOptions {
688 root,
689 target: std::path::Path::new("src/app.ts"),
690 cache_dir: root.join(".fallow"),
691 no_cache: true,
692 since: None,
693 min_commits: None,
694 }
695 }
696
697 fn churn_result(root: &std::path::Path, commits: u32) -> crate::churn::ChurnResult {
698 let path = root.join("src/app.ts");
699 let mut files = rustc_hash::FxHashMap::default();
700 files.insert(
701 path.clone(),
702 crate::churn::FileChurn {
703 path,
704 commits,
705 weighted_commits: 2.5,
706 lines_added: 20,
707 lines_deleted: 5,
708 trend: crate::churn::ChurnTrend::Accelerating,
709 authors: rustc_hash::FxHashMap::default(),
710 },
711 );
712 crate::churn::ChurnResult {
713 files,
714 shallow_clone: false,
715 author_pool: Vec::new(),
716 clock: crate::clock::AnalysisClock::pinned(1_788_782_400),
717 git_log_bytes: 0,
718 commits: Vec::new(),
719 }
720 }
721
722 #[test]
723 fn target_churn_returns_only_the_requested_qualifying_file() {
724 let root = std::path::Path::new("/project");
725 let options = target_churn_options(root);
726
727 let outcome = analyze_target_churn_with(
728 &options,
729 |_| true,
730 |_, _, _, _| Some((churn_result(root, 4), false)),
731 )
732 .unwrap();
733
734 let TargetChurnOutcome::Found(evidence) = outcome else {
735 panic!("expected qualifying churn evidence");
736 };
737 assert_eq!(evidence.file.path, root.join("src/app.ts"));
738 assert_eq!(evidence.file.commits, 4);
739 assert_eq!(evidence.min_commits, 3);
740 assert_eq!(evidence.since.display, "6 months");
741 }
742
743 #[test]
744 fn target_churn_distinguishes_no_qualifying_history() {
745 let root = std::path::Path::new("/project");
746 let options = target_churn_options(root);
747
748 let outcome = analyze_target_churn_with(
749 &options,
750 |_| true,
751 |_, _, _, _| Some((churn_result(root, 2), false)),
752 )
753 .unwrap();
754
755 assert!(matches!(
756 outcome,
757 TargetChurnOutcome::NoQualifyingChurn {
758 observed_commits: Some(2),
759 min_commits: 3,
760 ..
761 }
762 ));
763 }
764
765 #[test]
766 fn target_churn_distinguishes_git_unavailable() {
767 let root = std::path::Path::new("/project");
768 let options = target_churn_options(root);
769
770 let outcome = analyze_target_churn_with(
771 &options,
772 |_| false,
773 |_, _, _, _| panic!("churn analysis must not run without git"),
774 )
775 .unwrap();
776
777 assert!(matches!(outcome, TargetChurnOutcome::Unavailable { .. }));
778 }
779
780 #[test]
781 fn target_churn_surfaces_analysis_failure() {
782 let root = std::path::Path::new("/project");
783 let options = target_churn_options(root);
784
785 let error = analyze_target_churn_with(&options, |_| true, |_, _, _, _| None)
786 .expect_err("failed git analysis must remain explicit");
787
788 assert!(error.contains("git churn analysis failed"));
789 }
790
791 #[test]
792 fn hotspot_score_both_maxima_zero() {
793 assert!((compute_hotspot_score(0.0, 0.0, 0.0, 0.0)).abs() < f64::EPSILON);
794 }
795
796 #[test]
797 fn hotspot_score_max_weighted_zero() {
798 assert!((compute_hotspot_score(5.0, 0.0, 0.5, 1.0)).abs() < f64::EPSILON);
799 }
800
801 #[test]
802 fn hotspot_score_max_density_zero() {
803 assert!((compute_hotspot_score(5.0, 10.0, 0.0, 0.0)).abs() < f64::EPSILON);
804 }
805
806 #[test]
807 fn hotspot_score_equal_normalization() {
808 let score = compute_hotspot_score(10.0, 10.0, 2.0, 2.0);
809 assert!((score - 100.0).abs() < f64::EPSILON);
810 }
811
812 #[test]
813 fn hotspot_score_half_values() {
814 let score = compute_hotspot_score(5.0, 10.0, 1.0, 2.0);
815 assert!((score - 25.0).abs() < f64::EPSILON);
816 }
817
818 #[test]
819 fn excluded_no_filters() {
820 let path = std::path::Path::new("/project/src/foo.ts");
821 let root = std::path::Path::new("/project");
822 let ignore_set = globset::GlobSet::empty();
823
824 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
825 }
826
827 #[test]
828 fn excluded_workspace_filter_mismatch() {
829 let path = std::path::Path::new("/project/packages/b/src/foo.ts");
830 let root = std::path::Path::new("/project");
831 let ws_roots: crate::workspace_scope::WorkspaceScope =
832 vec![std::path::PathBuf::from("/project/packages/a")].into();
833 let ignore_set = globset::GlobSet::empty();
834
835 assert!(is_excluded_from_hotspots(
836 path,
837 root,
838 &ignore_set,
839 Some(&ws_roots)
840 ));
841 }
842
843 #[test]
844 fn excluded_workspace_filter_match() {
845 let path = std::path::Path::new("/project/packages/a/src/foo.ts");
846 let root = std::path::Path::new("/project");
847 let ws_roots: crate::workspace_scope::WorkspaceScope =
848 vec![std::path::PathBuf::from("/project/packages/a")].into();
849 let ignore_set = globset::GlobSet::empty();
850
851 assert!(!is_excluded_from_hotspots(
852 path,
853 root,
854 &ignore_set,
855 Some(&ws_roots)
856 ));
857 }
858
859 #[test]
860 fn excluded_matching_glob() {
861 let path = std::path::Path::new("/project/src/generated/types.ts");
862 let root = std::path::Path::new("/project");
863 let mut builder = globset::GlobSetBuilder::new();
864 builder.add(globset::Glob::new("src/generated/**").unwrap());
865 let ignore_set = builder.build().unwrap();
866
867 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
868 }
869
870 #[test]
871 fn excluded_non_matching_glob() {
872 let path = std::path::Path::new("/project/src/components/Button.tsx");
873 let root = std::path::Path::new("/project");
874 let mut builder = globset::GlobSetBuilder::new();
875 builder.add(globset::Glob::new("src/generated/**").unwrap());
876 let ignore_set = builder.build().unwrap();
877
878 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
879 }
880
881 #[test]
882 fn normalization_maxima_empty_input() {
883 let scores: Vec<FileHealthScore> = vec![];
884 let churn_files = rustc_hash::FxHashMap::default();
885
886 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
887 assert!((max_w).abs() < f64::EPSILON);
888 assert!((max_d).abs() < f64::EPSILON);
889 }
890
891 #[test]
892 fn normalization_maxima_single_file() {
893 let scores = vec![FileHealthScore {
894 path: std::path::PathBuf::from("/src/foo.ts"),
895 fan_in: 0,
896 fan_out: 0,
897 dead_code_ratio: 0.0,
898 complexity_density: 0.75,
899 maintainability_index: 80.0,
900 total_cyclomatic: 15,
901 total_cognitive: 10,
902 function_count: 3,
903 lines: 20,
904 crap_max: 0.0,
905 crap_above_threshold: 0,
906 crap_exempted: 0,
907 crap_suppressed: 0,
908 crap_unsuppressed_max: None,
909 crap_unsuppressed_effective_threshold: None,
910 crap_effective_threshold: None,
911 }];
912 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
913 rustc_hash::FxHashMap::default();
914 churn_files.insert(
915 std::path::PathBuf::from("/src/foo.ts"),
916 crate::churn::FileChurn {
917 path: std::path::PathBuf::from("/src/foo.ts"),
918 commits: 5,
919 weighted_commits: 4.2,
920 lines_added: 100,
921 lines_deleted: 20,
922 trend: crate::churn::ChurnTrend::Stable,
923 authors: rustc_hash::FxHashMap::default(),
924 },
925 );
926
927 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
928 assert!((max_w - 4.2).abs() < f64::EPSILON);
929 assert!((max_d - 0.75).abs() < f64::EPSILON);
930 }
931
932 #[test]
936 fn normalization_maxima_ignore_crap_exemption_fields() {
937 let base = FileHealthScore {
938 path: std::path::PathBuf::from("/src/foo.ts"),
939 fan_in: 0,
940 fan_out: 0,
941 dead_code_ratio: 0.0,
942 complexity_density: 0.75,
943 maintainability_index: 80.0,
944 total_cyclomatic: 15,
945 total_cognitive: 10,
946 function_count: 3,
947 lines: 20,
948 crap_max: 110.0,
949 crap_above_threshold: 2,
950 crap_exempted: 0,
951 crap_suppressed: 0,
952 crap_unsuppressed_max: None,
953 crap_unsuppressed_effective_threshold: None,
954 crap_effective_threshold: None,
955 };
956 let exempt = FileHealthScore {
957 crap_above_threshold: 0,
958 crap_exempted: 2,
959 crap_effective_threshold: Some(500.0),
960 ..base.clone()
961 };
962 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
963 rustc_hash::FxHashMap::default();
964 churn_files.insert(
965 std::path::PathBuf::from("/src/foo.ts"),
966 crate::churn::FileChurn {
967 path: std::path::PathBuf::from("/src/foo.ts"),
968 commits: 5,
969 weighted_commits: 4.2,
970 lines_added: 100,
971 lines_deleted: 20,
972 trend: crate::churn::ChurnTrend::Stable,
973 authors: rustc_hash::FxHashMap::default(),
974 },
975 );
976
977 let flagged = compute_normalization_maxima(&[base], &churn_files, 3);
978 let exempted = compute_normalization_maxima(&[exempt], &churn_files, 3);
979 assert_eq!(flagged, exempted);
980 }
981
982 #[test]
983 fn normalization_maxima_below_min_commits() {
984 let scores = vec![FileHealthScore {
985 path: std::path::PathBuf::from("/src/foo.ts"),
986 fan_in: 0,
987 fan_out: 0,
988 dead_code_ratio: 0.0,
989 complexity_density: 0.75,
990 maintainability_index: 80.0,
991 total_cyclomatic: 15,
992 total_cognitive: 10,
993 function_count: 3,
994 lines: 20,
995 crap_max: 0.0,
996 crap_above_threshold: 0,
997 crap_exempted: 0,
998 crap_suppressed: 0,
999 crap_unsuppressed_max: None,
1000 crap_unsuppressed_effective_threshold: None,
1001 crap_effective_threshold: None,
1002 }];
1003 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1004 rustc_hash::FxHashMap::default();
1005 churn_files.insert(
1006 std::path::PathBuf::from("/src/foo.ts"),
1007 crate::churn::FileChurn {
1008 path: std::path::PathBuf::from("/src/foo.ts"),
1009 commits: 2, weighted_commits: 4.2,
1011 lines_added: 100,
1012 lines_deleted: 20,
1013 trend: crate::churn::ChurnTrend::Stable,
1014 authors: rustc_hash::FxHashMap::default(),
1015 },
1016 );
1017
1018 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1019 assert!((max_w).abs() < f64::EPSILON);
1020 assert!((max_d).abs() < f64::EPSILON);
1021 }
1022
1023 #[test]
1024 fn normalization_maxima_all_zeros() {
1025 let scores = vec![FileHealthScore {
1026 path: std::path::PathBuf::from("/src/foo.ts"),
1027 fan_in: 0,
1028 fan_out: 0,
1029 dead_code_ratio: 0.0,
1030 complexity_density: 0.0,
1031 maintainability_index: 100.0,
1032 total_cyclomatic: 0,
1033 total_cognitive: 0,
1034 function_count: 1,
1035 lines: 10,
1036 crap_max: 0.0,
1037 crap_above_threshold: 0,
1038 crap_exempted: 0,
1039 crap_suppressed: 0,
1040 crap_unsuppressed_max: None,
1041 crap_unsuppressed_effective_threshold: None,
1042 crap_effective_threshold: None,
1043 }];
1044 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1045 rustc_hash::FxHashMap::default();
1046 churn_files.insert(
1047 std::path::PathBuf::from("/src/foo.ts"),
1048 crate::churn::FileChurn {
1049 path: std::path::PathBuf::from("/src/foo.ts"),
1050 commits: 5,
1051 weighted_commits: 0.0,
1052 lines_added: 0,
1053 lines_deleted: 0,
1054 trend: crate::churn::ChurnTrend::Stable,
1055 authors: rustc_hash::FxHashMap::default(),
1056 },
1057 );
1058
1059 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1060 assert!((max_w).abs() < f64::EPSILON);
1061 assert!((max_d).abs() < f64::EPSILON);
1062 }
1063
1064 #[test]
1065 fn hotspot_score_high_churn_low_complexity() {
1066 let score = compute_hotspot_score(10.0, 10.0, 0.1, 1.0);
1067 assert!((score - 10.0).abs() < f64::EPSILON);
1068 }
1069
1070 #[test]
1071 fn hotspot_score_low_churn_high_complexity() {
1072 let score = compute_hotspot_score(1.0, 10.0, 2.0, 2.0);
1073 assert!((score - 10.0).abs() < f64::EPSILON);
1074 }
1075
1076 #[test]
1077 fn hotspot_score_rounding() {
1078 let score = compute_hotspot_score(1.0, 3.0, 1.0, 3.0);
1079 assert!((score - 11.1).abs() < f64::EPSILON);
1080 }
1081
1082 #[test]
1083 fn hotspot_score_very_small_values() {
1084 let score = compute_hotspot_score(0.01, 100.0, 0.001, 10.0);
1085 assert!((score).abs() < 0.1);
1086 }
1087
1088 #[test]
1089 fn hotspot_score_weighted_exceeds_max() {
1090 let score = compute_hotspot_score(15.0, 10.0, 1.0, 2.0);
1091 assert!((score - 75.0).abs() < f64::EPSILON);
1092 }
1093
1094 #[test]
1095 fn normalization_maxima_multiple_files_picks_max() {
1096 let scores = vec![
1097 FileHealthScore {
1098 path: std::path::PathBuf::from("/src/a.ts"),
1099 fan_in: 0,
1100 fan_out: 0,
1101 dead_code_ratio: 0.0,
1102 complexity_density: 0.5,
1103 maintainability_index: 80.0,
1104 total_cyclomatic: 10,
1105 total_cognitive: 5,
1106 function_count: 2,
1107 lines: 50,
1108 crap_max: 0.0,
1109 crap_above_threshold: 0,
1110 crap_exempted: 0,
1111 crap_suppressed: 0,
1112 crap_unsuppressed_max: None,
1113 crap_unsuppressed_effective_threshold: None,
1114 crap_effective_threshold: None,
1115 },
1116 FileHealthScore {
1117 path: std::path::PathBuf::from("/src/b.ts"),
1118 fan_in: 0,
1119 fan_out: 0,
1120 dead_code_ratio: 0.0,
1121 complexity_density: 1.2, maintainability_index: 60.0,
1123 total_cyclomatic: 30,
1124 total_cognitive: 20,
1125 function_count: 5,
1126 lines: 100,
1127 crap_max: 0.0,
1128 crap_above_threshold: 0,
1129 crap_exempted: 0,
1130 crap_suppressed: 0,
1131 crap_unsuppressed_max: None,
1132 crap_unsuppressed_effective_threshold: None,
1133 crap_effective_threshold: None,
1134 },
1135 FileHealthScore {
1136 path: std::path::PathBuf::from("/src/c.ts"),
1137 fan_in: 0,
1138 fan_out: 0,
1139 dead_code_ratio: 0.0,
1140 complexity_density: 0.8,
1141 maintainability_index: 70.0,
1142 total_cyclomatic: 20,
1143 total_cognitive: 15,
1144 function_count: 4,
1145 lines: 80,
1146 crap_max: 0.0,
1147 crap_above_threshold: 0,
1148 crap_exempted: 0,
1149 crap_suppressed: 0,
1150 crap_unsuppressed_max: None,
1151 crap_unsuppressed_effective_threshold: None,
1152 crap_effective_threshold: None,
1153 },
1154 ];
1155 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1156 rustc_hash::FxHashMap::default();
1157 churn_files.insert(
1158 std::path::PathBuf::from("/src/a.ts"),
1159 crate::churn::FileChurn {
1160 path: std::path::PathBuf::from("/src/a.ts"),
1161 commits: 5,
1162 weighted_commits: 3.0,
1163 lines_added: 50,
1164 lines_deleted: 10,
1165 trend: crate::churn::ChurnTrend::Stable,
1166 authors: rustc_hash::FxHashMap::default(),
1167 },
1168 );
1169 churn_files.insert(
1170 std::path::PathBuf::from("/src/b.ts"),
1171 crate::churn::FileChurn {
1172 path: std::path::PathBuf::from("/src/b.ts"),
1173 commits: 10,
1174 weighted_commits: 8.5, lines_added: 200,
1176 lines_deleted: 50,
1177 trend: crate::churn::ChurnTrend::Accelerating,
1178 authors: rustc_hash::FxHashMap::default(),
1179 },
1180 );
1181 churn_files.insert(
1182 std::path::PathBuf::from("/src/c.ts"),
1183 crate::churn::FileChurn {
1184 path: std::path::PathBuf::from("/src/c.ts"),
1185 commits: 7,
1186 weighted_commits: 5.0,
1187 lines_added: 100,
1188 lines_deleted: 30,
1189 trend: crate::churn::ChurnTrend::Cooling,
1190 authors: rustc_hash::FxHashMap::default(),
1191 },
1192 );
1193
1194 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1195 assert!((max_w - 8.5).abs() < f64::EPSILON);
1196 assert!((max_d - 1.2).abs() < f64::EPSILON);
1197 }
1198
1199 #[test]
1200 fn normalization_maxima_mixed_above_and_below_threshold() {
1201 let scores = vec![
1202 FileHealthScore {
1203 path: std::path::PathBuf::from("/src/frequent.ts"),
1204 fan_in: 0,
1205 fan_out: 0,
1206 dead_code_ratio: 0.0,
1207 complexity_density: 0.4,
1208 maintainability_index: 85.0,
1209 total_cyclomatic: 8,
1210 total_cognitive: 4,
1211 function_count: 2,
1212 lines: 40,
1213 crap_max: 0.0,
1214 crap_above_threshold: 0,
1215 crap_exempted: 0,
1216 crap_suppressed: 0,
1217 crap_unsuppressed_max: None,
1218 crap_unsuppressed_effective_threshold: None,
1219 crap_effective_threshold: None,
1220 },
1221 FileHealthScore {
1222 path: std::path::PathBuf::from("/src/rare.ts"),
1223 fan_in: 0,
1224 fan_out: 0,
1225 dead_code_ratio: 0.0,
1226 complexity_density: 2.0, maintainability_index: 50.0,
1228 total_cyclomatic: 40,
1229 total_cognitive: 30,
1230 function_count: 8,
1231 lines: 200,
1232 crap_max: 0.0,
1233 crap_above_threshold: 0,
1234 crap_exempted: 0,
1235 crap_suppressed: 0,
1236 crap_unsuppressed_max: None,
1237 crap_unsuppressed_effective_threshold: None,
1238 crap_effective_threshold: None,
1239 },
1240 ];
1241 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1242 rustc_hash::FxHashMap::default();
1243 churn_files.insert(
1244 std::path::PathBuf::from("/src/frequent.ts"),
1245 crate::churn::FileChurn {
1246 path: std::path::PathBuf::from("/src/frequent.ts"),
1247 commits: 10,
1248 weighted_commits: 7.0,
1249 lines_added: 150,
1250 lines_deleted: 40,
1251 trend: crate::churn::ChurnTrend::Stable,
1252 authors: rustc_hash::FxHashMap::default(),
1253 },
1254 );
1255 churn_files.insert(
1256 std::path::PathBuf::from("/src/rare.ts"),
1257 crate::churn::FileChurn {
1258 path: std::path::PathBuf::from("/src/rare.ts"),
1259 commits: 1, weighted_commits: 0.9,
1261 lines_added: 10,
1262 lines_deleted: 2,
1263 trend: crate::churn::ChurnTrend::Cooling,
1264 authors: rustc_hash::FxHashMap::default(),
1265 },
1266 );
1267
1268 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 5);
1269 assert!((max_w - 7.0).abs() < f64::EPSILON);
1270 assert!((max_d - 0.4).abs() < f64::EPSILON);
1271 }
1272
1273 #[test]
1274 fn normalization_maxima_file_score_without_churn() {
1275 let scores = vec![FileHealthScore {
1276 path: std::path::PathBuf::from("/src/no_churn.ts"),
1277 fan_in: 0,
1278 fan_out: 0,
1279 dead_code_ratio: 0.0,
1280 complexity_density: 5.0,
1281 maintainability_index: 30.0,
1282 total_cyclomatic: 100,
1283 total_cognitive: 80,
1284 function_count: 20,
1285 lines: 500,
1286 crap_max: 0.0,
1287 crap_above_threshold: 0,
1288 crap_exempted: 0,
1289 crap_suppressed: 0,
1290 crap_unsuppressed_max: None,
1291 crap_unsuppressed_effective_threshold: None,
1292 crap_effective_threshold: None,
1293 }];
1294 let churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1295 rustc_hash::FxHashMap::default();
1296
1297 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 1);
1298 assert!((max_w).abs() < f64::EPSILON);
1299 assert!((max_d).abs() < f64::EPSILON);
1300 }
1301
1302 #[test]
1303 fn normalization_maxima_min_commits_zero() {
1304 let scores = vec![FileHealthScore {
1305 path: std::path::PathBuf::from("/src/foo.ts"),
1306 fan_in: 0,
1307 fan_out: 0,
1308 dead_code_ratio: 0.0,
1309 complexity_density: 0.3,
1310 maintainability_index: 90.0,
1311 total_cyclomatic: 3,
1312 total_cognitive: 2,
1313 function_count: 1,
1314 lines: 10,
1315 crap_max: 0.0,
1316 crap_above_threshold: 0,
1317 crap_exempted: 0,
1318 crap_suppressed: 0,
1319 crap_unsuppressed_max: None,
1320 crap_unsuppressed_effective_threshold: None,
1321 crap_effective_threshold: None,
1322 }];
1323 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1324 rustc_hash::FxHashMap::default();
1325 churn_files.insert(
1326 std::path::PathBuf::from("/src/foo.ts"),
1327 crate::churn::FileChurn {
1328 path: std::path::PathBuf::from("/src/foo.ts"),
1329 commits: 0,
1330 weighted_commits: 0.0,
1331 lines_added: 0,
1332 lines_deleted: 0,
1333 trend: crate::churn::ChurnTrend::Stable,
1334 authors: rustc_hash::FxHashMap::default(),
1335 },
1336 );
1337
1338 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 0);
1339 assert!((max_w).abs() < f64::EPSILON);
1340 assert!((max_d - 0.3).abs() < f64::EPSILON);
1341 }
1342
1343 #[test]
1344 fn normalization_maxima_exactly_at_threshold() {
1345 let scores = vec![FileHealthScore {
1346 path: std::path::PathBuf::from("/src/foo.ts"),
1347 fan_in: 0,
1348 fan_out: 0,
1349 dead_code_ratio: 0.0,
1350 complexity_density: 1.5,
1351 maintainability_index: 65.0,
1352 total_cyclomatic: 25,
1353 total_cognitive: 18,
1354 function_count: 5,
1355 lines: 120,
1356 crap_max: 0.0,
1357 crap_above_threshold: 0,
1358 crap_exempted: 0,
1359 crap_suppressed: 0,
1360 crap_unsuppressed_max: None,
1361 crap_unsuppressed_effective_threshold: None,
1362 crap_effective_threshold: None,
1363 }];
1364 let mut churn_files: rustc_hash::FxHashMap<std::path::PathBuf, crate::churn::FileChurn> =
1365 rustc_hash::FxHashMap::default();
1366 churn_files.insert(
1367 std::path::PathBuf::from("/src/foo.ts"),
1368 crate::churn::FileChurn {
1369 path: std::path::PathBuf::from("/src/foo.ts"),
1370 commits: 3, weighted_commits: 2.8,
1372 lines_added: 60,
1373 lines_deleted: 15,
1374 trend: crate::churn::ChurnTrend::Stable,
1375 authors: rustc_hash::FxHashMap::default(),
1376 },
1377 );
1378
1379 let (max_w, max_d) = compute_normalization_maxima(&scores, &churn_files, 3);
1380 assert!((max_w - 2.8).abs() < f64::EPSILON);
1381 assert!((max_d - 1.5).abs() < f64::EPSILON);
1382 }
1383
1384 #[test]
1385 fn excluded_workspace_and_glob_combined() {
1386 let path = std::path::Path::new("/project/packages/a/src/generated/types.ts");
1387 let root = std::path::Path::new("/project");
1388 let ws_roots: crate::workspace_scope::WorkspaceScope =
1389 vec![std::path::PathBuf::from("/project/packages/a")].into();
1390 let mut builder = globset::GlobSetBuilder::new();
1391 builder.add(globset::Glob::new("**/generated/**").unwrap());
1392 let ignore_set = builder.build().unwrap();
1393
1394 assert!(is_excluded_from_hotspots(
1395 path,
1396 root,
1397 &ignore_set,
1398 Some(&ws_roots)
1399 ));
1400 }
1401
1402 #[test]
1403 fn excluded_workspace_match_but_glob_no_match() {
1404 let path = std::path::Path::new("/project/packages/a/src/index.ts");
1405 let root = std::path::Path::new("/project");
1406 let ws_roots: crate::workspace_scope::WorkspaceScope =
1407 vec![std::path::PathBuf::from("/project/packages/a")].into();
1408 let mut builder = globset::GlobSetBuilder::new();
1409 builder.add(globset::Glob::new("**/generated/**").unwrap());
1410 let ignore_set = builder.build().unwrap();
1411
1412 assert!(!is_excluded_from_hotspots(
1413 path,
1414 root,
1415 &ignore_set,
1416 Some(&ws_roots)
1417 ));
1418 }
1419
1420 #[test]
1421 fn excluded_path_equals_root() {
1422 let path = std::path::Path::new("/project");
1423 let root = std::path::Path::new("/project");
1424 let ignore_set = globset::GlobSet::empty();
1425
1426 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1427 }
1428
1429 #[test]
1430 fn excluded_path_outside_root() {
1431 let path = std::path::Path::new("/other/src/foo.ts");
1432 let root = std::path::Path::new("/project");
1433 let mut builder = globset::GlobSetBuilder::new();
1434 builder.add(globset::Glob::new("src/foo.ts").unwrap());
1435 let ignore_set = builder.build().unwrap();
1436
1437 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1438 }
1439
1440 #[test]
1441 fn excluded_multiple_globs_first_matches() {
1442 let path = std::path::Path::new("/project/dist/bundle.js");
1443 let root = std::path::Path::new("/project");
1444 let mut builder = globset::GlobSetBuilder::new();
1445 builder.add(globset::Glob::new("dist/**").unwrap());
1446 builder.add(globset::Glob::new("node_modules/**").unwrap());
1447 let ignore_set = builder.build().unwrap();
1448
1449 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
1450 }
1451
1452 #[test]
1453 fn excluded_multiple_globs_second_matches() {
1454 let path = std::path::Path::new("/project/node_modules/lodash/index.js");
1455 let root = std::path::Path::new("/project");
1456 let mut builder = globset::GlobSetBuilder::new();
1457 builder.add(globset::Glob::new("dist/**").unwrap());
1458 builder.add(globset::Glob::new("node_modules/**").unwrap());
1459 let ignore_set = builder.build().unwrap();
1460
1461 assert!(is_excluded_from_hotspots(path, root, &ignore_set, None));
1462 }
1463
1464 #[test]
1465 fn excluded_multiple_globs_none_matches() {
1466 let path = std::path::Path::new("/project/src/app.ts");
1467 let root = std::path::Path::new("/project");
1468 let mut builder = globset::GlobSetBuilder::new();
1469 builder.add(globset::Glob::new("dist/**").unwrap());
1470 builder.add(globset::Glob::new("node_modules/**").unwrap());
1471 let ignore_set = builder.build().unwrap();
1472
1473 assert!(!is_excluded_from_hotspots(path, root, &ignore_set, None));
1474 }
1475}