codeint-git 0.10.5

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
#![forbid(unsafe_code)]

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;

use codeint_model::{InvalidRepoPath, RepoPath};
use gix::dir::entry::{Kind, Status};
use gix::dir::walk::EmissionMode;
use gix::dir::walk::delegate::Collect;
use gix::index::entry::{Flags, Mode, Stage, Stat, stat::Options as StatOptions};
use gix::index::fs::Metadata as IndexMetadata;

mod changed_lines;
mod churn;
mod history;
mod rename;
mod result_cache;
mod snapshot_lookup;
#[cfg(test)]
mod tests;

pub use changed_lines::LineRange;
pub use churn::{ChurnRange, CoChangeSummary, FileChurnSummary};
pub use history::{CommitRange, HistoryCommit};
pub use rename::{DEFAULT_RENAME_THRESHOLD, MAX_RENAME_THRESHOLD, RenameMap};
pub use result_cache::{ResultCache, ResultCacheError};
pub use snapshot_lookup::SnapshotFileLookup;

#[derive(Debug, thiserror::Error)]
pub enum GitError {
    #[error("{} is not inside a Git repository", start.display())]
    NotInRepository { start: PathBuf },
    #[error("{} is inside a bare Git repository, which has no working tree", start.display())]
    BareRepository { start: PathBuf },
    #[error("cannot open the Git repository that contains {}", start.display())]
    Open {
        start: PathBuf,
        #[source]
        source: gix::Error,
    },
    #[error("cannot list the files of the working tree")]
    Walk(#[source] gix::Error),
    #[error("a working tree path is not valid UTF-8: {path}")]
    NonUtf8Path {
        path: String,
        #[source]
        source: std::string::FromUtf8Error,
    },
    #[error(transparent)]
    InvalidPath(#[from] InvalidRepoPath),
    #[error("cannot read {path}")]
    Read {
        path: RepoPath,
        #[source]
        source: std::io::Error,
    },
    #[error("the Git ref {name:?} does not name a commit in this repository")]
    UnknownRef {
        name: String,
        #[source]
        source: gix::Error,
    },
    #[error("HEAD does not name a commit yet, so it has no merge-base with {base_ref:?}")]
    NoHeadCommit {
        base_ref: String,
        #[source]
        source: gix::Error,
    },
    #[error("{base_ref:?} and {head_ref:?} have no commit in common, so they have no merge-base")]
    NoMergeBase { base_ref: String, head_ref: String },
    #[error("cannot find the merge-base of {base_ref:?} and {head_ref:?}")]
    MergeBase {
        base_ref: String,
        head_ref: String,
        #[source]
        source: gix::Error,
    },
    #[error("HEAD does not name a commit yet, so the current branch has no history to measure")]
    NoHistory(#[source] gix::Error),
    #[error("cannot read commit {commit} of the history")]
    History {
        commit: CommitId,
        #[source]
        source: gix::Error,
    },
    #[error("cannot list the files of commit {commit}")]
    CommitTree {
        commit: CommitId,
        #[source]
        source: gix::Error,
    },
    #[error("cannot read {path} from commit {commit}")]
    ReadBlob {
        path: RepoPath,
        commit: CommitId,
        #[source]
        source: gix::Error,
    },
    #[error("{path} is {size_bytes} bytes, exceeding the {max_bytes}-byte limit")]
    FileTooLarge {
        path: RepoPath,
        size_bytes: u64,
        max_bytes: u64,
    },
}

const HEAD: &str = "HEAD";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CommitId(gix::ObjectId);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BlobId(gix::ObjectId);

pub struct Repository {
    repository: gix::Repository,
    root: PathBuf,
}

pub struct ChangedFiles {
    pub merge_base: CommitId,
    pub files: Vec<RepoPath>,
}

pub struct Snapshot {
    files: Vec<RepoPath>,
    submodules: Vec<RepoPath>,
    contents: Contents,
}

enum Contents {
    WorkingTree {
        root: PathBuf,
        index: gix::worktree::Index,
        stat_options: StatOptions,
    },
    Commit {
        repository: Box<gix::ThreadSafeRepository>,
        commit: CommitId,
        blobs: HashMap<RepoPath, gix::ObjectId>,
    },
}

#[derive(Clone, Copy)]
pub struct ParallelSnapshotReader<'snapshot> {
    source: ParallelSource<'snapshot>,
}

#[derive(Clone, Copy)]
enum ParallelSource<'snapshot> {
    WorkingTree {
        root: &'snapshot Path,
    },
    Commit {
        repository: &'snapshot gix::ThreadSafeRepository,
        commit: CommitId,
        blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
    },
}

pub struct ThreadLocalSnapshotReader<'snapshot> {
    source: ThreadLocalSource<'snapshot>,
}

