use crate::git::GitContext;
use crate::language::Language;
use crate::report::{FunctionRiskReport, MetricsReport};
use crate::risk::RiskBand;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[cfg(test)]
use crate::report::RiskReport;
pub const SNAPSHOT_SCHEMA_VERSION: u32 = 6;
const SNAPSHOT_SCHEMA_MIN_VERSION: u32 = 6;
pub const FORMULA_VERSION: u32 = 3;
fn default_formula_version() -> u32 {
FORMULA_VERSION
}
const INDEX_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct CommitInfo {
pub sha: String,
pub parents: Vec<String>,
pub timestamp: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub author: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_fix_commit: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_revert_commit: Option<bool>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub ticket_ids: Vec<String>,
}
impl From<GitContext> for CommitInfo {
fn from(ctx: GitContext) -> Self {
CommitInfo {
sha: ctx.head_sha,
parents: ctx.parent_shas,
timestamp: ctx.timestamp,
branch: ctx.branch,
message: ctx.message,
author: ctx.author,
is_fix_commit: ctx.is_fix_commit,
is_revert_commit: ctx.is_revert_commit,
ticket_ids: ctx.ticket_ids,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct AnalysisInfo {
pub scope: String,
#[serde(rename = "tool_version")]
pub tool_version: String,
#[serde(default = "default_formula_version")]
pub formula_version: u32,
#[serde(default = "default_touch_window_days")]
pub touch_window_days: u32,
}
fn default_touch_window_days() -> u32 {
crate::git::TOUCH_WINDOW_DAYS as u32
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct ChurnMetrics {
pub lines_added: usize,
pub lines_deleted: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct CallGraphMetrics {
pub fan_in: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct FunctionSnapshot {
pub function_id: String,
pub file: String,
pub line: u32,
pub language: Language,
pub metrics: MetricsReport,
pub lrs: f64,
pub band: RiskBand,
#[serde(skip_serializing_if = "Option::is_none")]
pub suppression_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub churn: Option<ChurnMetrics>,
#[serde(skip_serializing_if = "Option::is_none")]
pub touch_count: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub days_since_last_change: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub callgraph: Option<CallGraphMetrics>,
#[serde(skip_serializing_if = "Option::is_none")]
pub activity_risk: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub risk_factors: Option<crate::scoring::RiskFactors>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tier: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub subsystem: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authors_90d: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub directed_coupling: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub convention_bug_fix_count: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub burst_score: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commit_count: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub author_count: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub author_entropy: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub isolation_rate: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub age_days: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_touch_days: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub newcomer_rate: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub explanation: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BandStats {
pub count: usize,
pub sum_risk: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct SnapshotSummary {
pub total_functions: usize,
pub total_activity_risk: f64,
pub top_1_pct_share: f64,
pub top_5_pct_share: f64,
pub top_10_pct_share: f64,
pub by_band: std::collections::BTreeMap<String, BandStats>,
#[serde(default)]
pub signal_confidence: crate::aggregates::SignalConfidence,
#[serde(default)]
pub conventional_prefix_rate: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct Snapshot {
#[serde(rename = "schema_version")]
pub schema_version: u32,
pub commit: CommitInfo,
pub analysis: AnalysisInfo,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub functions: Vec<FunctionSnapshot>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<SnapshotSummary>,
#[serde(skip_serializing_if = "Option::is_none")]
pub aggregates: Option<crate::aggregates::SnapshotAggregates>,
#[serde(skip_serializing_if = "Option::is_none")]
pub triage: Option<crate::aggregates::TriageView>,
#[serde(skip_serializing_if = "Option::is_none")]
pub architecture: Option<crate::aggregates::AgentArchitectureView>,
#[serde(skip_serializing_if = "Option::is_none")]
pub co_change: Option<crate::aggregates::AgentCoChangeView>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct IndexEntry {
pub sha: String,
pub parents: Vec<String>,
pub timestamp: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct Index {
#[serde(rename = "schema_version")]
pub schema_version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub compaction_level: Option<u32>,
pub commits: Vec<IndexEntry>,
}
const SUBSYSTEM_MANIFESTS: &[&str] = &[
"package.json",
"Cargo.toml",
"pyproject.toml",
"go.mod",
"setup.py",
"setup.cfg",
"Gemfile",
"build.gradle",
"pom.xml",
"mix.exs",
];
const SKIP_DIRS: &[&str] = &[
"node_modules",
".git",
"__pycache__",
".venv",
"venv",
"dist",
"build",
"out",
"target",
];
fn build_subsystem_cache(repo_root: &Path) -> HashMap<PathBuf, String> {
let mut cache: HashMap<PathBuf, String> = HashMap::new();
collect_manifest_dirs(repo_root, repo_root, &mut cache);
cache
}
fn collect_manifest_dirs(dir: &Path, repo_root: &Path, cache: &mut HashMap<PathBuf, String>) {
for manifest in SUBSYSTEM_MANIFESTS {
if dir.join(manifest).exists() {
let rel = dir
.strip_prefix(repo_root)
.unwrap_or(dir)
.to_string_lossy()
.replace('\\', "/");
cache.entry(dir.to_path_buf()).or_insert(rel);
break;
}
}
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let ft = match entry.file_type() {
Ok(ft) => ft,
Err(_) => continue,
};
if !ft.is_dir() {
continue;
}
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with('.') || SKIP_DIRS.contains(&name_str.as_ref()) {
continue;
}
collect_manifest_dirs(&entry.path(), repo_root, cache);
}
}
fn subsystem_for_file(
abs_file: &Path,
repo_root: &Path,
cache: &HashMap<PathBuf, String>,
) -> Option<String> {
let mut best: Option<&str> = None;
let mut best_depth = 0usize;
let mut dir = abs_file.parent()?;
loop {
if let Some(label) = cache.get(dir) {
let depth = dir.components().count();
if depth >= best_depth {
best = Some(label.as_str());
best_depth = depth;
}
}
match dir.parent() {
Some(p) if p != dir && dir.starts_with(repo_root) => dir = p,
_ => break,
}
}
best.map(|s| s.to_string())
}
impl Snapshot {
pub fn new(git_context: GitContext, reports: Vec<FunctionRiskReport>) -> Self {
let mut functions: Vec<FunctionSnapshot> = reports
.into_iter()
.map(|report| {
let normalized_file = report.file.replace('\\', "/");
let function_symbol = if report.function.starts_with("<anonymous>") {
"<anonymous>"
} else {
&report.function
};
let function_id = format!("{}::{}", normalized_file, function_symbol);
FunctionSnapshot {
function_id,
file: normalized_file,
line: report.line,
language: report.language,
metrics: report.metrics,
lrs: report.lrs,
band: report.band,
suppression_reason: report.suppression_reason,
churn: None, touch_count: None, days_since_last_change: None, callgraph: None, activity_risk: None,
risk_factors: None,
tier: None,
subsystem: None,
authors_90d: None,
directed_coupling: None,
convention_bug_fix_count: None,
burst_score: None,
commit_count: None,
author_count: None,
author_entropy: None,
isolation_rate: None,
age_days: None,
last_touch_days: None,
newcomer_rate: None,
explanation: None,
}
})
.collect();
functions.sort_by(|a, b| a.function_id.cmp(&b.function_id));
Snapshot {
schema_version: SNAPSHOT_SCHEMA_VERSION,
commit: CommitInfo::from(git_context),
analysis: AnalysisInfo {
scope: "full".to_string(),
tool_version: env!("CARGO_PKG_VERSION").to_string(),
formula_version: FORMULA_VERSION,
touch_window_days: 365,
},
functions,
summary: None,
aggregates: None, triage: None,
architecture: None,
co_change: None,
}
}
pub fn populate_churn(
&mut self,
file_churns: &std::collections::HashMap<String, crate::git::FileChurn>,
) {
for function in &mut self.functions {
let file_path = &function.file;
if let Some(file_churn) = file_churns.get(file_path) {
function.churn = Some(ChurnMetrics {
lines_added: file_churn.lines_added,
lines_deleted: file_churn.lines_deleted,
});
}
}
}
pub fn relativize_paths(&mut self, repo_root: &Path) {
let (prefix_can, prefix_raw) = crate::trainer::repo_prefixes(repo_root);
for function in &mut self.functions {
let rel = crate::trainer::make_rel(&function.file, &prefix_can, &prefix_raw);
if rel == function.file {
continue;
}
if let Some((_, symbol)) = function.function_id.split_once("::") {
function.function_id = format!("{rel}::{symbol}");
}
function.file = rel;
}
}
pub fn populate_authors_90d(&mut self, repo_root: &Path) {
use std::collections::{HashMap, HashSet};
use std::process::Command;
let mut file_indices: HashMap<String, Vec<usize>> = HashMap::new();
for (i, func) in self.functions.iter().enumerate() {
file_indices.entry(func.file.clone()).or_default().push(i);
}
for (abs_path, indices) in &file_indices {
let rel = if let Ok(r) = std::path::Path::new(abs_path).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
abs_path.clone()
};
let out = Command::new("git")
.args(["log", "--after=90.days.ago", "--format=%ae", "--", &rel])
.current_dir(repo_root)
.output();
let count = match out {
Ok(o) if o.status.success() => {
let text = String::from_utf8_lossy(&o.stdout);
text.lines()
.filter(|l| !l.is_empty())
.collect::<HashSet<_>>()
.len() as u32
}
_ => continue, };
for &i in indices {
self.functions[i].authors_90d = Some(count);
}
}
}
pub fn populate_convention_bug_fix_count(&mut self, repo_root: &Path) {
use std::collections::HashMap;
use std::process::Command;
let mut file_indices: HashMap<String, Vec<usize>> = HashMap::new();
for (i, func) in self.functions.iter().enumerate() {
file_indices.entry(func.file.clone()).or_default().push(i);
}
for (abs_path, indices) in &file_indices {
let rel = if let Ok(r) = std::path::Path::new(abs_path).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
abs_path.clone()
};
let out = Command::new("git")
.args(["log", "--format=%s", "--", &rel])
.current_dir(repo_root)
.output();
let count = match out {
Ok(o) if o.status.success() => {
let text = String::from_utf8_lossy(&o.stdout);
text.lines()
.filter(|l| crate::git::detect_fix_commit(l))
.count() as u32
}
_ => continue,
};
for &i in indices {
self.functions[i].convention_bug_fix_count = Some(count);
}
}
}
pub fn populate_burst_score(&mut self, repo_root: &Path) {
let signals = crate::history_signals::compute_history_signals_for_repo(repo_root);
if signals.is_empty() {
return;
}
self.apply_burst_score_data(repo_root, &signals);
}
fn apply_burst_score_data(
&mut self,
repo_root: &Path,
signals: &std::collections::HashMap<String, crate::history_signals::HistorySignals>,
) {
use std::collections::HashMap;
let mut file_indices: HashMap<String, Vec<usize>> = HashMap::new();
for (i, func) in self.functions.iter().enumerate() {
let rel = if let Ok(r) = std::path::Path::new(&func.file).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
func.file.clone()
};
file_indices.entry(rel).or_default().push(i);
}
for (rel, indices) in &file_indices {
let Some(s) = signals.get(rel) else {
continue;
};
for &i in indices {
self.functions[i].burst_score = Some(s.burst_score);
}
}
}
pub fn populate_history_signals(&mut self, repo_root: &Path) {
let git_dir = crate::coupling::git_dir(repo_root);
let commits = crate::history_signals::load_commits_with_author(&git_dir);
if commits.is_empty() {
return;
}
let signals = crate::history_signals::compute_history_signals(&commits);
let mut file_indices: HashMap<String, Vec<usize>> = HashMap::new();
for (i, func) in self.functions.iter().enumerate() {
let rel = if let Ok(r) = std::path::Path::new(&func.file).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
func.file.clone()
};
file_indices.entry(rel).or_default().push(i);
}
for (rel, indices) in &file_indices {
let Some(s) = signals.get(rel) else {
continue;
};
for &i in indices {
self.functions[i].commit_count = Some(s.commit_count);
self.functions[i].author_count = Some(s.author_count);
self.functions[i].author_entropy = Some(s.author_entropy);
self.functions[i].isolation_rate = Some(s.isolation_rate);
self.functions[i].age_days = Some(s.age_days);
self.functions[i].last_touch_days = Some(s.last_touch_days);
self.functions[i].newcomer_rate = s.newcomer_rate;
}
}
}
pub fn populate_directed_coupling(
&mut self,
repo_root: &Path,
partner_scores: &std::collections::HashMap<String, f64>,
) {
let (dc_scores, _jaccard) =
crate::coupling::compute_directed_coupling_for_repo(repo_root, partner_scores);
self.apply_directed_coupling_data(repo_root, &dc_scores);
}
pub fn apply_directed_coupling_data(
&mut self,
repo_root: &Path,
dc_scores: &std::collections::HashMap<String, f64>,
) {
let mut file_indices: std::collections::HashMap<String, Vec<usize>> =
std::collections::HashMap::new();
for (i, func) in self.functions.iter().enumerate() {
let rel = std::path::Path::new(&func.file)
.strip_prefix(repo_root)
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|_| func.file.replace('\\', "/"));
file_indices.entry(rel).or_default().push(i);
}
for (rel_path, indices) in &file_indices {
let score = dc_scores.get(rel_path).copied();
for &i in indices {
self.functions[i].directed_coupling = score;
}
}
}
pub fn populate_subsystems(&mut self, repo_root: &Path) {
let cache = build_subsystem_cache(repo_root);
for function in &mut self.functions {
let path = Path::new(&function.file);
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
repo_root.join(path)
};
function.subsystem = subsystem_for_file(&abs, repo_root, &cache);
}
}
fn fetch_touch_metrics_data(
&self,
repo_root: &std::path::Path,
window_days: u32,
) -> (
crate::git::BatchedTouchMetrics,
std::collections::HashMap<String, u32>,
) {
use std::collections::HashMap;
let abs_to_rel: HashMap<String, String> = self
.functions
.iter()
.map(|function| {
let abs = function.file.clone();
let rel = if let Ok(r) = std::path::Path::new(&abs).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
abs.clone()
};
(abs, rel)
})
.collect();
let batched =
crate::git::batch_touch_metrics_at(repo_root, self.commit.timestamp, window_days)
.unwrap_or_else(|_| crate::git::BatchedTouchMetrics {
touch_count: HashMap::new(),
days_since_last_change: HashMap::new(),
});
let stale_files: std::collections::HashSet<&str> = abs_to_rel
.values()
.map(|s| s.as_str())
.filter(|rel| !batched.days_since_last_change.contains_key(*rel))
.collect();
let stale_days =
crate::git::batch_last_touch_for_files(repo_root, &stale_files, self.commit.timestamp);
(batched, stale_days)
}
fn apply_touch_metrics_data(
&mut self,
repo_root: &std::path::Path,
batched: &crate::git::BatchedTouchMetrics,
stale_days: &std::collections::HashMap<String, u32>,
) {
use std::collections::HashMap;
let mut unique_files: HashMap<String, Vec<usize>> = HashMap::new();
for (idx, function) in self.functions.iter().enumerate() {
unique_files
.entry(function.file.clone())
.or_default()
.push(idx);
}
let abs_to_rel: HashMap<String, String> = unique_files
.keys()
.map(|abs| {
let rel = if let Ok(r) = std::path::Path::new(abs).strip_prefix(repo_root) {
r.to_string_lossy().to_string()
} else {
abs.clone()
};
(abs.clone(), rel)
})
.collect();
for (abs_path, function_indices) in &unique_files {
let rel = abs_to_rel
.get(abs_path)
.map(|s| s.as_str())
.unwrap_or(abs_path);
let touch_count = batched.touch_count.get(rel).copied().or(Some(0));
let days_since = batched
.days_since_last_change
.get(rel)
.copied()
.or_else(|| stale_days.get(rel).copied());
for &idx in function_indices {
self.functions[idx].touch_count = touch_count;
self.functions[idx].days_since_last_change = days_since;
}
}
}
fn populate_file_level_touch_metrics(
&mut self,
repo_root: &std::path::Path,
window_days: u32,
) -> anyhow::Result<()> {
let (batched, stale_days) = self.fetch_touch_metrics_data(repo_root, window_days);
self.apply_touch_metrics_data(repo_root, &batched, &stale_days);
Ok(())
}
pub fn populate_touch_metrics(
&mut self,
repo_root: &std::path::Path,
window_days: u32,
) -> anyhow::Result<()> {
self.populate_file_level_touch_metrics(repo_root, window_days)
}
pub fn adjust_recency_for_branch(
&mut self,
repo_root: &std::path::Path,
merge_base_sha: &str,
merge_base_ts: i64,
) {
let merge_base_age_days = ((self.commit.timestamp - merge_base_ts).max(0) / 86400) as u32;
let mut files_needing_lookup: std::collections::HashSet<String> =
std::collections::HashSet::new();
for func in &self.functions {
if func
.days_since_last_change
.is_some_and(|d| d < merge_base_age_days)
{
files_needing_lookup.insert(func.file.clone());
}
}
let mut pre_branch: std::collections::HashMap<String, Option<u32>> =
std::collections::HashMap::new();
for abs_file in &files_needing_lookup {
let rel = std::path::Path::new(abs_file)
.strip_prefix(repo_root)
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_else(|_| abs_file.replace('\\', "/"));
let days = crate::git::days_since_last_change_at_sha(
repo_root,
&rel,
merge_base_sha,
self.commit.timestamp,
);
pre_branch.insert(abs_file.clone(), days);
}
for func in &mut self.functions {
if let Some(Some(pre_days)) = pre_branch.get(&func.file) {
func.days_since_last_change = Some(*pre_days);
}
}
}
pub fn populate_callgraph(&mut self, call_graph: &crate::callgraph::CallGraph) {
let fan_in_map = call_graph.build_fan_in_map();
for function in &mut self.functions {
if call_graph.contains(&function.function_id) {
function.callgraph = Some(CallGraphMetrics {
fan_in: fan_in_map.get(&function.function_id).copied().unwrap_or(0),
});
}
}
}
pub fn compute_activity_risk(&mut self) {
for function in &mut self.functions {
let (activity_risk, risk_factors) =
crate::scoring::compute_activity_risk(&crate::scoring::ActivityRiskInput {
lrs: function.lrs,
churn: function
.churn
.as_ref()
.map(|c| (c.lines_added, c.lines_deleted)),
touch_count: function.touch_count,
days_since_last_change: function.days_since_last_change,
});
function.activity_risk = Some(activity_risk);
function.risk_factors = Some(risk_factors);
}
}
pub fn compute_tiers(&mut self) {
if self.functions.is_empty() {
return;
}
let mut touches: Vec<usize> = self
.functions
.iter()
.map(|f| f.touch_count.unwrap_or(0))
.collect();
touches.sort_unstable();
let touch_median = touches[(50 * (touches.len() - 1)) / 100];
for function in &mut self.functions {
let touched_often = function.touch_count.is_some_and(|t| t > touch_median);
let recently_changed = function.days_since_last_change.is_some_and(|d| d <= 30);
function.tier = Some(
if touched_often || recently_changed {
"active"
} else {
"quiet"
}
.to_string(),
);
}
}
pub fn compute_summary(&mut self, repo_root: &Path) {
let (signal_confidence, conventional_prefix_rate) =
crate::aggregates::compute_signal_confidence(repo_root);
let n = self.functions.len();
if n == 0 {
self.summary = Some(SnapshotSummary {
total_functions: 0,
total_activity_risk: 0.0,
top_1_pct_share: 0.0,
top_5_pct_share: 0.0,
top_10_pct_share: 0.0,
by_band: std::collections::BTreeMap::new(),
signal_confidence,
conventional_prefix_rate,
});
return;
}
let mut scored: Vec<f64> = self
.functions
.iter()
.map(|f| f.activity_risk.unwrap_or(f.lrs))
.collect();
scored.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
let total_risk: f64 = scored.iter().sum();
let (top_1_pct_share, top_5_pct_share, top_10_pct_share) =
compute_top_k_shares(&scored, total_risk);
self.summary = Some(SnapshotSummary {
total_functions: n,
total_activity_risk: total_risk,
top_1_pct_share,
top_5_pct_share,
top_10_pct_share,
by_band: compute_band_distribution(&self.functions),
signal_confidence,
conventional_prefix_rate,
});
}
pub fn to_json(&self) -> Result<String> {
serde_json::to_string_pretty(self).context("failed to serialize snapshot to JSON")
}
pub fn write_json_to<W: std::io::Write>(&self, writer: &mut W) -> Result<()> {
serde_json::to_writer_pretty(&mut *writer, self)
.context("failed to write snapshot JSON")?;
writeln!(writer).context("failed to write trailing newline")
}
pub fn from_json(json: &str) -> Result<Self> {
let snapshot: Snapshot =
serde_json::from_str(json).context("failed to deserialize snapshot from JSON")?;
if snapshot.schema_version < SNAPSHOT_SCHEMA_MIN_VERSION
|| snapshot.schema_version > SNAPSHOT_SCHEMA_VERSION
{
anyhow::bail!(
"unsupported snapshot schema version {} (this build reads version {}); \
regenerate it with `hotspots analyze --mode snapshot --force`",
snapshot.schema_version,
SNAPSHOT_SCHEMA_VERSION
);
}
Ok(snapshot)
}
pub fn commit_sha(&self) -> &str {
&self.commit.sha
}
}
fn compute_top_k_shares(scored: &[f64], total_risk: f64) -> (f64, f64, f64) {
let n = scored.len();
let safe_div = |a: f64, b: f64| if b > 0.0 { a / b } else { 0.0 };
let top1_sum: f64 = scored.iter().take((n / 100).max(1)).sum();
let top5_sum: f64 = scored.iter().take((n * 5 / 100).max(1)).sum();
let top10_sum: f64 = scored.iter().take((n / 10).max(1)).sum();
(
safe_div(top1_sum, total_risk),
safe_div(top5_sum, total_risk),
safe_div(top10_sum, total_risk),
)
}
fn compute_band_distribution(
functions: &[FunctionSnapshot],
) -> std::collections::BTreeMap<String, BandStats> {
let mut by_band = std::collections::BTreeMap::new();
for func in functions {
let score = func.activity_risk.unwrap_or(func.lrs);
let entry = by_band
.entry(func.band.as_str().to_string())
.or_insert(BandStats {
count: 0,
sum_risk: 0.0,
});
entry.count += 1;
entry.sum_risk += score;
}
by_band
}
pub struct SnapshotEnricher {
snapshot: Snapshot,
}
impl SnapshotEnricher {
pub fn new(snapshot: Snapshot) -> Self {
SnapshotEnricher { snapshot }
}
pub fn with_subsystems(mut self, repo_root: &Path) -> Self {
if repo_root.exists() {
self.snapshot.populate_subsystems(repo_root);
}
self
}
pub fn with_relative_paths(mut self, repo_root: &Path) -> Self {
self.snapshot.relativize_paths(repo_root);
self
}
pub fn with_burst_score(mut self, repo_root: &Path) -> Self {
if repo_root.exists() {
self.snapshot.populate_burst_score(repo_root);
}
self
}
pub fn with_burst_score_data(
mut self,
repo_root: &Path,
signals: &std::collections::HashMap<String, crate::history_signals::HistorySignals>,
) -> Self {
self.snapshot.apply_burst_score_data(repo_root, signals);
self
}
pub fn with_churn(
mut self,
file_churns: &std::collections::HashMap<String, crate::git::FileChurn>,
) -> Self {
self.snapshot.populate_churn(file_churns);
self
}
pub fn with_touch_metrics(mut self, repo_root: &Path, window_days: u32) -> Self {
if let Err(e) = self.snapshot.populate_touch_metrics(repo_root, window_days) {
eprintln!("Warning: failed to populate touch metrics: {}", e);
}
self
}
pub fn fetch_touch_metrics_data(
&self,
repo_root: &Path,
window_days: u32,
) -> (
crate::git::BatchedTouchMetrics,
std::collections::HashMap<String, u32>,
) {
self.snapshot
.fetch_touch_metrics_data(repo_root, window_days)
}
pub fn with_touch_metrics_data(
mut self,
repo_root: &Path,
batched: &crate::git::BatchedTouchMetrics,
stale_days: &std::collections::HashMap<String, u32>,
) -> Self {
self.snapshot
.apply_touch_metrics_data(repo_root, batched, stale_days);
self
}
pub fn with_branch_recency_adjustment(
mut self,
repo_root: &Path,
merge_base: Option<&(String, i64)>,
) -> Self {
if let Some((sha, ts)) = merge_base {
self.snapshot.adjust_recency_for_branch(repo_root, sha, *ts);
}
self
}
pub fn with_callgraph(mut self, call_graph: &crate::callgraph::CallGraph) -> Self {
self.snapshot.populate_callgraph(call_graph);
self
}
pub fn enrich(mut self, repo_root: &Path) -> Self {
self.snapshot.compute_activity_risk();
self.snapshot.compute_tiers();
self.snapshot.compute_summary(repo_root);
self
}
pub fn build(self) -> Snapshot {
self.snapshot
}
}
impl Index {
pub fn new() -> Self {
Index {
schema_version: INDEX_SCHEMA_VERSION,
compaction_level: Some(0), commits: Vec::new(),
}
}
pub fn compaction_level(&self) -> u32 {
self.compaction_level.unwrap_or(0)
}
pub fn set_compaction_level(&mut self, level: u32) {
self.compaction_level = Some(level);
}
pub fn load_or_new(path: &Path) -> Result<Self> {
if path.exists() {
let json = std::fs::read_to_string(path)
.with_context(|| format!("failed to read index file: {}", path.display()))?;
Self::from_json(&json)
} else {
Ok(Self::new())
}
}
pub fn from_json(json: &str) -> Result<Self> {
let index: Index =
serde_json::from_str(json).context("failed to deserialize index from JSON")?;
if index.schema_version != INDEX_SCHEMA_VERSION {
anyhow::bail!(
"index schema version mismatch: expected {}, got {}",
INDEX_SCHEMA_VERSION,
index.schema_version
);
}
Ok(index)
}
pub fn to_json(&self) -> Result<String> {
serde_json::to_string_pretty(self).context("failed to serialize index to JSON")
}
pub fn add_commit(&mut self, entry: IndexEntry) {
if !self.commits.iter().any(|c| c.sha == entry.sha) {
self.commits.push(entry);
self.commits.sort_by(|a, b| {
a.timestamp
.cmp(&b.timestamp)
.then_with(|| a.sha.cmp(&b.sha))
});
}
}
pub fn remove_commit(&mut self, sha: &str) {
self.commits.retain(|c| c.sha != sha);
}
pub fn contains(&self, sha: &str) -> bool {
self.commits.iter().any(|c| c.sha == sha)
}
}
impl Default for Index {
fn default() -> Self {
Self::new()
}
}
const DELTA_SNAPSHOT_SCHEMA_VERSION: u32 = 1;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct DeltaSnapshot {
pub schema_version: u32,
pub snapshot_schema_version: u32,
pub commit: CommitInfo,
pub analysis: AnalysisInfo,
pub base_sha: String,
pub added: Vec<FunctionSnapshot>,
pub modified: Vec<FunctionSnapshot>,
pub removed: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<SnapshotSummary>,
}
pub fn compute_delta(base: &Snapshot, current: &Snapshot) -> DeltaSnapshot {
use std::collections::HashMap;
let base_map: HashMap<&str, &FunctionSnapshot> = base
.functions
.iter()
.map(|f| (f.function_id.as_str(), f))
.collect();
let current_map: HashMap<&str, ()> = current
.functions
.iter()
.map(|f| (f.function_id.as_str(), ()))
.collect();
let added: Vec<FunctionSnapshot> = current
.functions
.iter()
.filter(|f| !base_map.contains_key(f.function_id.as_str()))
.cloned()
.collect();
let modified: Vec<FunctionSnapshot> = current
.functions
.iter()
.filter(|f| {
base_map
.get(f.function_id.as_str())
.map(|bf| *bf != *f)
.unwrap_or(false)
})
.cloned()
.collect();
let removed: Vec<String> = base
.functions
.iter()
.filter(|f| !current_map.contains_key(f.function_id.as_str()))
.map(|f| f.function_id.clone())
.collect();
DeltaSnapshot {
schema_version: DELTA_SNAPSHOT_SCHEMA_VERSION,
snapshot_schema_version: current.schema_version,
commit: current.commit.clone(),
analysis: current.analysis.clone(),
base_sha: base.commit.sha.clone(),
added,
modified,
removed,
summary: current.summary.clone(),
}
}
pub fn apply_delta(base: Snapshot, delta: DeltaSnapshot) -> Snapshot {
use std::collections::HashMap;
let mut functions: HashMap<String, FunctionSnapshot> = base
.functions
.into_iter()
.map(|f| (f.function_id.clone(), f))
.collect();
for id in &delta.removed {
functions.remove(id);
}
for func in delta.modified {
functions.insert(func.function_id.clone(), func);
}
for func in delta.added {
functions.insert(func.function_id.clone(), func);
}
let mut result: Vec<FunctionSnapshot> = functions.into_values().collect();
result.sort_by(|a, b| a.function_id.cmp(&b.function_id));
Snapshot {
schema_version: delta.snapshot_schema_version,
commit: delta.commit,
analysis: delta.analysis,
functions: result,
summary: delta.summary,
aggregates: None,
triage: None,
architecture: None,
co_change: None,
}
}
pub fn persist_delta(repo_root: &Path, delta: &DeltaSnapshot) -> Result<()> {
let path = delta_snapshot_path(repo_root, &delta.commit.sha);
let json = serde_json::to_string_pretty(delta).context("failed to serialize delta snapshot")?;
let compressed =
zstd::encode_all(json.as_bytes(), 3).context("failed to compress delta snapshot")?;
atomic_write_bytes(&path, &compressed)
.with_context(|| format!("failed to persist delta snapshot: {}", path.display()))
}
pub fn hotspots_dir(repo_root: &Path) -> PathBuf {
repo_root.join(".hotspots")
}
pub fn ensure_gitignored(repo_root: &Path) {
let gitignore_path = repo_root.join(".gitignore");
let existing = std::fs::read_to_string(&gitignore_path).unwrap_or_default();
let already_ignored = existing.lines().any(|line| {
matches!(
line.trim(),
".hotspots" | ".hotspots/" | "/.hotspots" | "/.hotspots/"
)
});
if already_ignored {
return;
}
let mut updated = existing;
if !updated.is_empty() && !updated.ends_with('\n') {
updated.push('\n');
}
updated.push_str(".hotspots/\n");
let _ = std::fs::write(&gitignore_path, updated);
}
#[cfg(test)]
mod ensure_gitignored_tests {
use super::ensure_gitignored;
#[test]
fn creates_gitignore_with_entry_when_missing() {
let dir = tempfile::tempdir().unwrap();
ensure_gitignored(dir.path());
let contents = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
assert!(contents.contains(".hotspots/"));
}
#[test]
fn appends_entry_to_existing_gitignore() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".gitignore"), "target/\n").unwrap();
ensure_gitignored(dir.path());
let contents = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
assert!(contents.contains("target/"));
assert!(contents.contains(".hotspots/"));
}
#[test]
fn is_idempotent_when_already_present() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".gitignore"), "target/\n.hotspots/\n").unwrap();
ensure_gitignored(dir.path());
let contents = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
assert_eq!(contents.matches(".hotspots/").count(), 1);
}
#[test]
fn recognizes_bare_and_rooted_variants_as_already_ignored() {
for variant in [".hotspots", ".hotspots/", "/.hotspots", "/.hotspots/"] {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".gitignore"), format!("{variant}\n")).unwrap();
ensure_gitignored(dir.path());
let contents = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
assert_eq!(
contents,
format!("{variant}\n"),
"should not duplicate for variant {variant:?}"
);
}
}
#[test]
fn missing_dir_does_not_panic() {
ensure_gitignored(std::path::Path::new("/nonexistent/path/for/test"));
}
}
pub fn snapshots_dir(repo_root: &Path) -> PathBuf {
hotspots_dir(repo_root).join("snapshots")
}
pub fn index_path(repo_root: &Path) -> PathBuf {
hotspots_dir(repo_root).join("index.json")
}
pub fn snapshot_path(repo_root: &Path, commit_sha: &str) -> PathBuf {
snapshots_dir(repo_root).join(format!("{}.json.zst", commit_sha))
}
pub fn delta_snapshot_path(repo_root: &Path, commit_sha: &str) -> PathBuf {
snapshots_dir(repo_root).join(format!("{}.delta.json.zst", commit_sha))
}
pub fn snapshot_path_existing(repo_root: &Path, commit_sha: &str) -> Option<PathBuf> {
let zst = snapshot_path(repo_root, commit_sha);
if zst.exists() {
return Some(zst);
}
let json = snapshots_dir(repo_root).join(format!("{}.json", commit_sha));
if json.exists() {
return Some(json);
}
None
}
pub fn load_snapshot(repo_root: &Path, commit_sha: &str) -> Result<Option<Snapshot>> {
if let Some(path) = snapshot_path_existing(repo_root, commit_sha) {
return Ok(Some(read_snapshot_file(&path)?));
}
let dpath = delta_snapshot_path(repo_root, commit_sha);
if dpath.exists() {
let compressed = std::fs::read(&dpath)
.with_context(|| format!("failed to read delta: {}", dpath.display()))?;
let bytes = zstd::decode_all(compressed.as_slice())
.with_context(|| format!("failed to decompress delta: {}", dpath.display()))?;
let json = String::from_utf8(bytes).context("delta snapshot contains invalid UTF-8")?;
let delta: DeltaSnapshot = serde_json::from_str(&json)
.with_context(|| format!("failed to parse delta: {}", dpath.display()))?;
let base = load_snapshot(repo_root, &delta.base_sha)?.ok_or_else(|| {
anyhow::anyhow!(
"base snapshot {} not found for delta {}",
delta.base_sha,
commit_sha
)
})?;
return Ok(Some(apply_delta(base, delta)));
}
Ok(None)
}
fn read_snapshot_file(path: &Path) -> Result<Snapshot> {
let is_compressed = path
.file_name()
.and_then(|n| n.to_str())
.map(|n| n.ends_with(".json.zst"))
.unwrap_or(false);
let json: String = if is_compressed {
let compressed = std::fs::read(path)
.with_context(|| format!("failed to read snapshot: {}", path.display()))?;
let bytes = zstd::decode_all(compressed.as_slice())
.with_context(|| format!("failed to decompress snapshot: {}", path.display()))?;
String::from_utf8(bytes).context("snapshot contains invalid UTF-8")?
} else {
std::fs::read_to_string(path)
.with_context(|| format!("failed to read snapshot: {}", path.display()))?
};
Snapshot::from_json(&json)
.with_context(|| format!("failed to parse snapshot: {}", path.display()))
}
pub fn atomic_write(path: &Path, contents: &str) -> Result<()> {
use std::fs;
use std::io::Write;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create directory: {}", parent.display()))?;
}
let temp_path = path.with_extension("tmp");
let mut file = fs::File::create(&temp_path)
.with_context(|| format!("failed to create temp file: {}", temp_path.display()))?;
file.write_all(contents.as_bytes())
.with_context(|| format!("failed to write to temp file: {}", temp_path.display()))?;
file.sync_all()
.with_context(|| format!("failed to sync temp file: {}", temp_path.display()))?;
drop(file);
fs::rename(&temp_path, path)
.with_context(|| format!("failed to rename temp file to: {}", path.display()))?;
Ok(())
}
pub fn atomic_write_bytes(path: &Path, contents: &[u8]) -> Result<()> {
use std::fs;
use std::io::Write;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create directory: {}", parent.display()))?;
}
let temp_path = path.with_extension("tmp");
let mut file = fs::File::create(&temp_path)
.with_context(|| format!("failed to create temp file: {}", temp_path.display()))?;
file.write_all(contents)
.with_context(|| format!("failed to write to temp file: {}", temp_path.display()))?;
file.sync_all()
.with_context(|| format!("failed to sync temp file: {}", temp_path.display()))?;
drop(file);
fs::rename(&temp_path, path)
.with_context(|| format!("failed to rename temp file to: {}", path.display()))?;
Ok(())
}
pub fn persist_snapshot(repo_root: &Path, snapshot: &Snapshot, force: bool) -> Result<()> {
ensure_gitignored(repo_root);
let snapshot_path = snapshot_path(repo_root, snapshot.commit_sha());
let canonical_json = Snapshot::from_json(&snapshot.to_json()?)
.context("failed to normalize snapshot for canonical form")?
.to_json()?;
if !force {
if let Some(existing) = load_snapshot(repo_root, snapshot.commit_sha())? {
if existing.to_json()? == canonical_json {
return Ok(());
}
anyhow::bail!(
"snapshot already exists and differs: {} (snapshots are immutable; use --force to overwrite)",
snapshot_path.display()
);
}
}
let compressed =
zstd::encode_all(canonical_json.as_bytes(), 3).context("failed to compress snapshot")?;
atomic_write_bytes(&snapshot_path, &compressed)
.with_context(|| format!("failed to persist snapshot: {}", snapshot_path.display()))?;
Ok(())
}
pub fn append_to_index(repo_root: &Path, snapshot: &Snapshot) -> Result<()> {
let index_path = index_path(repo_root);
let mut index = Index::load_or_new(&index_path)?;
index.add_commit(IndexEntry {
sha: snapshot.commit.sha.clone(),
parents: snapshot.commit.parents.clone(),
timestamp: snapshot.commit.timestamp,
});
let json = index.to_json()?;
atomic_write(&index_path, &json)
.with_context(|| format!("failed to update index: {}", index_path.display()))?;
Ok(())
}
pub fn rebuild_index(repo_root: &Path) -> Result<Index> {
let snapshots_dir = snapshots_dir(repo_root);
if !snapshots_dir.exists() {
return Ok(Index::new());
}
let mut index = Index::new();
let entries = std::fs::read_dir(&snapshots_dir).with_context(|| {
format!(
"failed to read snapshots directory: {}",
snapshots_dir.display()
)
})?;
for entry_result in entries {
let entry = entry_result?;
let path = entry.path();
let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if !file_name.ends_with(".json.zst") && !file_name.ends_with(".json") {
continue;
}
let snapshot = match read_snapshot_file(&path) {
Ok(s) => s,
Err(e) => {
eprintln!(
"Warning: failed to parse snapshot {}: {}",
path.display(),
e
);
continue;
}
};
index.add_commit(IndexEntry {
sha: snapshot.commit.sha,
parents: snapshot.commit.parents,
timestamp: snapshot.commit.timestamp,
});
}
Ok(index)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::report::MetricsReport;
fn create_test_snapshot() -> Snapshot {
let git_context = GitContext {
head_sha: "abc123".to_string(),
parent_shas: vec!["def456".to_string()],
timestamp: 1705600000,
branch: Some("main".to_string()),
is_detached: false,
message: Some("test commit".to_string()),
author: Some("Test Author".to_string()),
is_fix_commit: Some(false),
is_revert_commit: Some(false),
ticket_ids: vec![],
};
let report = FunctionRiskReport {
file: "src/foo.ts".to_string(),
function: "handler".to_string(),
line: 42,
language: Language::TypeScript,
metrics: MetricsReport {
cc: 5,
nd: 2,
fo: 3,
ns: 1,
loc: 10,
missing_docstring: false,
},
risk: RiskReport {
r_cc: 2.0,
r_nd: 1.0,
r_fo: 1.0,
r_ns: 1.0,
},
lrs: 4.8,
band: RiskBand::Moderate,
suppression_reason: None,
callees: vec![],
explanation: None,
};
Snapshot::new(git_context, vec![report])
}
#[test]
fn test_snapshot_serialization() {
let snapshot = create_test_snapshot();
let json = snapshot.to_json().expect("should serialize");
assert!(json.contains(&format!("\"schema_version\": {SNAPSHOT_SCHEMA_VERSION}")));
assert!(json.contains("\"sha\": \"abc123\""));
assert!(json.contains("\"function_id\""));
let deserialized = Snapshot::from_json(&json).expect("should deserialize");
assert_eq!(deserialized.commit.sha, snapshot.commit.sha);
assert_eq!(deserialized.functions.len(), snapshot.functions.len());
}
#[test]
fn test_function_id_format() {
let snapshot = create_test_snapshot();
assert_eq!(snapshot.functions[0].function_id, "src/foo.ts::handler");
}
#[test]
fn test_snapshot_enricher_with_churn() {
use crate::git::FileChurn;
let snapshot = create_test_snapshot();
let mut churn_map = std::collections::HashMap::new();
churn_map.insert(
"src/foo.ts".to_string(),
FileChurn {
file: "src/foo.ts".to_string(),
lines_added: 10,
lines_deleted: 5,
},
);
let snapshot = SnapshotEnricher::new(snapshot)
.with_churn(&churn_map)
.build();
let churn = snapshot.functions[0]
.churn
.as_ref()
.expect("churn should be set");
assert_eq!(churn.lines_added, 10);
assert_eq!(churn.lines_deleted, 5);
}
#[test]
fn test_snapshot_enricher_enrich_computes_summary() {
let snapshot = create_test_snapshot();
let tmp = tempfile::tempdir().unwrap();
let snapshot = SnapshotEnricher::new(snapshot).enrich(tmp.path()).build();
let summary = snapshot.summary.as_ref().expect("summary should be set");
assert_eq!(summary.total_functions, 1);
assert_eq!(
summary.signal_confidence,
crate::aggregates::SignalConfidence::Low
);
assert_eq!(summary.conventional_prefix_rate, None);
}
#[test]
fn test_snapshot_deserializes_old_summary_json_missing_signal_confidence_fields() {
let snapshot = create_test_snapshot();
let tmp = tempfile::tempdir().unwrap();
let snapshot = SnapshotEnricher::new(snapshot).enrich(tmp.path()).build();
let mut value: serde_json::Value =
serde_json::from_str(&snapshot.to_json().unwrap()).unwrap();
value["summary"]
.as_object_mut()
.unwrap()
.remove("signal_confidence");
value["summary"]
.as_object_mut()
.unwrap()
.remove("conventional_prefix_rate");
let old_format_json = serde_json::to_string(&value).unwrap();
let reloaded = Snapshot::from_json(&old_format_json)
.expect("old-format summary JSON must still deserialize");
let summary = reloaded.summary.expect("summary should be set");
assert_eq!(
summary.signal_confidence,
crate::aggregates::SignalConfidence::Low
);
assert_eq!(summary.conventional_prefix_rate, None);
}
#[test]
fn test_snapshot_enricher_enrich_computes_activity_risk_and_tier() {
let snapshot = create_test_snapshot();
let tmp = tempfile::tempdir().unwrap();
let snapshot = SnapshotEnricher::new(snapshot).enrich(tmp.path()).build();
assert!(snapshot.functions[0].activity_risk.is_some());
assert!(snapshot.functions[0].tier.is_some());
}
#[test]
fn test_snapshot_enricher_build_passthrough() {
let snapshot = create_test_snapshot();
let built = SnapshotEnricher::new(snapshot.clone()).build();
assert_eq!(
built.functions[0].function_id,
snapshot.functions[0].function_id
);
assert_eq!(built.commit.sha, snapshot.commit.sha);
}
#[test]
fn test_index_ordering() {
let mut index = Index::new();
index.add_commit(IndexEntry {
sha: "zzz".to_string(),
parents: vec![],
timestamp: 2000,
});
index.add_commit(IndexEntry {
sha: "aaa".to_string(),
parents: vec![],
timestamp: 1000,
});
index.add_commit(IndexEntry {
sha: "mmm".to_string(),
parents: vec![],
timestamp: 2000,
});
assert_eq!(index.commits[0].sha, "aaa");
assert_eq!(index.commits[1].sha, "mmm");
assert_eq!(index.commits[2].sha, "zzz");
}
#[test]
fn test_relativize_paths_makes_file_and_function_id_repo_relative() {
let mut snapshot = create_test_snapshot();
for (file, expected) in [
("/repo/src/foo.ts", "src/foo.ts"),
("/repo/./src/foo.ts", "src/foo.ts"),
("src/foo.ts", "src/foo.ts"),
] {
snapshot.functions[0].file = file.to_string();
snapshot.functions[0].function_id = format!("{file}::foo");
snapshot.relativize_paths(std::path::Path::new("/repo"));
assert_eq!(snapshot.functions[0].file, expected);
assert_eq!(
snapshot.functions[0].function_id,
format!("{expected}::foo")
);
}
}
fn run_git_dated_test(dir: &std::path::Path, ts: i64, args: &[&str]) {
let date = format!("{ts} +0000");
let mut cmd = std::process::Command::new("git");
for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
cmd.env_remove(var);
}
let out = cmd
.current_dir(dir)
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@example.com")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@example.com")
.env("GIT_AUTHOR_DATE", &date)
.env("GIT_COMMITTER_DATE", &date)
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("run git");
assert!(
out.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
}
fn make_touch_test_repo() -> (tempfile::TempDir, i64) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
run_git_dated_test(root, 0, &["init", "-q"]);
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/foo.ts"), "export function handler() {}\n").unwrap();
run_git_dated_test(root, 1_700_000_000, &["add", "-A"]);
run_git_dated_test(root, 1_700_000_000, &["commit", "-q", "-m", "c1"]);
std::fs::write(
root.join("src/foo.ts"),
"export function handler() { return 1; }\n",
)
.unwrap();
run_git_dated_test(root, 1_700_100_000, &["add", "-A"]);
run_git_dated_test(root, 1_700_100_000, &["commit", "-q", "-m", "c2"]);
let as_of = 1_700_200_000;
(tmp, as_of)
}
fn snapshot_at(repo_root: &std::path::Path, as_of: i64) -> Snapshot {
let mut snapshot = create_test_snapshot();
snapshot.commit.timestamp = as_of;
snapshot.functions[0].file = repo_root.join("src/foo.ts").to_string_lossy().to_string();
snapshot
}
#[test]
fn touch_metrics_data_split_matches_populate_touch_metrics() {
let (tmp, as_of) = make_touch_test_repo();
let repo_root = tmp.path();
let mut via_populate = snapshot_at(repo_root, as_of);
via_populate
.populate_touch_metrics(repo_root, 365)
.expect("populate_touch_metrics");
let mut via_split = snapshot_at(repo_root, as_of);
let (batched, stale_days) = via_split.fetch_touch_metrics_data(repo_root, 365);
via_split.apply_touch_metrics_data(repo_root, &batched, &stale_days);
assert_eq!(
via_populate.functions[0].touch_count,
via_split.functions[0].touch_count
);
assert_eq!(
via_populate.functions[0].days_since_last_change,
via_split.functions[0].days_since_last_change
);
assert_eq!(via_populate.functions[0].touch_count, Some(2));
}
#[test]
fn burst_score_data_split_matches_populate_burst_score() {
let (tmp, as_of) = make_touch_test_repo();
let repo_root = tmp.path();
let mut via_populate = snapshot_at(repo_root, as_of);
via_populate.populate_burst_score(repo_root);
let mut via_split = snapshot_at(repo_root, as_of);
let signals = crate::history_signals::compute_history_signals_for_repo(repo_root);
via_split.apply_burst_score_data(repo_root, &signals);
assert_eq!(
via_populate.functions[0].burst_score,
via_split.functions[0].burst_score
);
assert!(via_populate.functions[0].burst_score.is_some());
}
#[test]
fn with_touch_metrics_data_builder_matches_with_touch_metrics() {
let (tmp, as_of) = make_touch_test_repo();
let repo_root = tmp.path();
let a = SnapshotEnricher::new(snapshot_at(repo_root, as_of))
.with_touch_metrics(repo_root, 365)
.build();
let enricher = SnapshotEnricher::new(snapshot_at(repo_root, as_of));
let (batched, stale_days) = enricher.fetch_touch_metrics_data(repo_root, 365);
let b = enricher
.with_touch_metrics_data(repo_root, &batched, &stale_days)
.build();
assert_eq!(a.functions[0].touch_count, b.functions[0].touch_count);
assert_eq!(
a.functions[0].days_since_last_change,
b.functions[0].days_since_last_change
);
}
#[test]
fn with_burst_score_data_builder_matches_with_burst_score() {
let (tmp, as_of) = make_touch_test_repo();
let repo_root = tmp.path();
let a = SnapshotEnricher::new(snapshot_at(repo_root, as_of))
.with_burst_score(repo_root)
.build();
let signals = crate::history_signals::compute_history_signals_for_repo(repo_root);
let b = SnapshotEnricher::new(snapshot_at(repo_root, as_of))
.with_burst_score_data(repo_root, &signals)
.build();
assert_eq!(a.functions[0].burst_score, b.functions[0].burst_score);
}
fn make_coupling_test_repo() -> (tempfile::TempDir, i64) {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
run_git_dated_test(root, 0, &["init", "-q"]);
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/foo.ts"), "a\n").unwrap();
std::fs::write(root.join("src/bar.ts"), "a\n").unwrap();
run_git_dated_test(root, 1_700_000_000, &["add", "-A"]);
run_git_dated_test(root, 1_700_000_000, &["commit", "-q", "-m", "init"]);
for i in 0..12 {
let ts = 1_700_000_000 + (i + 1) * 100_000;
std::fs::write(root.join("src/foo.ts"), format!("a{i}\n")).unwrap();
std::fs::write(root.join("src/bar.ts"), format!("a{i}\n")).unwrap();
run_git_dated_test(root, ts, &["add", "-A"]);
let msg = format!("c{i}");
run_git_dated_test(root, ts, &["commit", "-q", "-m", &msg]);
}
let as_of = 1_700_000_000 + 13 * 100_000;
(tmp, as_of)
}
#[test]
fn apply_directed_coupling_data_matches_populate_directed_coupling() {
let (tmp, as_of) = make_coupling_test_repo();
let repo_root = tmp.path();
let partner_scores: std::collections::HashMap<String, f64> =
[("src/bar.ts".to_string(), 5.0)].into_iter().collect();
let mut via_populate = snapshot_at(repo_root, as_of);
via_populate.populate_directed_coupling(repo_root, &partner_scores);
let mut via_split = snapshot_at(repo_root, as_of);
let fetch = crate::coupling::fetch_directed_coupling_data(repo_root)
.expect("fixture has commit history");
let (dc_scores, _jaccard) =
crate::coupling::finish_directed_coupling(&fetch, &partner_scores);
via_split.apply_directed_coupling_data(repo_root, &dc_scores);
assert_eq!(
via_populate.functions[0].directed_coupling,
via_split.functions[0].directed_coupling
);
assert!(via_populate.functions[0].directed_coupling.is_some());
}
}