1use std::cmp::Ordering;
2use std::collections::{BTreeMap, BTreeSet};
3
4use codeint_model::RepoPath;
5use gix::ObjectId;
6use gix::objs::tree::{EntryMode, EntryRef};
7
8use crate::history::{SECONDS_PER_DAY, WalkDecision};
9use crate::{CommitId, CommitRange, GitError, Repository};
10
11#[cfg(test)]
12mod tests;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ChurnRange {
16 Days(u32),
17 Since { unix_seconds: i64 },
18 Commits(usize),
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct FileChurnSummary {
23 pub commits_analyzed: usize,
24 pub shallow: bool,
25 pub truncated_by_shallow_boundary: bool,
26 pub touches_by_file: BTreeMap<RepoPath, usize>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct CoChangeSummary {
31 pub commits_analyzed: usize,
32 pub commits_excluded_by_bulk_limit: usize,
33 pub shallow: bool,
34 pub truncated_by_shallow_boundary: bool,
35 pub touches_by_file: BTreeMap<RepoPath, usize>,
36 pub co_changes: BTreeMap<(RepoPath, RepoPath), usize>,
37}
38
39struct WalkOutcome {
40 commits_analyzed: usize,
41 shallow: bool,
42 truncated_by_shallow_boundary: bool,
43}
44
45impl ChurnRange {
46 fn into_commit_range(self, head_unix_seconds: i64) -> CommitRange {
47 match self {
48 ChurnRange::Days(days) => CommitRange::CommittedSince {
49 unix_seconds: head_unix_seconds.saturating_sub(i64::from(days) * SECONDS_PER_DAY),
50 },
51 ChurnRange::Since { unix_seconds } => CommitRange::CommittedSince { unix_seconds },
52 ChurnRange::Commits(count) => CommitRange::Latest(count),
53 }
54 }
55}
56
57impl Repository {
58 pub fn file_churn(&self, range: ChurnRange) -> Result<FileChurnSummary, GitError> {
59 let mut touches_by_file: BTreeMap<RepoPath, usize> = BTreeMap::new();
60 let outcome = self.walk_touched_commits(range, |touched| {
61 for path in touched {
62 *touches_by_file.entry(path).or_insert(0) += 1;
63 }
64 })?;
65 Ok(FileChurnSummary {
66 commits_analyzed: outcome.commits_analyzed,
67 shallow: outcome.shallow,
68 truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary,
69 touches_by_file,
70 })
71 }
72
73 pub fn co_change_coupling(
74 &self,
75 range: ChurnRange,
76 max_commit_files: usize,
77 allowed_paths: &BTreeSet<RepoPath>,
78 ) -> Result<CoChangeSummary, GitError> {
79 let mut commits_excluded_by_bulk_limit = 0usize;
80 let mut touches_by_file: BTreeMap<RepoPath, usize> = BTreeMap::new();
81 let mut co_changes: BTreeMap<(RepoPath, RepoPath), usize> = BTreeMap::new();
82 let outcome = self.walk_touched_commits(range, |touched| {
83 if touched.len() > max_commit_files {
84 commits_excluded_by_bulk_limit += 1;
85 return;
86 }
87 let measured: Vec<RepoPath> = touched
88 .into_iter()
89 .filter(|path| allowed_paths.contains(path))
90 .collect();
91 for path in &measured {
92 *touches_by_file.entry(path.clone()).or_insert(0) += 1;
93 }
94 for (index, left) in measured.iter().enumerate() {
95 for right in &measured[index + 1..] {
96 *co_changes.entry((left.clone(), right.clone())).or_insert(0) += 1;
97 }
98 }
99 })?;
100 Ok(CoChangeSummary {
101 commits_analyzed: outcome.commits_analyzed,
102 commits_excluded_by_bulk_limit,
103 shallow: outcome.shallow,
104 truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary,
105 touches_by_file,
106 co_changes,
107 })
108 }
109
110 fn walk_touched_commits(
111 &self,
112 range: ChurnRange,
113 on_commit: impl FnMut(BTreeSet<RepoPath>),
114 ) -> Result<WalkOutcome, GitError> {
115 let head = self.repository.head_id().map_err(GitError::NoHistory)?;
116 let shallow_boundary = self
117 .repository
118 .shallow_commits()
119 .map_err(GitError::NoHistory)?;
120 let shallow = shallow_boundary
121 .as_ref()
122 .is_some_and(|boundary| !boundary.is_empty());
123 let head_id = head.detach();
124 let head_commit =
125 self.repository
126 .find_commit(head_id)
127 .map_err(|source| GitError::History {
128 commit: CommitId(head_id),
129 source,
130 })?;
131 let head_time = head_commit
132 .time()
133 .map_err(|source| GitError::History {
134 commit: CommitId(head_id),
135 source,
136 })?
137 .seconds;
138 let effective = range.into_commit_range(head_time);
139 self.walk_commits(
140 head_id,
141 effective,
142 shallow,
143 shallow_boundary.as_ref(),
144 on_commit,
145 )
146 }
147
148 fn walk_commits(
149 &self,
150 start: ObjectId,
151 effective: CommitRange,
152 shallow: bool,
153 shallow_boundary: Option<&gix::shallow::Commits>,
154 mut on_commit: impl FnMut(BTreeSet<RepoPath>),
155 ) -> Result<WalkOutcome, GitError> {
156 let mut commits_analyzed = 0usize;
157 let mut truncated_by_shallow_boundary = false;
158 let mut next = Some(start);
159 while let Some(id) = next {
160 let commit = CommitId(id);
161 let found = self
162 .repository
163 .find_commit(id)
164 .map_err(|source| GitError::History { commit, source })?;
165 let committed_at = found
166 .time()
167 .map_err(|source| GitError::History { commit, source })?
168 .seconds;
169 let decision = effective.decide(commits_analyzed, committed_at);
170 if decision == WalkDecision::Stop {
171 break;
172 }
173 let at_boundary = shallow_boundary.is_some_and(|boundary| boundary.contains(&id));
174 if at_boundary {
175 truncated_by_shallow_boundary = true;
176 break;
177 }
178 let parent_id = found.parent_ids().next().map(|parent| parent.detach());
179 if decision == WalkDecision::Include {
180 commits_analyzed += 1;
181 let touched = self.touched_files_in_commit(commit, &found, parent_id)?;
182 on_commit(touched);
183 }
184 next = parent_id;
185 }
186 Ok(WalkOutcome {
187 commits_analyzed,
188 shallow,
189 truncated_by_shallow_boundary,
190 })
191 }
192
193 fn touched_files_in_commit(
194 &self,
195 commit: CommitId,
196 found: &gix::Commit<'_>,
197 parent_id: Option<ObjectId>,
198 ) -> Result<BTreeSet<RepoPath>, GitError> {
199 let new_tree = found
200 .tree()
201 .map_err(|source| GitError::CommitTree { commit, source })?;
202 let mut touched = BTreeSet::new();
203 let mut diff = TreeDiffer {
204 repository: &self.repository,
205 commit,
206 touched: &mut touched,
207 };
208 match parent_id {
209 Some(pid) => {
210 let parent_commit = CommitId(pid);
211 let old_tree = self
212 .repository
213 .find_commit(pid)
214 .and_then(|parent| parent.tree())
215 .map_err(|source| GitError::CommitTree {
216 commit: parent_commit,
217 source,
218 })?;
219 diff.trees("", &old_tree, &new_tree)?;
220 }
221 None => {
222 diff.collect_blobs("", &new_tree)?;
223 }
224 }
225 Ok(touched)
226 }
227}
228
229struct TreeDiffer<'a> {
230 repository: &'a gix::Repository,
231 commit: CommitId,
232 touched: &'a mut BTreeSet<RepoPath>,
233}
234
235struct TreeCursor<'a, I> {
236 iter: I,
237 next: Option<(EntryRef<'a>, &'a str)>,
238}
239
240impl<'a, I> TreeCursor<'a, I> {
241 fn new<'repo>(commit: CommitId, mut iter: I) -> Result<Self, GitError>
242 where
243 I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
244 {
245 let next = next_utf8_entry(commit, &mut iter)?;
246 Ok(Self { iter, next })
247 }
248
249 fn advance<'repo>(&mut self, commit: CommitId) -> Result<(), GitError>
250 where
251 I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
252 {
253 self.next = next_utf8_entry(commit, &mut self.iter)?;
254 Ok(())
255 }
256}
257
258impl TreeDiffer<'_> {
259 fn trees(
260 &mut self,
261 prefix: &str,
262 old_tree: &gix::Tree<'_>,
263 new_tree: &gix::Tree<'_>,
264 ) -> Result<(), GitError> {
265 if old_tree.id == new_tree.id {
266 return Ok(());
267 }
268 let mut old_cursor = TreeCursor::new(self.commit, old_tree.iter())?;
269 let mut new_cursor = TreeCursor::new(self.commit, new_tree.iter())?;
270 while self.step_trees(prefix, &mut old_cursor, &mut new_cursor)? {}
271 Ok(())
272 }
273
274 fn step_trees<'repo, 'a, I>(
275 &mut self,
276 prefix: &str,
277 old_cursor: &mut TreeCursor<'a, I>,
278 new_cursor: &mut TreeCursor<'a, I>,
279 ) -> Result<bool, GitError>
280 where
281 I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
282 {
283 match (old_cursor.next.take(), new_cursor.next.take()) {
284 (Some(old), Some(new)) => {
285 self.diff_pair(prefix, old, new, old_cursor, new_cursor)?;
286 Ok(true)
287 }
288 (Some((old, name)), None) => {
289 self.record_and_advance(prefix, old, name, old_cursor)?;
290 Ok(true)
291 }
292 (None, Some((new, name))) => {
293 self.record_and_advance(prefix, new, name, new_cursor)?;
294 Ok(true)
295 }
296 (None, None) => Ok(false),
297 }
298 }
299
300 fn diff_pair<'repo, 'a, I>(
301 &mut self,
302 prefix: &str,
303 old: (EntryRef<'a>, &'a str),
304 new: (EntryRef<'a>, &'a str),
305 old_cursor: &mut TreeCursor<'a, I>,
306 new_cursor: &mut TreeCursor<'a, I>,
307 ) -> Result<(), GitError>
308 where
309 I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
310 {
311 match old.0.cmp(&new.0) {
312 Ordering::Less => {
313 new_cursor.next = Some(new);
314 self.record_and_advance(prefix, old.0, old.1, old_cursor)
315 }
316 Ordering::Greater => {
317 old_cursor.next = Some(old);
318 self.record_and_advance(prefix, new.0, new.1, new_cursor)
319 }
320 Ordering::Equal => {
321 self.diff_matching_entries(prefix, old.0, new.0, new.1)?;
322 old_cursor.advance(self.commit)?;
323 new_cursor.advance(self.commit)
324 }
325 }
326 }
327
328 fn diff_matching_entries(
329 &mut self,
330 prefix: &str,
331 old: EntryRef<'_>,
332 new: EntryRef<'_>,
333 name: &str,
334 ) -> Result<(), GitError> {
335 if old.oid == new.oid && old.mode == new.mode {
336 return Ok(());
337 }
338 let path = join_prefix(prefix, name);
339 self.visit_changed(
340 &path,
341 (old.mode, old.oid.to_owned()),
342 (new.mode, new.oid.to_owned()),
343 )
344 }
345
346 fn record_and_advance<'repo, 'a, I>(
347 &mut self,
348 prefix: &str,
349 entry: EntryRef<'a>,
350 name: &str,
351 cursor: &mut TreeCursor<'a, I>,
352 ) -> Result<(), GitError>
353 where
354 I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
355 {
356 let path = join_prefix(prefix, name);
357 self.record_entry(&path, entry.mode, entry.oid.to_owned())?;
358 cursor.advance(self.commit)
359 }
360
361 fn visit_changed(
362 &mut self,
363 path: &str,
364 (old_mode, old_oid): (EntryMode, ObjectId),
365 (new_mode, new_oid): (EntryMode, ObjectId),
366 ) -> Result<(), GitError> {
367 if old_mode.is_tree() && new_mode.is_tree() {
368 let old_sub = find_tree(self.repository, self.commit, old_oid)?;
369 let new_sub = find_tree(self.repository, self.commit, new_oid)?;
370 return self.trees(path, &old_sub, &new_sub);
371 }
372 self.record_entry(path, old_mode, old_oid)?;
373 self.record_entry(path, new_mode, new_oid)
374 }
375
376 fn record_entry(&mut self, path: &str, mode: EntryMode, oid: ObjectId) -> Result<(), GitError> {
377 if mode.is_blob() {
378 if let Ok(repo_path) = RepoPath::new(path) {
379 self.touched.insert(repo_path);
380 }
381 } else if mode.is_tree() {
382 let subtree = find_tree(self.repository, self.commit, oid)?;
383 self.collect_blobs(path, &subtree)?;
384 }
385 Ok(())
386 }
387
388 fn collect_blobs(&mut self, prefix: &str, tree: &gix::Tree<'_>) -> Result<(), GitError> {
389 let mut iter = tree.iter();
390 while let Some((entry, name)) = next_utf8_entry(self.commit, &mut iter)? {
391 let path = join_prefix(prefix, name);
392 self.record_entry(&path, entry.mode, entry.oid.to_owned())?;
393 }
394 Ok(())
395 }
396}
397
398fn find_tree(
399 repository: &gix::Repository,
400 commit: CommitId,
401 oid: ObjectId,
402) -> Result<gix::Tree<'_>, GitError> {
403 repository
404 .find_tree(oid)
405 .map_err(|source| GitError::CommitTree { commit, source })
406}
407
408fn next_utf8_entry<'repo, 'a>(
409 commit: CommitId,
410 iter: &mut impl Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
411) -> Result<Option<(EntryRef<'a>, &'a str)>, GitError> {
412 for item in iter {
413 let entry = item.map_err(|source| GitError::CommitTree { commit, source })?;
414 if let Ok(name) = std::str::from_utf8(entry.inner.filename) {
415 return Ok(Some((entry.inner, name)));
416 }
417 }
418 Ok(None)
419}
420
421fn join_prefix(prefix: &str, name: &str) -> String {
422 if prefix.is_empty() {
423 name.to_owned()
424 } else {
425 format!("{prefix}/{name}")
426 }
427}