codeint-git 0.10.4

Git repository inspection, history, and caching for codeint
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};

use codeint_model::RepoPath;
use gix::ObjectId;
use gix::objs::tree::{EntryMode, EntryRef};

use crate::history::{SECONDS_PER_DAY, WalkDecision};
use crate::{CommitId, CommitRange, GitError, Repository};

#[cfg(test)]
mod tests;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChurnRange {
    Days(u32),
    Since { unix_seconds: i64 },
    Commits(usize),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChurnSummary {
    pub commits_analyzed: usize,
    pub shallow: bool,
    pub truncated_by_shallow_boundary: bool,
    pub touches_by_file: BTreeMap<RepoPath, usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoChangeSummary {
    pub commits_analyzed: usize,
    pub commits_excluded_by_bulk_limit: usize,
    pub shallow: bool,
    pub truncated_by_shallow_boundary: bool,
    pub touches_by_file: BTreeMap<RepoPath, usize>,
    pub co_changes: BTreeMap<(RepoPath, RepoPath), usize>,
}

struct WalkOutcome {
    commits_analyzed: usize,
    shallow: bool,
    truncated_by_shallow_boundary: bool,
}

impl ChurnRange {
    fn into_commit_range(self, head_unix_seconds: i64) -> CommitRange {
        match self {
            ChurnRange::Days(days) => CommitRange::CommittedSince {
                unix_seconds: head_unix_seconds.saturating_sub(i64::from(days) * SECONDS_PER_DAY),
            },
            ChurnRange::Since { unix_seconds } => CommitRange::CommittedSince { unix_seconds },
            ChurnRange::Commits(count) => CommitRange::Latest(count),
        }
    }
}

impl Repository {
    pub fn file_churn(&self, range: ChurnRange) -> Result<FileChurnSummary, GitError> {
        let mut touches_by_file: BTreeMap<RepoPath, usize> = BTreeMap::new();
        let outcome = self.walk_touched_commits(range, |touched| {
            for path in touched {
                *touches_by_file.entry(path).or_insert(0) += 1;
            }
        })?;
        Ok(FileChurnSummary {
            commits_analyzed: outcome.commits_analyzed,
            shallow: outcome.shallow,
            truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary,
            touches_by_file,
        })
    }

    pub fn co_change_coupling(
        &self,
        range: ChurnRange,
        max_commit_files: usize,
        allowed_paths: &BTreeSet<RepoPath>,
    ) -> Result<CoChangeSummary, GitError> {
        let mut commits_excluded_by_bulk_limit = 0usize;
        let mut touches_by_file: BTreeMap<RepoPath, usize> = BTreeMap::new();
        let mut co_changes: BTreeMap<(RepoPath, RepoPath), usize> = BTreeMap::new();
        let outcome = self.walk_touched_commits(range, |touched| {
            if touched.len() > max_commit_files {
                commits_excluded_by_bulk_limit += 1;
                return;
            }
            let measured: Vec<RepoPath> = touched
                .into_iter()
                .filter(|path| allowed_paths.contains(path))
                .collect();
            for path in &measured {
                *touches_by_file.entry(path.clone()).or_insert(0) += 1;
            }
            for (index, left) in measured.iter().enumerate() {
                for right in &measured[index + 1..] {
                    *co_changes.entry((left.clone(), right.clone())).or_insert(0) += 1;
                }
            }
        })?;
        Ok(CoChangeSummary {
            commits_analyzed: outcome.commits_analyzed,
            commits_excluded_by_bulk_limit,
            shallow: outcome.shallow,
            truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary,
            touches_by_file,
            co_changes,
        })
    }

    fn walk_touched_commits(
        &self,
        range: ChurnRange,
        on_commit: impl FnMut(BTreeSet<RepoPath>),
    ) -> Result<WalkOutcome, GitError> {
        let head = self.repository.head_id().map_err(GitError::NoHistory)?;
        let shallow_boundary = self
            .repository
            .shallow_commits()
            .map_err(GitError::NoHistory)?;
        let shallow = shallow_boundary
            .as_ref()
            .is_some_and(|boundary| !boundary.is_empty());
        let head_id = head.detach();
        let head_commit =
            self.repository
                .find_commit(head_id)
                .map_err(|source| GitError::History {
                    commit: CommitId(head_id),
                    source,
                })?;
        let head_time = head_commit
            .time()
            .map_err(|source| GitError::History {
                commit: CommitId(head_id),
                source,
            })?
            .seconds;
        let effective = range.into_commit_range(head_time);
        self.walk_commits(
            head_id,
            effective,
            shallow,
            shallow_boundary.as_ref(),
            on_commit,
        )
    }

    fn walk_commits(
        &self,
        start: ObjectId,
        effective: CommitRange,
        shallow: bool,
        shallow_boundary: Option<&gix::shallow::Commits>,
        mut on_commit: impl FnMut(BTreeSet<RepoPath>),
    ) -> Result<WalkOutcome, GitError> {
        let mut commits_analyzed = 0usize;
        let mut truncated_by_shallow_boundary = false;
        let mut next = Some(start);
        while let Some(id) = next {
            let commit = CommitId(id);
            let found = self
                .repository
                .find_commit(id)
                .map_err(|source| GitError::History { commit, source })?;
            let committed_at = found
                .time()
                .map_err(|source| GitError::History { commit, source })?
                .seconds;
            let decision = effective.decide(commits_analyzed, committed_at);
            if decision == WalkDecision::Stop {
                break;
            }
            let at_boundary = shallow_boundary.is_some_and(|boundary| boundary.contains(&id));
            if at_boundary {
                truncated_by_shallow_boundary = true;
                break;
            }
            let parent_id = found.parent_ids().next().map(|parent| parent.detach());
            if decision == WalkDecision::Include {
                commits_analyzed += 1;
                let touched = self.touched_files_in_commit(commit, &found, parent_id)?;
                on_commit(touched);
            }
            next = parent_id;
        }
        Ok(WalkOutcome {
            commits_analyzed,
            shallow,
            truncated_by_shallow_boundary,
        })
    }

    fn touched_files_in_commit(
        &self,
        commit: CommitId,
        found: &gix::Commit<'_>,
        parent_id: Option<ObjectId>,
    ) -> Result<BTreeSet<RepoPath>, GitError> {
        let new_tree = found
            .tree()
            .map_err(|source| GitError::CommitTree { commit, source })?;
        let mut touched = BTreeSet::new();
        let mut diff = TreeDiffer {
            repository: &self.repository,
            commit,
            touched: &mut touched,
        };
        match parent_id {
            Some(pid) => {
                let parent_commit = CommitId(pid);
                let old_tree = self
                    .repository
                    .find_commit(pid)
                    .and_then(|parent| parent.tree())
                    .map_err(|source| GitError::CommitTree {
                        commit: parent_commit,
                        source,
                    })?;
                diff.trees("", &old_tree, &new_tree)?;
            }
            None => {
                diff.collect_blobs("", &new_tree)?;
            }
        }
        Ok(touched)
    }
}

struct TreeDiffer<'a> {
    repository: &'a gix::Repository,
    commit: CommitId,
    touched: &'a mut BTreeSet<RepoPath>,
}

struct TreeCursor<'a, I> {
    iter: I,
    next: Option<(EntryRef<'a>, &'a str)>,
}

