use std::path::Path; use std::time::Duration; use crate::command::GitEnv; use crate::error::{Error, Result}; use crate::history::{git, read_capped, validate_oid}; pub const MAX_COMMITS: usize = 48; const WALK_TIMEOUT: Duration = Duration::from_secs(5); const REC: u8 = 0x1e; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CommitChurn { pub oid: String, pub lines: u64, } pub async fn recent_churn( env: &GitEnv, repo: &Path, head: &str, limit: usize, ) -> Result> { validate_oid(head)?; let limit = limit.clamp(1, MAX_COMMITS); let cmd = git(env, "log") .git_dir(repo) .arg("--no-color") .arg("--no-ext-diff") .arg("--no-textconv") .arg("--no-renames") .arg("--root") .arg("--shortstat") .arg("--diff-merges=first-parent") .arg("--format=%x1e%H") .user_opt("--max-count", &limit.to_string())? .user_revs(&[head])?; let read = match tokio::time::timeout(WALK_TIMEOUT, read_capped(cmd)).await { Ok(read) => read?, Err(_) => return Err(Error::Failed("commit walk timed out".into())), }; Ok(parse(&read.0)) } fn parse(buf: &[u8]) -> Vec { buf.split(|&b| b == REC) .filter_map(|rec| { let text = String::from_utf8_lossy(rec); let mut lines = text.lines(); let oid = lines.next()?.trim(); validate_oid(oid).ok()?; let lines_changed = lines.map(stat_line_total).sum(); Some(CommitChurn { oid: oid.to_owned(), lines: lines_changed, }) }) .collect() } fn stat_line_total(line: &str) -> u64 { if !line.contains("changed") { return 0; } line.split(',') .filter(|part| part.contains("insertion") || part.contains("deletion")) .filter_map(|part| part.split_whitespace().next()?.parse::().ok()) .sum() }