1#![forbid(unsafe_code)]
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::atomic::AtomicBool;
6
7use codeint_model::{InvalidRepoPath, RepoPath};
8use gix::dir::entry::{Kind, Status};
9use gix::dir::walk::EmissionMode;
10use gix::dir::walk::delegate::Collect;
11use gix::index::entry::{Flags, Mode, Stage, Stat, stat::Options as StatOptions};
12use gix::index::fs::Metadata as IndexMetadata;
13
14mod changed_lines;
15mod churn;
16mod history;
17mod rename;
18mod result_cache;
19mod snapshot_lookup;
20#[cfg(test)]
21mod tests;
22
23pub use changed_lines::LineRange;
24pub use churn::{ChurnRange, CoChangeSummary, FileChurnSummary};
25pub use history::{CommitRange, HistoryCommit};
26pub use rename::{DEFAULT_RENAME_THRESHOLD, MAX_RENAME_THRESHOLD, RenameMap};
27pub use result_cache::{ResultCache, ResultCacheError};
28pub use snapshot_lookup::SnapshotFileLookup;
29
30#[derive(Debug, thiserror::Error)]
31pub enum GitError {
32 #[error("{} is not inside a Git repository", start.display())]
33 NotInRepository { start: PathBuf },
34 #[error("{} is inside a bare Git repository, which has no working tree", start.display())]
35 BareRepository { start: PathBuf },
36 #[error("cannot open the Git repository that contains {}", start.display())]
37 Open {
38 start: PathBuf,
39 #[source]
40 source: gix::Error,
41 },
42 #[error("cannot list the files of the working tree")]
43 Walk(#[source] gix::Error),
44 #[error("a working tree path is not valid UTF-8: {path}")]
45 NonUtf8Path {
46 path: String,
47 #[source]
48 source: std::string::FromUtf8Error,
49 },
50 #[error(transparent)]
51 InvalidPath(#[from] InvalidRepoPath),
52 #[error("cannot read {path}")]
53 Read {
54 path: RepoPath,
55 #[source]
56 source: std::io::Error,
57 },
58 #[error("the Git ref {name:?} does not name a commit in this repository")]
59 UnknownRef {
60 name: String,
61 #[source]
62 source: gix::Error,
63 },
64 #[error("HEAD does not name a commit yet, so it has no merge-base with {base_ref:?}")]
65 NoHeadCommit {
66 base_ref: String,
67 #[source]
68 source: gix::Error,
69 },
70 #[error("{base_ref:?} and {head_ref:?} have no commit in common, so they have no merge-base")]
71 NoMergeBase { base_ref: String, head_ref: String },
72 #[error("cannot find the merge-base of {base_ref:?} and {head_ref:?}")]
73 MergeBase {
74 base_ref: String,
75 head_ref: String,
76 #[source]
77 source: gix::Error,
78 },
79 #[error("HEAD does not name a commit yet, so the current branch has no history to measure")]
80 NoHistory(#[source] gix::Error),
81 #[error("cannot read commit {commit} of the history")]
82 History {
83 commit: CommitId,
84 #[source]
85 source: gix::Error,
86 },
87 #[error("cannot list the files of commit {commit}")]
88 CommitTree {
89 commit: CommitId,
90 #[source]
91 source: gix::Error,
92 },
93 #[error("cannot read {path} from commit {commit}")]
94 ReadBlob {
95 path: RepoPath,
96 commit: CommitId,
97 #[source]
98 source: gix::Error,
99 },
100 #[error("{path} is {size_bytes} bytes, exceeding the {max_bytes}-byte limit")]
101 FileTooLarge {
102 path: RepoPath,
103 size_bytes: u64,
104 max_bytes: u64,
105 },
106}
107
108const HEAD: &str = "HEAD";
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub struct CommitId(gix::ObjectId);
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114pub struct BlobId(gix::ObjectId);
115
116pub struct Repository {
117 repository: gix::Repository,
118 root: PathBuf,
119}
120
121pub struct ChangedFiles {
122 pub merge_base: CommitId,
123 pub files: Vec<RepoPath>,
124}
125
126pub struct Snapshot {
127 files: Vec<RepoPath>,
128 submodules: Vec<RepoPath>,
129 contents: Contents,
130}
131
132enum Contents {
133 WorkingTree {
134 root: PathBuf,
135 index: gix::worktree::Index,
136 stat_options: StatOptions,
137 },
138 Commit {
139 repository: Box<gix::ThreadSafeRepository>,
140 commit: CommitId,
141 blobs: HashMap<RepoPath, gix::ObjectId>,
142 },
143}
144
145#[derive(Clone, Copy)]
146pub struct ParallelSnapshotReader<'snapshot> {
147 source: ParallelSource<'snapshot>,
148}
149
150#[derive(Clone, Copy)]
151enum ParallelSource<'snapshot> {
152 WorkingTree {
153 root: &'snapshot Path,
154 },
155 Commit {
156 repository: &'snapshot gix::ThreadSafeRepository,
157 commit: CommitId,
158 blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
159 },
160}
161
162pub struct ThreadLocalSnapshotReader<'snapshot> {
163 source: ThreadLocalSource<'snapshot>,
164}
165
166enum ThreadLocalSource<'snapshot> {
167 WorkingTree {
168 root: &'snapshot Path,
169 },
170 Commit {
171 repository: Box<gix::Repository>,
172 commit: CommitId,
173 blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
174 },
175}
176
177impl std::fmt::Display for CommitId {
178 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179 write!(formatter, "{}", self.0)
180 }
181}
182
183impl Repository {
184 pub fn init(folder: &Path) -> Result<Repository, GitError> {
185 gix::init(folder).map_err(|source| GitError::Open {
186 start: folder.to_path_buf(),
187 source,
188 })?;
189 Repository::discover(folder)
190 }
191
192 pub fn discover(start: &Path) -> Result<Repository, GitError> {
193 let repository = gix::discover(start).map_err(|source| {
194 if source.is_not_found() {
195 GitError::NotInRepository {
196 start: start.to_path_buf(),
197 }
198 } else {
199 GitError::Open {
200 start: start.to_path_buf(),
201 source,
202 }
203 }
204 })?;
205 let root = repository
206 .workdir()
207 .ok_or_else(|| GitError::BareRepository {
208 start: start.to_path_buf(),
209 })?
210 .to_path_buf();
211 Ok(Repository { repository, root })
212 }
213
214 pub fn root(&self) -> &Path {
215 &self.root
216 }
217
218 pub fn working_tree(&self) -> Result<Snapshot, GitError> {
219 let (Listing { files, submodules }, index) = list_working_tree(&self.repository)?;
220 let stat_options = self.repository.stat_options().map_err(GitError::Walk)?;
221 Ok(Snapshot {
222 files,
223 submodules,
224 contents: Contents::WorkingTree {
225 root: self.root.clone(),
226 index,
227 stat_options,
228 },
229 })
230 }
231
232 pub fn resolve(&self, git_ref: &str) -> Result<CommitId, GitError> {
233 self.repository
234 .rev_parse_single(git_ref)
235 .and_then(|id| id.object()?.peel_to_commit())
236 .map(|commit| CommitId(commit.id))
237 .map_err(|source| GitError::UnknownRef {
238 name: git_ref.to_owned(),
239 source,
240 })
241 }
242
243 pub fn merge_base_with_head(&self, base_ref: &str) -> Result<CommitId, GitError> {
244 let base = self.resolve(base_ref)?;
245 let head = self
246 .repository
247 .head_id()
248 .map_err(|source| GitError::NoHeadCommit {
249 base_ref: base_ref.to_owned(),
250 source,
251 })?;
252 self.merge_base_of((base_ref, base), (HEAD, CommitId(head.detach())))
253 }
254
255 pub fn merge_base(&self, base_ref: &str, head_ref: &str) -> Result<CommitId, GitError> {
256 let base = self.resolve(base_ref)?;
257 let head = self.resolve(head_ref)?;
258 self.merge_base_of((base_ref, base), (head_ref, head))
259 }
260
261 fn merge_base_of(
262 &self,
263 (base_ref, base): (&str, CommitId),
264 (head_ref, head): (&str, CommitId),
265 ) -> Result<CommitId, GitError> {
266 let merge_base = self
267 .repository
268 .merge_base(base.0, head.0)
269 .map_err(|source| GitError::MergeBase {
270 base_ref: base_ref.to_owned(),
271 head_ref: head_ref.to_owned(),
272 source,
273 })?
274 .ok_or_else(|| GitError::NoMergeBase {
275 base_ref: base_ref.to_owned(),
276 head_ref: head_ref.to_owned(),
277 })?;
278 Ok(CommitId(merge_base.detach()))
279 }
280
281 pub fn commit(&self, commit: CommitId) -> Result<Snapshot, GitError> {
282 let (Listing { files, submodules }, blobs) = list_commit(&self.repository, commit)?;
283 Ok(Snapshot {
284 files,
285 submodules,
286 contents: Contents::Commit {
287 repository: Box::new(self.repository.clone().into_sync()),
288 commit,
289 blobs,
290 },
291 })
292 }
293
294 pub fn changed_files_since(&self, base_ref: &str) -> Result<ChangedFiles, GitError> {
295 let merge_base = self.merge_base_with_head(base_ref)?;
296 let base = self.commit(merge_base)?;
297 let working = self.working_tree()?;
298 let files = working.changed_files_from(&base)?;
299 Ok(ChangedFiles { merge_base, files })
300 }
301}
302
303impl Snapshot {
304 pub fn files(&self) -> &[RepoPath] {
305 &self.files
306 }
307
308 pub fn submodules(&self) -> &[RepoPath] {
309 &self.submodules
310 }
311
312 pub fn changed_files_from(&self, base: &Snapshot) -> Result<Vec<RepoPath>, GitError> {
313 let mut changed = Vec::new();
314 for path in self.files() {
315 if self.file_differs_from(base, path)? {
316 changed.push(path.clone());
317 }
318 }
319 changed.sort();
320 Ok(changed)
321 }
322
323 fn file_differs_from(&self, base: &Snapshot, path: &RepoPath) -> Result<bool, GitError> {
324 if !base.contains_file(path) {
325 return Ok(true);
326 }
327 match (&self.contents, &base.contents) {
328 (
329 Contents::Commit {
330 blobs: head_blobs, ..
331 },
332 Contents::Commit {
333 blobs: base_blobs, ..
334 },
335 ) => Ok(head_blobs.get(path) != base_blobs.get(path)),
336 (
337 Contents::WorkingTree {
338 root,
339 index,
340 stat_options,
341 },
342 Contents::Commit {
343 blobs: base_blobs, ..
344 },
345 ) if working_tree_matches_base_blob(
346 root,
347 index,
348 *stat_options,
349 path,
350 base_blobs.get(path),
351 ) =>
352 {
353 Ok(false)
354 }
355 _ => Ok(self.read(path)? != base.read(path)?),
356 }
357 }
358
359 pub(crate) fn contains_file(&self, path: &RepoPath) -> bool {
360 match &self.contents {
361 Contents::Commit { blobs, .. } => blobs.contains_key(path),
362 Contents::WorkingTree { .. } => self.files.binary_search(path).is_ok(),
363 }
364 }
365
366 pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
367 match &self.contents {
368 Contents::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
369 Contents::WorkingTree { .. } => None,
370 }
371 }
372
373 pub fn parallel_reader(&self) -> ParallelSnapshotReader<'_> {
374 let source = match &self.contents {
375 Contents::WorkingTree { root, .. } => ParallelSource::WorkingTree { root },
376 Contents::Commit {
377 repository,
378 commit,
379 blobs,
380 } => ParallelSource::Commit {
381 repository,
382 commit: *commit,
383 blobs,
384 },
385 };
386 ParallelSnapshotReader { source }
387 }
388
389 pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
390 self.parallel_reader().thread_local().read(path)
391 }
392}
393
394impl<'snapshot> ParallelSnapshotReader<'snapshot> {
395 pub fn thread_local(self) -> ThreadLocalSnapshotReader<'snapshot> {
396 let source = match self.source {
397 ParallelSource::WorkingTree { root } => ThreadLocalSource::WorkingTree { root },
398 ParallelSource::Commit {
399 repository,
400 commit,
401 blobs,
402 } => ThreadLocalSource::Commit {
403 repository: Box::new(repository.to_thread_local()),
404 commit,
405 blobs,
406 },
407 };
408 ThreadLocalSnapshotReader { source }
409 }
410}
411
412impl ThreadLocalSnapshotReader<'_> {
413 pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
414 match &self.source {
415 ThreadLocalSource::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
416 ThreadLocalSource::WorkingTree { .. } => None,
417 }
418 }
419
420 pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
421 match &self.source {
422 ThreadLocalSource::WorkingTree { root } => std::fs::read(root.join(path.as_str()))
423 .map_err(|source| GitError::Read {
424 path: path.clone(),
425 source,
426 }),
427 ThreadLocalSource::Commit {
428 repository,
429 commit,
430 blobs,
431 } => {
432 let blob = blobs.get(path).ok_or_else(|| GitError::Read {
433 path: path.clone(),
434 source: std::io::ErrorKind::NotFound.into(),
435 })?;
436 repository
437 .find_blob(*blob)
438 .map(|mut blob| blob.take_data())
439 .map_err(|source| GitError::ReadBlob {
440 path: path.clone(),
441 commit: *commit,
442 source,
443 })
444 }
445 }
446 }
447}
448
449struct Listing {
450 files: Vec<RepoPath>,
451 submodules: Vec<RepoPath>,
452}
453
454fn list_working_tree(
455 repository: &gix::Repository,
456) -> Result<(Listing, gix::worktree::Index), GitError> {
457 let index = repository.index_or_empty().map_err(GitError::Walk)?;
458 let options = repository
459 .dirwalk_options()
460 .map_err(GitError::Walk)?
461 .emit_tracked(true)
462 .emit_untracked(EmissionMode::Matching)
463 .emit_ignored(None)
464 .recurse_repositories(false);
465 let mut collect = Collect::default();
466 repository
467 .dirwalk(
468 &index,
469 None::<&str>,
470 &AtomicBool::new(false),
471 options,
472 &mut collect,
473 )
474 .map_err(GitError::Walk)?;
475 let mut listing = Listing {
476 files: Vec::new(),
477 submodules: Vec::new(),
478 };
479 for (entry, _) in collect.into_entries_by_path() {
480 let is_submodule = entry.index_kind == Some(Kind::Repository);
481 let is_measurable_file = matches!(entry.status, Status::Tracked | Status::Untracked)
482 && entry.disk_kind == Some(Kind::File);
483 if is_submodule {
484 listing.submodules.push(repo_path(entry.rela_path)?);
485 } else if is_measurable_file {
486 listing.files.push(repo_path(entry.rela_path)?);
487 }
488 }
489 Ok((listing, index))
490}
491
492fn working_tree_matches_base_blob(
493 root: &Path,
494 index: &gix::worktree::Index,
495 stat_options: StatOptions,
496 path: &RepoPath,
497 base_blob: Option<&gix::ObjectId>,
498) -> bool {
499 let Some(&base_oid) = base_blob else {
500 return false;
501 };
502 let Some(entry) = index.entry_by_path_and_stage(path.as_str().into(), Stage::Unconflicted)
503 else {
504 return false;
505 };
506 if entry.id != base_oid || !is_trustworthy_regular_file_entry(entry) {
507 return false;
508 }
509 let racy_options = StatOptions {
510 use_nsec: false,
511 ..stat_options
512 };
513 if entry.stat.is_racy(index.timestamp(), racy_options) {
514 return false;
515 }
516 let Ok(metadata) = IndexMetadata::from_path_no_follow(&root.join(path.as_str())) else {
517 return false;
518 };
519 if !metadata.is_file()
520 || u32::try_from(metadata.len()).ok() != Some(entry.stat.size)
521 || mode_changed(entry.mode, &metadata)
522 {
523 return false;
524 }
525 let Ok(fs_stat) = Stat::from_fs(&metadata) else {
526 return false;
527 };
528 entry.stat.matches(&fs_stat, stat_options)
529}
530
531fn is_trustworthy_regular_file_entry(entry: &gix::index::Entry) -> bool {
532 let untrusted_flags = Flags::INTENT_TO_ADD
533 | Flags::SKIP_WORKTREE
534 | Flags::ASSUME_VALID
535 | Flags::UPDATE
536 | Flags::REMOVE
537 | Flags::CONFLICTED
538 | Flags::WORKTREE_REMOVE;
539 matches!(entry.mode, Mode::FILE | Mode::FILE_EXECUTABLE)
540 && entry.stat.mtime.secs != 0
541 && !entry.flags.intersects(untrusted_flags)
542}
543
544fn mode_changed(mode: Mode, metadata: &IndexMetadata) -> bool {
545 #[cfg(unix)]
546 {
547 (mode == Mode::FILE_EXECUTABLE) != metadata.is_executable()
548 }
549 #[cfg(not(unix))]
550 {
551 let _ = (mode, metadata);
552 false
553 }
554}
555
556fn list_commit(
557 repository: &gix::Repository,
558 commit: CommitId,
559) -> Result<(Listing, HashMap<RepoPath, gix::ObjectId>), GitError> {
560 let entries = repository
561 .find_commit(commit.0)
562 .and_then(|found| found.tree())
563 .and_then(|tree| tree.traverse().breadthfirst.files())
564 .map_err(|source| GitError::CommitTree { commit, source })?;
565 let mut listing = Listing {
566 files: Vec::new(),
567 submodules: Vec::new(),
568 };
569 let mut blobs = HashMap::new();
570 for entry in entries {
571 if entry.mode.is_commit() {
572 listing.submodules.push(repo_path(entry.filepath)?);
573 } else if entry.mode.is_blob() {
574 let path = repo_path(entry.filepath)?;
575 blobs.insert(path.clone(), entry.oid);
576 listing.files.push(path);
577 }
578 }
579 listing.files.sort();
580 listing.submodules.sort();
581 Ok((listing, blobs))
582}
583
584fn repo_path(rela_path: gix::bstr::BString) -> Result<RepoPath, GitError> {
585 let path = String::from_utf8(rela_path.into()).map_err(|source| GitError::NonUtf8Path {
586 path: String::from_utf8_lossy(source.as_bytes()).into_owned(),
587 source,
588 })?;
589 Ok(RepoPath::new(path)?)
590}