enum ThreadLocalSource<'snapshot> {
    WorkingTree {
        root: &'snapshot Path,
    },
    Commit {
        repository: Box<gix::Repository>,
        commit: CommitId,
        blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
    },
}

impl std::fmt::Display for CommitId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

impl Repository {
    pub fn init(folder: &Path) -> Result<Repository, GitError> {
        gix::init(folder).map_err(|source| GitError::Open {
            start: folder.to_path_buf(),
            source,
        })?;
        Repository::discover(folder)
    }

    pub fn discover(start: &Path) -> Result<Repository, GitError> {
        let repository = gix::discover(start).map_err(|source| {
            if source.is_not_found() {
                GitError::NotInRepository {
                    start: start.to_path_buf(),
                }
            } else {
                GitError::Open {
                    start: start.to_path_buf(),
                    source,
                }
            }
        })?;
        let root = repository
            .workdir()
            .ok_or_else(|| GitError::BareRepository {
                start: start.to_path_buf(),
            })?
            .to_path_buf();
        Ok(Repository { repository, root })
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn working_tree(&self) -> Result<Snapshot, GitError> {
        let (Listing { files, submodules }, index) = list_working_tree(&self.repository)?;
        let stat_options = self.repository.stat_options().map_err(GitError::Walk)?;
        Ok(Snapshot {
            files,
            submodules,
            contents: Contents::WorkingTree {
                root: self.root.clone(),
                index,
                stat_options,
            },
        })
    }

    pub fn resolve(&self, git_ref: &str) -> Result<CommitId, GitError> {
        self.repository
            .rev_parse_single(git_ref)
            .and_then(|id| id.object()?.peel_to_commit())
            .map(|commit| CommitId(commit.id))
            .map_err(|source| GitError::UnknownRef {
                name: git_ref.to_owned(),
                source,
            })
    }

    pub fn merge_base_with_head(&self, base_ref: &str) -> Result<CommitId, GitError> {
        let base = self.resolve(base_ref)?;
        let head = self
            .repository
            .head_id()
            .map_err(|source| GitError::NoHeadCommit {
                base_ref: base_ref.to_owned(),
                source,
            })?;
        self.merge_base_of((base_ref, base), (HEAD, CommitId(head.detach())))
    }

    pub fn merge_base(&self, base_ref: &str, head_ref: &str) -> Result<CommitId, GitError> {
        let base = self.resolve(base_ref)?;
        let head = self.resolve(head_ref)?;
        self.merge_base_of((base_ref, base), (head_ref, head))
    }

    fn merge_base_of(
        &self,
        (base_ref, base): (&str, CommitId),
        (head_ref, head): (&str, CommitId),
    ) -> Result<CommitId, GitError> {
        let merge_base = self
            .repository
            .merge_base(base.0, head.0)
            .map_err(|source| GitError::MergeBase {
                base_ref: base_ref.to_owned(),
                head_ref: head_ref.to_owned(),
                source,
            })?
            .ok_or_else(|| GitError::NoMergeBase {
                base_ref: base_ref.to_owned(),
                head_ref: head_ref.to_owned(),
            })?;
        Ok(CommitId(merge_base.detach()))
    }

    pub fn commit(&self, commit: CommitId) -> Result<Snapshot, GitError> {
        let (Listing { files, submodules }, blobs) = list_commit(&self.repository, commit)?;
        Ok(Snapshot {
            files,
            submodules,
            contents: Contents::Commit {
                repository: Box::new(self.repository.clone().into_sync()),
                commit,
                blobs,
            },
        })
    }

    pub fn changed_files_since(&self, base_ref: &str) -> Result<ChangedFiles, GitError> {
        let merge_base = self.merge_base_with_head(base_ref)?;
        let base = self.commit(merge_base)?;
        let working = self.working_tree()?;
        let files = working.changed_files_from(&base)?;
        Ok(ChangedFiles { merge_base, files })
    }
}

impl Snapshot {
    pub fn files(&self) -> &[RepoPath] {
        &self.files
    }

