| 1 | use std::path::Path; |
| 2 | use std::time::Duration; |
| 3 | |
| 4 | use crate::command::GitEnv; |
| 5 | use crate::error::{Error, Result}; |
| 6 | use crate::history::{git, read_capped, validate_oid}; |
| 7 | |
| 8 | pub const MAX_COMMITS: usize = 48; |
| 9 | const WALK_TIMEOUT: Duration = Duration::from_secs(5); |
| 10 | const REC: u8 = 0x1e; |
| 11 | |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | pub struct CommitChurn { |
| 14 | pub oid: String, |
| 15 | pub lines: u64, |
| 16 | } |
| 17 | |
| 18 | pub async fn recent_churn( |
| 19 | env: &GitEnv, |
| 20 | repo: &Path, |
| 21 | head: &str, |
| 22 | limit: usize, |
| 23 | ) -> Result<Vec<CommitChurn>> { |
| 24 | validate_oid(head)?; |
| 25 | let limit = limit.clamp(1, MAX_COMMITS); |
| 26 | let cmd = git(env, "log") |
| 27 | .git_dir(repo) |
| 28 | .arg("--no-color") |
| 29 | .arg("--no-ext-diff") |
| 30 | .arg("--no-textconv") |
| 31 | .arg("--no-renames") |
| 32 | .arg("--root") |
| 33 | .arg("--shortstat") |
| 34 | .arg("--diff-merges=first-parent") |
| 35 | .arg("--format=%x1e%H") |
| 36 | .user_opt("--max-count", &limit.to_string())? |
| 37 | .user_revs(&[head])?; |
| 38 | let read = match tokio::time::timeout(WALK_TIMEOUT, read_capped(cmd)).await { |
| 39 | Ok(read) => read?, |
| 40 | Err(_) => return Err(Error::Failed("commit walk timed out".into())), |
| 41 | }; |
| 42 | Ok(parse(&read.0)) |
| 43 | } |
| 44 | |
| 45 | fn parse(buf: &[u8]) -> Vec<CommitChurn> { |
| 46 | buf.split(|&b| b == REC) |
| 47 | .filter_map(|rec| { |
| 48 | let text = String::from_utf8_lossy(rec); |
| 49 | let mut lines = text.lines(); |
| 50 | let oid = lines.next()?.trim(); |
| 51 | validate_oid(oid).ok()?; |
| 52 | let lines_changed = lines.map(stat_line_total).sum(); |
| 53 | Some(CommitChurn { |
| 54 | oid: oid.to_owned(), |
| 55 | lines: lines_changed, |
| 56 | }) |
| 57 | }) |
| 58 | .collect() |
| 59 | } |
| 60 | |
| 61 | fn stat_line_total(line: &str) -> u64 { |
| 62 | if !line.contains("changed") { |
| 63 | return 0; |
| 64 | } |
| 65 | line.split(',') |
| 66 | .filter(|part| part.contains("insertion") || part.contains("deletion")) |
| 67 | .filter_map(|part| part.split_whitespace().next()?.parse::<u64>().ok()) |
| 68 | .sum() |
| 69 | } |