impl<'a, I> TreeCursor<'a, I> {
    fn new<'repo>(commit: CommitId, mut iter: I) -> Result<Self, GitError>
    where
        I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
    {
        let next = next_utf8_entry(commit, &mut iter)?;
        Ok(Self { iter, next })
    }

    fn advance<'repo>(&mut self, commit: CommitId) -> Result<(), GitError>
    where
        I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
    {
        self.next = next_utf8_entry(commit, &mut self.iter)?;
        Ok(())
    }
}

impl TreeDiffer<'_> {
    fn trees(
        &mut self,
        prefix: &str,
        old_tree: &gix::Tree<'_>,
        new_tree: &gix::Tree<'_>,
    ) -> Result<(), GitError> {
        if old_tree.id == new_tree.id {
            return Ok(());
        }
        let mut old_cursor = TreeCursor::new(self.commit, old_tree.iter())?;
        let mut new_cursor = TreeCursor::new(self.commit, new_tree.iter())?;
        while self.step_trees(prefix, &mut old_cursor, &mut new_cursor)? {}
        Ok(())
    }

    fn step_trees<'repo, 'a, I>(
        &mut self,
        prefix: &str,
        old_cursor: &mut TreeCursor<'a, I>,
        new_cursor: &mut TreeCursor<'a, I>,
    ) -> Result<bool, GitError>
    where
        I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
    {
        match (old_cursor.next.take(), new_cursor.next.take()) {
            (Some(old), Some(new)) => {
                self.diff_pair(prefix, old, new, old_cursor, new_cursor)?;
                Ok(true)
            }
            (Some((old, name)), None) => {
                self.record_and_advance(prefix, old, name, old_cursor)?;
                Ok(true)
            }
            (None, Some((new, name))) => {
                self.record_and_advance(prefix, new, name, new_cursor)?;
                Ok(true)
            }
            (None, None) => Ok(false),
        }
    }

    fn diff_pair<'repo, 'a, I>(
        &mut self,
        prefix: &str,
        old: (EntryRef<'a>, &'a str),
        new: (EntryRef<'a>, &'a str),
        old_cursor: &mut TreeCursor<'a, I>,
        new_cursor: &mut TreeCursor<'a, I>,
    ) -> Result<(), GitError>
    where
        I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
    {
        match old.0.cmp(&new.0) {
            Ordering::Less => {
                new_cursor.next = Some(new);
                self.record_and_advance(prefix, old.0, old.1, old_cursor)
            }
            Ordering::Greater => {
                old_cursor.next = Some(old);
                self.record_and_advance(prefix, new.0, new.1, new_cursor)
            }
            Ordering::Equal => {
                self.diff_matching_entries(prefix, old.0, new.0, new.1)?;
                old_cursor.advance(self.commit)?;
                new_cursor.advance(self.commit)
            }
        }
    }

    fn diff_matching_entries(
        &mut self,
        prefix: &str,
        old: EntryRef<'_>,
        new: EntryRef<'_>,
        name: &str,
    ) -> Result<(), GitError> {
        if old.oid == new.oid && old.mode == new.mode {
            return Ok(());
        }
        let path = join_prefix(prefix, name);
        self.visit_changed(
            &path,
            (old.mode, old.oid.to_owned()),
            (new.mode, new.oid.to_owned()),
        )
    }

    fn record_and_advance<'repo, 'a, I>(
        &mut self,
        prefix: &str,
        entry: EntryRef<'a>,
        name: &str,
        cursor: &mut TreeCursor<'a, I>,
    ) -> Result<(), GitError>
    where
        I: Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
    {
        let path = join_prefix(prefix, name);
        self.record_entry(&path, entry.mode, entry.oid.to_owned())?;
        cursor.advance(self.commit)
    }

    fn visit_changed(
        &mut self,
        path: &str,
        (old_mode, old_oid): (EntryMode, ObjectId),
        (new_mode, new_oid): (EntryMode, ObjectId),
    ) -> Result<(), GitError> {
        if old_mode.is_tree() && new_mode.is_tree() {
            let old_sub = find_tree(self.repository, self.commit, old_oid)?;
            let new_sub = find_tree(self.repository, self.commit, new_oid)?;
            return self.trees(path, &old_sub, &new_sub);
        }
        self.record_entry(path, old_mode, old_oid)?;
        self.record_entry(path, new_mode, new_oid)
    }

    fn record_entry(&mut self, path: &str, mode: EntryMode, oid: ObjectId) -> Result<(), GitError> {
        if mode.is_blob() {
            if let Ok(repo_path) = RepoPath::new(path) {
                self.touched.insert(repo_path);
            }
        } else if mode.is_tree() {
            let subtree = find_tree(self.repository, self.commit, oid)?;
            self.collect_blobs(path, &subtree)?;
        }
        Ok(())
    }

    fn collect_blobs(&mut self, prefix: &str, tree: &gix::Tree<'_>) -> Result<(), GitError> {
        let mut iter = tree.iter();
        while let Some((entry, name)) = next_utf8_entry(self.commit, &mut iter)? {
            let path = join_prefix(prefix, name);
            self.record_entry(&path, entry.mode, entry.oid.to_owned())?;
        }
        Ok(())
    }
}

fn find_tree(
    repository: &gix::Repository,
    commit: CommitId,
    oid: ObjectId,
) -> Result<gix::Tree<'_>, GitError> {
    repository
        .find_tree(oid)
        .map_err(|source| GitError::CommitTree { commit, source })
}

fn next_utf8_entry<'repo, 'a>(
    commit: CommitId,
    iter: &mut impl Iterator<Item = Result<gix::object::tree::EntryRef<'repo, 'a>, gix::Error>>,
) -> Result<Option<(EntryRef<'a>, &'a str)>, GitError> {
    for item in iter {
        let entry = item.map_err(|source| GitError::CommitTree { commit, source })?;
        if let Ok(name) = std::str::from_utf8(entry.inner.filename) {
            return Ok(Some((entry.inner, name)));
        }
    }
    Ok(None)
}

fn join_prefix(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_owned()
    } else {
        format!("{prefix}/{name}")
    }
}