    pub fn submodules(&self) -> &[RepoPath] {
        &self.submodules
    }

    pub fn changed_files_from(&self, base: &Snapshot) -> Result<Vec<RepoPath>, GitError> {
        let mut changed = Vec::new();
        for path in self.files() {
            if self.file_differs_from(base, path)? {
                changed.push(path.clone());
            }
        }
        changed.sort();
        Ok(changed)
    }

    fn file_differs_from(&self, base: &Snapshot, path: &RepoPath) -> Result<bool, GitError> {
        if !base.contains_file(path) {
            return Ok(true);
        }
        match (&self.contents, &base.contents) {
            (
                Contents::Commit {
                    blobs: head_blobs, ..
                },
                Contents::Commit {
                    blobs: base_blobs, ..
                },
            ) => Ok(head_blobs.get(path) != base_blobs.get(path)),
            (
                Contents::WorkingTree {
                    root,
                    index,
                    stat_options,
                },
                Contents::Commit {
                    blobs: base_blobs, ..
                },
            ) if working_tree_matches_base_blob(
                root,
                index,
                *stat_options,
                path,
                base_blobs.get(path),
            ) =>
            {
                Ok(false)
            }
            _ => Ok(self.read(path)? != base.read(path)?),
        }
    }

    pub(crate) fn contains_file(&self, path: &RepoPath) -> bool {
        match &self.contents {
            Contents::Commit { blobs, .. } => blobs.contains_key(path),
            Contents::WorkingTree { .. } => self.files.binary_search(path).is_ok(),
        }
    }

    pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
        match &self.contents {
            Contents::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
            Contents::WorkingTree { .. } => None,
        }
    }

    pub fn parallel_reader(&self) -> ParallelSnapshotReader<'_> {
        let source = match &self.contents {
            Contents::WorkingTree { root, .. } => ParallelSource::WorkingTree { root },
            Contents::Commit {
                repository,
                commit,
                blobs,
            } => ParallelSource::Commit {
                repository,
                commit: *commit,
                blobs,
            },
        };
        ParallelSnapshotReader { source }
    }

    pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
        self.parallel_reader().thread_local().read(path)
    }
}

impl<'snapshot> ParallelSnapshotReader<'snapshot> {
    pub fn thread_local(self) -> ThreadLocalSnapshotReader<'snapshot> {
        let source = match self.source {
            ParallelSource::WorkingTree { root } => ThreadLocalSource::WorkingTree { root },
            ParallelSource::Commit {
                repository,
                commit,
                blobs,
            } => ThreadLocalSource::Commit {
                repository: Box::new(repository.to_thread_local()),
                commit,
                blobs,
            },
        };
        ThreadLocalSnapshotReader { source }
    }
}

impl ThreadLocalSnapshotReader<'_> {
    pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
        match &self.source {
            ThreadLocalSource::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
            ThreadLocalSource::WorkingTree { .. } => None,
        }
    }

    pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
        match &self.source {
            ThreadLocalSource::WorkingTree { root } => std::fs::read(root.join(path.as_str()))
                .map_err(|source| GitError::Read {
                    path: path.clone(),
                    source,
                }),
            ThreadLocalSource::Commit {
                repository,
                commit,
                blobs,
            } => {
                let blob = blobs.get(path).ok_or_else(|| GitError::Read {
                    path: path.clone(),
                    source: std::io::ErrorKind::NotFound.into(),
                })?;
                repository
                    .find_blob(*blob)
                    .map(|mut blob| blob.take_data())
                    .map_err(|source| GitError::ReadBlob {
                        path: path.clone(),
                        commit: *commit,
                        source,
                    })
            }
        }
    }
}

struct Listing {
    files: Vec<RepoPath>,
    submodules: Vec<RepoPath>,
}

