use crate::model::FileMetrics;
pub fn assign_hotspot_scores(files: &mut [FileMetrics]) {
let maxima = Maxima {
complexity: files
.iter()
.filter(|file| is_hotspot_source(&file.path))
.map(|file| file.structure.complexity_raw)
.fold(0.0_f64, f64::max),
context: files
.iter()
.filter(|file| is_hotspot_source(&file.path))
.map(|file| file.structure.context_cost_raw)
.fold(0.0_f64, f64::max),
churn_short: files
.iter()
.filter(|file| is_hotspot_source(&file.path))
.map(|file| file.churn_short.changed())
.max()
.unwrap_or(0) as f64,
churn_long: files
.iter()
.filter(|file| is_hotspot_source(&file.path))
.map(|file| file.churn_long.changed())
.max()
.unwrap_or(0) as f64,
};
for file in files.iter_mut() {
if !is_hotspot_source(&file.path) {
file.hotspot_score = 0.0;
continue;
}
let complexity = normalize(file.structure.complexity_raw, maxima.complexity);
let context = normalize(file.structure.context_cost_raw, maxima.context);
let churn_short = normalize(file.churn_short.changed() as f64, maxima.churn_short);
let churn_long = normalize(file.churn_long.changed() as f64, maxima.churn_long);
file.hotspot_score =
complexity * (1.0 + 0.9 * churn_short + 0.35 * churn_long) + 0.25 * context;
}
files.sort_by(|left, right| {
right
.hotspot_score
.total_cmp(&left.hotspot_score)
.then_with(|| left.path.cmp(&right.path))
});
}
fn is_hotspot_source(path: &str) -> bool {
let extension = std::path::Path::new(path)
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default();
matches!(
extension,
"rs" | "py"
| "sh"
| "bash"
| "js"
| "jsx"
| "ts"
| "tsx"
| "c"
| "cc"
| "cpp"
| "h"
| "hpp"
| "glsl"
| "glslh"
| "wgsl"
| "vert"
| "frag"
| "comp"
| "mesh"
| "task"
)
}
#[derive(Debug)]
struct Maxima {
complexity: f64,
context: f64,
churn_short: f64,
churn_long: f64,
}
fn normalize(value: f64, maximum: f64) -> f64 {
if maximum > 0.0 { value / maximum } else { 0.0 }
}
#[cfg(test)]
mod tests {
use crate::model::{Churn, FileMetrics, LineStats, SourceKind, StructureMetrics};
use super::assign_hotspot_scores;
fn file(path: &str, complexity: f64, churn: u64) -> FileMetrics {
FileMetrics {
path: path.to_string(),
language: "Rust".to_string(),
crate_name: None,
kind: SourceKind::Production,
lines: LineStats::default(),
inline_test_lines: LineStats::default(),
churn_short: Churn {
added: churn,
deleted: 0,
},
churn_long: Churn {
added: churn,
deleted: 0,
},
structure: StructureMetrics {
complexity_raw: complexity,
context_cost_raw: complexity,
..StructureMetrics::default()
},
hotspot_score: 0.0,
}
}
#[test]
fn recent_complex_file_ranks_first() {
let mut files = vec![file("quiet.rs", 10.0, 0), file("active.rs", 10.0, 100)];
assign_hotspot_scores(&mut files);
assert_eq!(files[0].path, "active.rs");
}
}