1#![cfg_attr(coverage_nightly, coverage(off))]
2use crate::models::churn::{ChurnSummary, CodeChurnAnalysis, FileChurnMetrics};
41use crate::models::error::TemplateError;
42use chrono::{DateTime, Duration, Utc};
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45use std::process::Command;
46use tracing::info;
47
48pub struct GitAnalysisService;
50
51impl GitAnalysisService {
52 #[must_use]
63 pub fn discover_repository_root(start: &Path) -> Option<PathBuf> {
64 let start = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
67 let mut current: Option<&Path> = Some(start.as_path());
68 while let Some(dir) = current {
69 if dir.join(".git").exists() {
70 return Some(dir.to_path_buf());
71 }
72 current = dir.parent();
73 }
74 None
75 }
76
77 fn scope_within_root(root: &Path, target: &Path) -> Option<PathBuf> {
80 let target = target
81 .canonicalize()
82 .unwrap_or_else(|_| target.to_path_buf());
83 let rel = target.strip_prefix(root).ok()?;
84 if rel.as_os_str().is_empty() {
85 None
86 } else {
87 Some(rel.to_path_buf())
88 }
89 }
90
91 #[inline]
92 #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
93 pub fn analyze_code_churn(
100 project_path: &Path,
101 period_days: u32,
102 ) -> Result<CodeChurnAnalysis, TemplateError> {
103 let repo_root = Self::discover_repository_root(project_path).ok_or_else(|| {
104 TemplateError::NotFound(format!(
105 "No git repository found at {project_path:?} or any of its parent directories"
106 ))
107 })?;
108 let scope = Self::scope_within_root(&repo_root, project_path);
109
110 let epoch = DateTime::from_timestamp(0, 0).unwrap_or_else(Utc::now);
129 let since_str = Duration::try_days(i64::from(period_days))
130 .and_then(|d| Utc::now().checked_sub_signed(d))
131 .filter(|since| *since >= epoch)
132 .map(|since| since.format("%Y-%m-%d").to_string());
133
134 info!("Analyzing code churn for last {} days", period_days);
135
136 let (file_metrics, total_commits) =
137 Self::get_file_metrics(&repo_root, since_str.as_deref(), scope.as_deref())?;
138 let summary = Self::generate_summary(&file_metrics, total_commits);
139
140 Ok(CodeChurnAnalysis {
141 generated_at: Utc::now(),
142 period_days,
143 repository_root: repo_root,
144 files: file_metrics,
145 summary,
146 })
147 }
148
149 fn capture_git_log_output(
165 project_path: &Path,
166 since_date: Option<&str>,
167 scope: Option<&Path>,
168 ) -> Result<Option<String>, TemplateError> {
169 let (tx, rx) = std::sync::mpsc::channel();
170 let project_dir = project_path.to_path_buf();
171 let since = since_date.map(std::string::ToString::to_string);
172 let scope = scope.map(Path::to_path_buf);
173 std::thread::spawn(move || {
174 let result = Self::git_log_numstat_command(since.as_deref(), scope.as_deref())
175 .current_dir(&project_dir)
176 .output();
177 let _ = tx.send(result);
178 });
179
180 let timeout = std::time::Duration::from_secs(60);
181 let output = match rx.recv_timeout(timeout) {
182 Ok(result) => result.map_err(TemplateError::Io)?,
183 Err(_) => {
184 tracing::warn!(
185 "git log --numstat timed out after {}s for {}",
186 timeout.as_secs(),
187 project_path.display()
188 );
189 return Ok(None);
190 }
191 };
192
193 if !output.status.success() {
194 let error_msg = String::from_utf8_lossy(&output.stderr);
195 if error_msg.contains("does not have any commits yet") {
197 return Ok(None);
198 }
199 return Err(TemplateError::NotFound(format!(
200 "Git log failed: {error_msg}"
201 )));
202 }
203
204 Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()))
205 }
206
207 fn git_log_numstat_command(since: Option<&str>, scope: Option<&Path>) -> Command {
210 let mut command = Command::new("git");
211 command.arg("log");
212 if let Some(since) = since {
217 command.arg("--since").arg(since);
218 }
219 command.arg("--pretty=format:%H|%an|%aI").arg("--numstat");
220 if let Some(scope) = scope {
224 command.arg("--").arg(scope);
225 }
226 command
227 }
228
229 fn parse_log_into_file_stats(
236 log_output: &str,
237 ) -> (HashMap<PathBuf, FileStats>, HashSet<String>) {
238 let mut file_stats: HashMap<PathBuf, FileStats> = HashMap::with_capacity(64);
239 let mut current_commit: Option<CommitInfo> = None;
240 let mut commit_hashes: HashSet<String> = HashSet::with_capacity(64);
241
242 for line in log_output.lines() {
243 if line.is_empty() {
244 continue;
245 }
246
247 if let Some((hash, author, date)) = Self::parse_commit_line(line) {
248 commit_hashes.insert(hash.clone());
249 current_commit = Some(CommitInfo { hash, author, date });
250 } else if let Some(ref commit) = current_commit {
251 if let Some(change) = Self::parse_numstat_line(line) {
252 Self::record_file_change(&mut file_stats, commit, change);
253 }
254 }
255 }
256
257 (file_stats, commit_hashes)
258 }
259
260 fn record_file_change(
263 file_stats: &mut HashMap<PathBuf, FileStats>,
264 commit: &CommitInfo,
265 (additions, deletions, file_path): (usize, usize, String),
266 ) {
267 let stats = file_stats
268 .entry(PathBuf::from(&file_path))
269 .or_insert_with(|| FileStats {
270 commits: Vec::new(),
271 authors: HashSet::with_capacity(64),
272 total_additions: 0,
273 total_deletions: 0,
274 first_seen: commit.date.clone(),
275 last_modified: commit.date.clone(),
276 });
277
278 stats.commits.push(commit.hash.clone());
279 stats.authors.insert(commit.author.clone());
280 stats.total_additions += additions;
281 stats.total_deletions += deletions;
282
283 if commit.date > stats.last_modified {
284 stats.last_modified = commit.date.clone();
285 }
286 if commit.date < stats.first_seen {
287 stats.first_seen = commit.date.clone();
288 }
289 }
290
291 fn build_churn_metrics(
294 project_path: &Path,
295 file_stats: HashMap<PathBuf, FileStats>,
296 ) -> Vec<FileChurnMetrics> {
297 let max_commits = file_stats
298 .values()
299 .map(|s| s.commits.len())
300 .max()
301 .unwrap_or(1);
302 let max_changes = file_stats
303 .values()
304 .map(|s| s.total_additions + s.total_deletions)
305 .max()
306 .unwrap_or(1);
307
308 let mut metrics: Vec<FileChurnMetrics> = file_stats
309 .into_iter()
310 .map(|(path, stats)| {
311 let mut metric = FileChurnMetrics {
312 path: project_path.join(&path),
313 relative_path: path.to_string_lossy().to_string(),
314 commit_count: stats.commits.len(),
315 unique_authors: {
318 let mut authors: Vec<String> = stats.authors.into_iter().collect();
319 authors.sort_unstable();
320 authors
321 },
322 additions: stats.total_additions,
323 deletions: stats.total_deletions,
324 churn_score: 0.0,
325 last_modified: DateTime::parse_from_rfc3339(&stats.last_modified)
326 .unwrap_or_else(|_| Utc::now().into())
327 .with_timezone(&Utc),
328 first_seen: DateTime::parse_from_rfc3339(&stats.first_seen)
329 .unwrap_or_else(|_| Utc::now().into())
330 .with_timezone(&Utc),
331 };
332 metric.calculate_churn_score(max_commits, max_changes);
333 metric
334 })
335 .collect();
336
337 metrics.sort_by(Self::churn_rank_cmp);
338 metrics
339 }
340
341 fn get_file_metrics(
342 project_path: &Path,
343 since_date: Option<&str>,
344 scope: Option<&Path>,
345 ) -> Result<(Vec<FileChurnMetrics>, usize), TemplateError> {
346 let log_output = match Self::capture_git_log_output(project_path, since_date, scope)? {
347 Some(log) => log,
348 None => return Ok((Vec::new(), 0)),
349 };
350
351 let (file_stats, commit_hashes) = Self::parse_log_into_file_stats(&log_output);
352 let metrics = Self::build_churn_metrics(project_path, file_stats);
353
354 Ok((metrics, commit_hashes.len()))
355 }
356
357 pub(crate) fn churn_rank_cmp(a: &FileChurnMetrics, b: &FileChurnMetrics) -> std::cmp::Ordering {
370 b.churn_score
371 .partial_cmp(&a.churn_score)
372 .expect("internal error")
373 .then_with(|| a.relative_path.cmp(&b.relative_path))
374 }
375
376 fn parse_commit_line(line: &str) -> Option<(String, String, String)> {
377 let parts: Vec<&str> = line.split('|').collect();
378 if parts.len() == 3 {
379 Some((
380 parts[0].to_string(),
381 parts[1].to_string(),
382 parts[2].to_string(),
383 ))
384 } else {
385 None
386 }
387 }
388
389 fn parse_numstat_line(line: &str) -> Option<(usize, usize, String)> {
390 let parts: Vec<&str> = line.split_whitespace().collect();
391 if parts.len() >= 3 {
392 let additions = parts[0].parse::<usize>().ok()?;
393 let deletions = parts[1].parse::<usize>().ok()?;
394 let file_path = Self::resolve_rename_path(&parts[2..].join(" "));
395 Some((additions, deletions, file_path))
396 } else {
397 None
398 }
399 }
400
401 fn resolve_rename_path(raw: &str) -> String {
411 if !raw.contains("=>") {
412 return raw.to_string();
413 }
414
415 if let Some(open) = raw.find('{') {
417 if let Some(close) = raw[open..].find('}').map(|offset| offset + open) {
418 if let Some((_old, new)) = raw[open + 1..close].split_once("=>") {
419 let rebuilt = format!("{}{}{}", &raw[..open], new.trim(), &raw[close + 1..]);
420 let mut collapsed = rebuilt;
423 while collapsed.contains("//") {
424 collapsed = collapsed.replace("//", "/");
425 }
426 if !raw.starts_with('/') {
427 collapsed = collapsed.trim_start_matches('/').to_string();
428 }
429 return collapsed;
430 }
431 }
432 }
433
434 match raw.split_once("=>") {
436 Some((_old, new)) => new.trim().to_string(),
437 None => raw.to_string(),
438 }
439 }
440
441 fn generate_summary(files: &[FileChurnMetrics], total_commits: usize) -> ChurnSummary {
447 let mut author_contributions: std::collections::BTreeMap<String, usize> =
448 std::collections::BTreeMap::new();
449
450 for file in files {
451 for author in &file.unique_authors {
452 *author_contributions.entry(author.clone()).or_insert(0) += 1;
453 }
454 }
455
456 let hotspot_files: Vec<PathBuf> = files
457 .iter()
458 .take(10)
459 .filter(|f| f.churn_score > 0.5)
460 .map(|f| f.path.clone())
461 .collect();
462
463 let stable_files: Vec<PathBuf> = files
464 .iter()
465 .rev()
466 .take(10)
467 .filter(|f| f.churn_score < 0.1 && f.commit_count > 0)
468 .map(|f| f.path.clone())
469 .collect();
470
471 let (mean_churn_score, variance_churn_score, stddev_churn_score) = if files.is_empty() {
473 (0.0, 0.0, 0.0)
474 } else {
475 let scores: Vec<f64> = files.iter().map(|f| f64::from(f.churn_score)).collect();
476 let n = scores.len() as f64;
477 let sum: f64 = scores.iter().sum();
478 let mean = sum / n;
479 let variance = scores.iter().map(|&s| (s - mean).powi(2)).sum::<f64>() / n;
480 let stddev = variance.sqrt();
481 (mean, variance, stddev)
482 };
483
484 ChurnSummary {
485 total_commits,
486 total_files_changed: files.len(),
487 hotspot_files,
488 stable_files,
489 author_contributions,
490 mean_churn_score,
491 variance_churn_score,
492 stddev_churn_score,
493 }
494 }
495}
496
497struct FileStats {
498 commits: Vec<String>,
499 authors: HashSet<String>,
500 total_additions: usize,
501 total_deletions: usize,
502 first_seen: String,
503 last_modified: String,
504}
505
506struct CommitInfo {
507 hash: String,
508 author: String,
509 date: String,
510}
511
512#[cfg_attr(coverage_nightly, coverage(off))]
513#[cfg(test)]
514mod tests {
515 use super::*;
516 use tempfile::TempDir;
517
518 #[test]
519 fn test_git_analysis_basic() {
520 assert_eq!(1 + 1, 2);
522 }
523
524 #[test]
525 fn test_parse_commit_line_valid() {
526 let line = "abc123|John Doe|2024-01-15T10:30:00Z";
527 let result = GitAnalysisService::parse_commit_line(line);
528 assert!(result.is_some());
529 let (hash, author, date) = result.unwrap();
530 assert_eq!(hash, "abc123");
531 assert_eq!(author, "John Doe");
532 assert_eq!(date, "2024-01-15T10:30:00Z");
533 }
534
535 #[test]
536 fn test_parse_commit_line_invalid_too_few() {
537 let line = "abc123|John Doe";
538 let result = GitAnalysisService::parse_commit_line(line);
539 assert!(result.is_none());
540 }
541
542 #[test]
543 fn test_parse_commit_line_invalid_empty() {
544 let line = "";
545 let result = GitAnalysisService::parse_commit_line(line);
546 assert!(result.is_none());
547 }
548
549 #[test]
550 fn test_parse_numstat_line_valid() {
551 let line = "10\t20\tsrc/main.rs";
552 let result = GitAnalysisService::parse_numstat_line(line);
553 assert!(result.is_some());
554 let (additions, deletions, path) = result.unwrap();
555 assert_eq!(additions, 10);
556 assert_eq!(deletions, 20);
557 assert_eq!(path, "src/main.rs");
558 }
559
560 #[test]
561 fn test_parse_numstat_line_with_spaces() {
562 let line = "5\t15\tpath/to file.rs";
563 let result = GitAnalysisService::parse_numstat_line(line);
564 assert!(result.is_some());
565 let (additions, deletions, path) = result.unwrap();
566 assert_eq!(additions, 5);
567 assert_eq!(deletions, 15);
568 assert_eq!(path, "path/to file.rs");
569 }
570
571 #[test]
576 fn test_parse_numstat_line_resolves_renames_to_the_current_path() {
577 let cases = [
578 (
579 "3\t1\t{server/src => src}/tdg/analyzer.rs",
580 "src/tdg/analyzer.rs",
581 ),
582 (
583 "1\t0\tserver/tests/{ => modules}/unit_mcp_semantic_tools.rs",
584 "server/tests/modules/unit_mcp_semantic_tools.rs",
585 ),
586 ("4\t4\t{src => }/main.rs", "main.rs"),
587 ("2\t2\told/path.rs => new/path.rs", "new/path.rs"),
588 ("7\t0\tsrc/{a.rs => b.rs}", "src/b.rs"),
589 ];
590
591 for (line, expected) in cases {
592 let (_, _, path) =
593 GitAnalysisService::parse_numstat_line(line).expect("numstat line must parse");
594 assert_eq!(path, expected, "line {line:?}");
595 assert!(
596 !path.contains("=>") && !path.contains('{'),
597 "rename syntax survived into the path: {path:?}"
598 );
599 }
600 }
601
602 #[test]
604 fn test_parse_numstat_line_leaves_ordinary_paths_alone() {
605 let (_, _, path) = GitAnalysisService::parse_numstat_line("1\t1\tsrc/{weird}/f.rs")
606 .expect("numstat line must parse");
607 assert_eq!(path, "src/{weird}/f.rs");
608 }
609
610 #[test]
611 fn test_parse_numstat_line_invalid() {
612 let line = "invalid";
613 let result = GitAnalysisService::parse_numstat_line(line);
614 assert!(result.is_none());
615 }
616
617 #[test]
618 fn test_parse_numstat_line_binary() {
619 let line = "-\t-\timage.png";
620 let result = GitAnalysisService::parse_numstat_line(line);
621 assert!(result.is_none()); }
623
624 #[test]
625 fn test_generate_summary_empty() {
626 let files: Vec<FileChurnMetrics> = vec![];
627 let summary = GitAnalysisService::generate_summary(&files, 0);
628 assert_eq!(summary.total_commits, 0);
629 assert_eq!(summary.total_files_changed, 0);
630 assert!(summary.hotspot_files.is_empty());
631 assert!(summary.stable_files.is_empty());
632 assert_eq!(summary.mean_churn_score, 0.0);
633 }
634
635 #[test]
636 fn test_generate_summary_single_file() {
637 let files = vec![FileChurnMetrics {
638 path: PathBuf::from("src/main.rs"),
639 relative_path: "src/main.rs".to_string(),
640 commit_count: 5,
641 unique_authors: vec!["Author1".to_string()],
642 additions: 100,
643 deletions: 50,
644 churn_score: 0.7,
645 last_modified: Utc::now(),
646 first_seen: Utc::now(),
647 }];
648 let summary = GitAnalysisService::generate_summary(&files, 3);
653 assert_eq!(summary.total_commits, 3);
654 assert_eq!(summary.total_files_changed, 1);
655 assert_eq!(summary.hotspot_files.len(), 1); }
657
658 #[test]
659 fn test_generate_summary_multiple_authors() {
660 let files = vec![
661 FileChurnMetrics {
662 path: PathBuf::from("file1.rs"),
663 relative_path: "file1.rs".to_string(),
664 commit_count: 3,
665 unique_authors: vec!["Author1".to_string(), "Author2".to_string()],
666 additions: 50,
667 deletions: 20,
668 churn_score: 0.3,
669 last_modified: Utc::now(),
670 first_seen: Utc::now(),
671 },
672 FileChurnMetrics {
673 path: PathBuf::from("file2.rs"),
674 relative_path: "file2.rs".to_string(),
675 commit_count: 2,
676 unique_authors: vec!["Author2".to_string()],
677 additions: 30,
678 deletions: 10,
679 churn_score: 0.05,
680 last_modified: Utc::now(),
681 first_seen: Utc::now(),
682 },
683 ];
684 let summary = GitAnalysisService::generate_summary(&files, 3);
687 assert_eq!(summary.total_commits, 3);
688 assert_eq!(summary.total_files_changed, 2);
689 assert_eq!(summary.author_contributions.len(), 2);
690 }
691
692 #[test]
693 fn test_analyze_code_churn_no_git() {
694 let temp_dir = TempDir::new().unwrap();
695 let result = GitAnalysisService::analyze_code_churn(temp_dir.path(), 30);
696 assert!(result.is_err());
697 }
698
699 #[test]
700 fn test_generate_summary_stable_files() {
701 let files = vec![FileChurnMetrics {
702 path: PathBuf::from("stable.rs"),
703 relative_path: "stable.rs".to_string(),
704 commit_count: 1,
705 unique_authors: vec!["Author".to_string()],
706 additions: 10,
707 deletions: 5,
708 churn_score: 0.05, last_modified: Utc::now(),
710 first_seen: Utc::now(),
711 }];
712 let summary = GitAnalysisService::generate_summary(&files, 1);
713 assert_eq!(summary.stable_files.len(), 1);
714 }
715
716 #[test]
717 fn test_churn_summary_statistics() {
718 let files = vec![
719 FileChurnMetrics {
720 path: PathBuf::from("f1.rs"),
721 relative_path: "f1.rs".to_string(),
722 commit_count: 2,
723 unique_authors: vec![],
724 additions: 0,
725 deletions: 0,
726 churn_score: 0.2,
727 last_modified: Utc::now(),
728 first_seen: Utc::now(),
729 },
730 FileChurnMetrics {
731 path: PathBuf::from("f2.rs"),
732 relative_path: "f2.rs".to_string(),
733 commit_count: 4,
734 unique_authors: vec![],
735 additions: 0,
736 deletions: 0,
737 churn_score: 0.8,
738 last_modified: Utc::now(),
739 first_seen: Utc::now(),
740 },
741 ];
742 let summary = GitAnalysisService::generate_summary(&files, 4);
743 assert!((summary.mean_churn_score - 0.5).abs() < 0.01);
745 assert!(summary.variance_churn_score >= 0.0);
747 assert!(summary.stddev_churn_score >= 0.0);
748 }
749
750 fn init_repo_with_subdir_commits() -> TempDir {
754 let temp = TempDir::new().unwrap();
755 let root = temp.path();
756
757 let git = |args: &[&str]| {
758 let status = std::process::Command::new("git")
759 .args(args)
760 .current_dir(root)
761 .output()
762 .expect("git must be available for this test");
763 assert!(
764 status.status.success(),
765 "git {args:?} failed: {}",
766 String::from_utf8_lossy(&status.stderr)
767 );
768 };
769
770 git(&["init", "--initial-branch=main"]);
771 git(&["config", "user.email", "test@example.com"]);
772 git(&["config", "user.name", "Test User"]);
773
774 std::fs::create_dir_all(root.join("src/utils")).unwrap();
775 std::fs::create_dir_all(root.join("docs")).unwrap();
776
777 for i in 0..3 {
778 std::fs::write(
779 root.join("src/utils/helper.rs"),
780 format!("pub fn helper() {{ let _ = {i}; }}\n"),
781 )
782 .unwrap();
783 std::fs::write(root.join("docs/readme.md"), format!("doc revision {i}\n")).unwrap();
784 git(&["add", "."]);
785 git(&["commit", "-m", &format!("change {i}")]);
786 }
787
788 temp
789 }
790
791 #[test]
792 fn test_discover_repository_root_walks_up() {
793 let temp = init_repo_with_subdir_commits();
794 let expected = temp.path().canonicalize().unwrap();
795
796 for start in [
798 temp.path().to_path_buf(),
799 temp.path().join("src"),
800 temp.path().join("src/utils"),
801 ] {
802 assert_eq!(
803 GitAnalysisService::discover_repository_root(&start),
804 Some(expected.clone()),
805 "should have walked up to the repo root from {start:?}"
806 );
807 }
808 }
809
810 #[test]
811 fn test_discover_repository_root_none_outside_repo() {
812 let temp = TempDir::new().unwrap();
813 assert!(GitAnalysisService::discover_repository_root(temp.path()).is_none());
814 }
815
816 #[test]
820 fn test_analyze_code_churn_from_subdirectory_is_measured() {
821 let temp = init_repo_with_subdir_commits();
822 let subdir = temp.path().join("src/utils");
823
824 let analysis = GitAnalysisService::analyze_code_churn(&subdir, 365)
825 .expect("churn inside a repository must be measurable from a subdirectory");
826
827 assert_eq!(
828 analysis.repository_root,
829 temp.path().canonicalize().unwrap(),
830 "repository_root must be the discovered root, not the queried subpath"
831 );
832 assert!(
833 !analysis.files.is_empty(),
834 "subdirectory churn must not be empty for a subtree with commits"
835 );
836 assert!(
837 analysis.summary.total_commits > 0,
838 "total_commits must be measured, got {}",
839 analysis.summary.total_commits
840 );
841 }
842
843 #[test]
846 fn test_analyze_code_churn_subdirectory_is_scoped() {
847 let temp = init_repo_with_subdir_commits();
848
849 let scoped = GitAnalysisService::analyze_code_churn(&temp.path().join("src/utils"), 365)
850 .expect("scoped churn");
851 let whole = GitAnalysisService::analyze_code_churn(temp.path(), 365).expect("root churn");
852
853 assert!(
854 scoped
855 .files
856 .iter()
857 .all(|f| f.relative_path.starts_with("src/utils")),
858 "scoped query returned files outside the requested subtree: {:?}",
859 scoped
860 .files
861 .iter()
862 .map(|f| f.relative_path.clone())
863 .collect::<Vec<_>>()
864 );
865 assert!(
866 whole.files.len() > scoped.files.len(),
867 "whole-repo churn ({}) must cover more files than src/utils ({})",
868 whole.files.len(),
869 scoped.files.len()
870 );
871 }
872
873 #[test]
875 fn test_analyze_code_churn_is_deterministic_over_5_runs() {
876 let temp = init_repo_with_subdir_commits();
877 let subdir = temp.path().join("src/utils");
878
879 let fingerprint = |a: &CodeChurnAnalysis| {
880 a.files
881 .iter()
882 .map(|f| {
883 format!(
884 "{}|{}|{}|{}|{:.6}",
885 f.relative_path, f.commit_count, f.additions, f.deletions, f.churn_score
886 )
887 })
888 .collect::<Vec<_>>()
889 .join("\n")
890 };
891
892 let first = fingerprint(&GitAnalysisService::analyze_code_churn(&subdir, 365).unwrap());
893 for i in 1..5 {
894 let again = fingerprint(&GitAnalysisService::analyze_code_churn(&subdir, 365).unwrap());
895 assert_eq!(first, again, "churn output differed on run {i}");
896 }
897 }
898
899 fn churn_metric(path: &str, score: f32) -> FileChurnMetrics {
900 FileChurnMetrics {
901 path: PathBuf::from(path),
902 relative_path: path.to_string(),
903 commit_count: 1,
904 unique_authors: vec!["a".to_string()],
905 additions: 1,
906 deletions: 1,
907 churn_score: score,
908 last_modified: Utc::now(),
909 first_seen: Utc::now(),
910 }
911 }
912
913 #[test]
919 fn test_churn_rank_cmp_breaks_score_ties_on_path() {
920 let forward = vec![
921 churn_metric("src/a.rs", 0.05),
922 churn_metric("src/b.rs", 0.05),
923 churn_metric("src/c.rs", 0.05),
924 churn_metric("src/hot.rs", 0.9),
925 ];
926 let mut reversed: Vec<FileChurnMetrics> = forward.iter().rev().cloned().collect();
927 let mut forward = forward;
928
929 forward.sort_by(GitAnalysisService::churn_rank_cmp);
930 reversed.sort_by(GitAnalysisService::churn_rank_cmp);
931
932 let paths = |v: &[FileChurnMetrics]| {
933 v.iter()
934 .map(|f| f.relative_path.clone())
935 .collect::<Vec<_>>()
936 };
937 assert_eq!(
938 paths(&forward),
939 vec!["src/hot.rs", "src/a.rs", "src/b.rs", "src/c.rs"],
940 "score descending, then path ascending"
941 );
942 assert_eq!(
943 paths(&forward),
944 paths(&reversed),
945 "the ranking must not depend on the order the metrics arrived in"
946 );
947 }
948}