fn list_working_tree(
    repository: &gix::Repository,
) -> Result<(Listing, gix::worktree::Index), GitError> {
    let index = repository.index_or_empty().map_err(GitError::Walk)?;
    let options = repository
        .dirwalk_options()
        .map_err(GitError::Walk)?
        .emit_tracked(true)
        .emit_untracked(EmissionMode::Matching)
        .emit_ignored(None)
        .recurse_repositories(false);
    let mut collect = Collect::default();
    repository
        .dirwalk(
            &index,
            None::<&str>,
            &AtomicBool::new(false),
            options,
            &mut collect,
        )
        .map_err(GitError::Walk)?;
    let mut listing = Listing {
        files: Vec::new(),
        submodules: Vec::new(),
    };
    for (entry, _) in collect.into_entries_by_path() {
        let is_submodule = entry.index_kind == Some(Kind::Repository);
        let is_measurable_file = matches!(entry.status, Status::Tracked | Status::Untracked)
            && entry.disk_kind == Some(Kind::File);
        if is_submodule {
            listing.submodules.push(repo_path(entry.rela_path)?);
        } else if is_measurable_file {
            listing.files.push(repo_path(entry.rela_path)?);
        }
    }
    Ok((listing, index))
}

fn working_tree_matches_base_blob(
    root: &Path,
    index: &gix::worktree::Index,
    stat_options: StatOptions,
    path: &RepoPath,
    base_blob: Option<&gix::ObjectId>,
) -> bool {
    let Some(&base_oid) = base_blob else {
        return false;
    };
    let Some(entry) = index.entry_by_path_and_stage(path.as_str().into(), Stage::Unconflicted)
    else {
        return false;
    };
    if entry.id != base_oid || !is_trustworthy_regular_file_entry(entry) {
        return false;
    }
    let racy_options = StatOptions {
        use_nsec: false,
        ..stat_options
    };
    if entry.stat.is_racy(index.timestamp(), racy_options) {
        return false;
    }
    let Ok(metadata) = IndexMetadata::from_path_no_follow(&root.join(path.as_str())) else {
        return false;
    };
    if !metadata.is_file()
        || u32::try_from(metadata.len()).ok() != Some(entry.stat.size)
        || mode_changed(entry.mode, &metadata)
    {
        return false;
    }
    let Ok(fs_stat) = Stat::from_fs(&metadata) else {
        return false;
    };
    entry.stat.matches(&fs_stat, stat_options)
}

fn is_trustworthy_regular_file_entry(entry: &gix::index::Entry) -> bool {
    let untrusted_flags = Flags::INTENT_TO_ADD
        | Flags::SKIP_WORKTREE
        | Flags::ASSUME_VALID
        | Flags::UPDATE
        | Flags::REMOVE
        | Flags::CONFLICTED
        | Flags::WORKTREE_REMOVE;
    matches!(entry.mode, Mode::FILE | Mode::FILE_EXECUTABLE)
        && entry.stat.mtime.secs != 0
        && !entry.flags.intersects(untrusted_flags)
}

fn mode_changed(mode: Mode, metadata: &IndexMetadata) -> bool {
    #[cfg(unix)]
    {
        (mode == Mode::FILE_EXECUTABLE) != metadata.is_executable()
    }
    #[cfg(not(unix))]
    {
        let _ = (mode, metadata);
        false
    }
}

fn list_commit(
    repository: &gix::Repository,
    commit: CommitId,
) -> Result<(Listing, HashMap<RepoPath, gix::ObjectId>), GitError> {
    let entries = repository
        .find_commit(commit.0)
        .and_then(|found| found.tree())
        .and_then(|tree| tree.traverse().breadthfirst.files())
        .map_err(|source| GitError::CommitTree { commit, source })?;
    let mut listing = Listing {
        files: Vec::new(),
        submodules: Vec::new(),
    };
    let mut blobs = HashMap::new();
    for entry in entries {
        if entry.mode.is_commit() {
            listing.submodules.push(repo_path(entry.filepath)?);
        } else if entry.mode.is_blob() {
            let path = repo_path(entry.filepath)?;
            blobs.insert(path.clone(), entry.oid);
            listing.files.push(path);
        }
    }
    listing.files.sort();
    listing.submodules.sort();
    Ok((listing, blobs))
}

fn repo_path(rela_path: gix::bstr::BString) -> Result<RepoPath, GitError> {
    let path = String::from_utf8(rela_path.into()).map_err(|source| GitError::NonUtf8Path {
        path: String::from_utf8_lossy(source.as_bytes()).into_owned(),
        source,
    })?;
    Ok(RepoPath::new(path)?)
}