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}
101
102const HEAD: &str = "HEAD";
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub struct CommitId(gix::ObjectId);
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108pub struct BlobId(gix::ObjectId);
109
110pub struct Repository {
111 repository: gix::Repository,
112 root: PathBuf,
113}
114
115pub struct ChangedFiles {
116 pub merge_base: CommitId,
117 pub files: Vec<RepoPath>,
118}
119
120pub struct Snapshot {
121 files: Vec<RepoPath>,
122 submodules: Vec<RepoPath>,
123 contents: Contents,
124}
125
126enum Contents {
127 WorkingTree {
128 root: PathBuf,
129 index: gix::worktree::Index,
130 stat_options: StatOptions,
131 },
132 Commit {
133 repository: Box<gix::ThreadSafeRepository>,
134 commit: CommitId,
135 blobs: HashMap<RepoPath, gix::ObjectId>,
136 },
137}
138
139#[derive(Clone, Copy)]
140pub struct ParallelSnapshotReader<'snapshot> {
141 source: ParallelSource<'snapshot>,
142}
143
144#[derive(Clone, Copy)]
145enum ParallelSource<'snapshot> {
146 WorkingTree {
147 root: &'snapshot Path,
148 },
149 Commit {
150 repository: &'snapshot gix::ThreadSafeRepository,
151 commit: CommitId,
152 blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
153 },
154}
155
156pub struct ThreadLocalSnapshotReader<'snapshot> {
157 source: ThreadLocalSource<'snapshot>,
158}
159
160enum ThreadLocalSource<'snapshot> {
161 WorkingTree {
162 root: &'snapshot Path,
163 },
164 Commit {
165 repository: Box<gix::Repository>,
166 commit: CommitId,
167 blobs: &'snapshot HashMap<RepoPath, gix::ObjectId>,
168 },
169}
170
171impl std::fmt::Display for CommitId {
172 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 write!(formatter, "{}", self.0)
174 }
175}
176
177impl Repository {
178 pub fn init(folder: &Path) -> Result<Repository, GitError> {
179 gix::init(folder).map_err(|source| GitError::Open {
180 start: folder.to_path_buf(),
181 source,
182 })?;
183 Repository::discover(folder)
184 }
185
186 pub fn discover(start: &Path) -> Result<Repository, GitError> {
187 let repository = gix::discover(start).map_err(|source| {
188 if source.is_not_found() {
189 GitError::NotInRepository {
190 start: start.to_path_buf(),
191 }
192 } else {
193 GitError::Open {
194 start: start.to_path_buf(),
195 source,
196 }
197 }
198 })?;
199 let root = repository
200 .workdir()
201 .ok_or_else(|| GitError::BareRepository {
202 start: start.to_path_buf(),
203 })?
204 .to_path_buf();
205 Ok(Repository { repository, root })
206 }
207
208 pub fn root(&self) -> &Path {
209 &self.root
210 }
211
212 pub fn working_tree(&self) -> Result<Snapshot, GitError> {
213 let (Listing { files, submodules }, index) = list_working_tree(&self.repository)?;
214 let stat_options = self.repository.stat_options().map_err(GitError::Walk)?;
215 Ok(Snapshot {
216 files,
217 submodules,
218 contents: Contents::WorkingTree {
219 root: self.root.clone(),
220 index,
221 stat_options,
222 },
223 })
224 }
225
226 pub fn resolve(&self, git_ref: &str) -> Result<CommitId, GitError> {
227 self.repository
228 .rev_parse_single(git_ref)
229 .and_then(|id| id.object()?.peel_to_commit())
230 .map(|commit| CommitId(commit.id))
231 .map_err(|source| GitError::UnknownRef {
232 name: git_ref.to_owned(),
233 source,
234 })
235 }
236
237 pub fn merge_base_with_head(&self, base_ref: &str) -> Result<CommitId, GitError> {
238 let base = self.resolve(base_ref)?;
239 let head = self
240 .repository
241 .head_id()
242 .map_err(|source| GitError::NoHeadCommit {
243 base_ref: base_ref.to_owned(),
244 source,
245 })?;
246 self.merge_base_of((base_ref, base), (HEAD, CommitId(head.detach())))
247 }
248
249 pub fn merge_base(&self, base_ref: &str, head_ref: &str) -> Result<CommitId, GitError> {
250 let base = self.resolve(base_ref)?;
251 let head = self.resolve(head_ref)?;
252 self.merge_base_of((base_ref, base), (head_ref, head))
253 }
254
255 fn merge_base_of(
256 &self,
257 (base_ref, base): (&str, CommitId),
258 (head_ref, head): (&str, CommitId),
259 ) -> Result<CommitId, GitError> {
260 let merge_base = self
261 .repository
262 .merge_base(base.0, head.0)
263 .map_err(|source| GitError::MergeBase {
264 base_ref: base_ref.to_owned(),
265 head_ref: head_ref.to_owned(),
266 source,
267 })?
268 .ok_or_else(|| GitError::NoMergeBase {
269 base_ref: base_ref.to_owned(),
270 head_ref: head_ref.to_owned(),
271 })?;
272 Ok(CommitId(merge_base.detach()))
273 }
274
275 pub fn commit(&self, commit: CommitId) -> Result<Snapshot, GitError> {
276 let (Listing { files, submodules }, blobs) = list_commit(&self.repository, commit)?;
277 Ok(Snapshot {
278 files,
279 submodules,
280 contents: Contents::Commit {
281 repository: Box::new(self.repository.clone().into_sync()),
282 commit,
283 blobs,
284 },
285 })
286 }
287
288 pub fn changed_files_since(&self, base_ref: &str) -> Result<ChangedFiles, GitError> {
289 let merge_base = self.merge_base_with_head(base_ref)?;
290 let base = self.commit(merge_base)?;
291 let working = self.working_tree()?;
292 let files = working.changed_files_from(&base)?;
293 Ok(ChangedFiles { merge_base, files })
294 }
295}
296
297impl Snapshot {
298 pub fn files(&self) -> &[RepoPath] {
299 &self.files
300 }
301
302 pub fn submodules(&self) -> &[RepoPath] {
303 &self.submodules
304 }
305
306 pub fn changed_files_from(&self, base: &Snapshot) -> Result<Vec<RepoPath>, GitError> {
307 let mut changed = Vec::new();
308 for path in self.files() {
309 if self.file_differs_from(base, path)? {
310 changed.push(path.clone());
311 }
312 }
313 changed.sort();
314 Ok(changed)
315 }
316
317 fn file_differs_from(&self, base: &Snapshot, path: &RepoPath) -> Result<bool, GitError> {
318 if !base.contains_file(path) {
319 return Ok(true);
320 }
321 match (&self.contents, &base.contents) {
322 (
323 Contents::Commit {
324 blobs: head_blobs, ..
325 },
326 Contents::Commit {
327 blobs: base_blobs, ..
328 },
329 ) => Ok(head_blobs.get(path) != base_blobs.get(path)),
330 (
331 Contents::WorkingTree {
332 root,
333 index,
334 stat_options,
335 },
336 Contents::Commit {
337 blobs: base_blobs, ..
338 },
339 ) if working_tree_matches_base_blob(
340 root,
341 index,
342 *stat_options,
343 path,
344 base_blobs.get(path),
345 ) =>
346 {
347 Ok(false)
348 }
349 _ => Ok(self.read(path)? != base.read(path)?),
350 }
351 }
352
353 pub(crate) fn contains_file(&self, path: &RepoPath) -> bool {
354 match &self.contents {
355 Contents::Commit { blobs, .. } => blobs.contains_key(path),
356 Contents::WorkingTree { .. } => self.files.binary_search(path).is_ok(),
357 }
358 }
359
360 pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
361 match &self.contents {
362 Contents::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
363 Contents::WorkingTree { .. } => None,
364 }
365 }
366
367 pub fn parallel_reader(&self) -> ParallelSnapshotReader<'_> {
368 let source = match &self.contents {
369 Contents::WorkingTree { root, .. } => ParallelSource::WorkingTree { root },
370 Contents::Commit {
371 repository,
372 commit,
373 blobs,
374 } => ParallelSource::Commit {
375 repository,
376 commit: *commit,
377 blobs,
378 },
379 };
380 ParallelSnapshotReader { source }
381 }
382
383 pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
384 self.parallel_reader().thread_local().read(path)
385 }
386}
387
388impl<'snapshot> ParallelSnapshotReader<'snapshot> {
389 pub fn thread_local(self) -> ThreadLocalSnapshotReader<'snapshot> {
390 let source = match self.source {
391 ParallelSource::WorkingTree { root } => ThreadLocalSource::WorkingTree { root },
392 ParallelSource::Commit {
393 repository,
394 commit,
395 blobs,
396 } => ThreadLocalSource::Commit {
397 repository: Box::new(repository.to_thread_local()),
398 commit,
399 blobs,
400 },
401 };
402 ThreadLocalSnapshotReader { source }
403 }
404}
405
406impl ThreadLocalSnapshotReader<'_> {
407 pub fn blob_id(&self, path: &RepoPath) -> Option<BlobId> {
408 match &self.source {
409 ThreadLocalSource::Commit { blobs, .. } => blobs.get(path).copied().map(BlobId),
410 ThreadLocalSource::WorkingTree { .. } => None,
411 }
412 }
413
414 pub fn read(&self, path: &RepoPath) -> Result<Vec<u8>, GitError> {
415 match &self.source {
416 ThreadLocalSource::WorkingTree { root } => std::fs::read(root.join(path.as_str()))
417 .map_err(|source| GitError::Read {
418 path: path.clone(),
419 source,
420 }),
421 ThreadLocalSource::Commit {
422 repository,
423 commit,
424 blobs,
425 } => {
426 let blob = blobs.get(path).ok_or_else(|| GitError::Read {
427 path: path.clone(),
428 source: std::io::ErrorKind::NotFound.into(),
429 })?;
430 repository
431 .find_blob(*blob)
432 .map(|mut blob| blob.take_data())
433 .map_err(|source| GitError::ReadBlob {
434 path: path.clone(),
435 commit: *commit,
436 source,
437 })
438 }
439 }
440 }
441}
442
443struct Listing {
444 files: Vec<RepoPath>,
445 submodules: Vec<RepoPath>,
446}
447
448fn list_working_tree(
449 repository: &gix::Repository,
450) -> Result<(Listing, gix::worktree::Index), GitError> {
451 let index = repository.index_or_empty().map_err(GitError::Walk)?;
452 let options = repository
453 .dirwalk_options()
454 .map_err(GitError::Walk)?
455 .emit_tracked(true)
456 .emit_untracked(EmissionMode::Matching)
457 .emit_ignored(None)
458 .recurse_repositories(false);
459 let mut collect = Collect::default();
460 repository
461 .dirwalk(
462 &index,
463 None::<&str>,
464 &AtomicBool::new(false),
465 options,
466 &mut collect,
467 )
468 .map_err(GitError::Walk)?;
469 let mut listing = Listing {
470 files: Vec::new(),
471 submodules: Vec::new(),
472 };
473 for (entry, _) in collect.into_entries_by_path() {
474 let is_submodule = entry.index_kind == Some(Kind::Repository);
475 let is_measurable_file = matches!(entry.status, Status::Tracked | Status::Untracked)
476 && entry.disk_kind == Some(Kind::File);
477 if is_submodule {
478 listing.submodules.push(repo_path(entry.rela_path)?);
479 } else if is_measurable_file {
480 listing.files.push(repo_path(entry.rela_path)?);
481 }
482 }
483 Ok((listing, index))
484}
485
486fn working_tree_matches_base_blob(
487 root: &Path,
488 index: &gix::worktree::Index,
489 stat_options: StatOptions,
490 path: &RepoPath,
491 base_blob: Option<&gix::ObjectId>,
492) -> bool {
493 let Some(&base_oid) = base_blob else {
494 return false;
495 };
496 let Some(entry) = index.entry_by_path_and_stage(path.as_str().into(), Stage::Unconflicted)
497 else {
498 return false;
499 };
500 if entry.id != base_oid || !is_trustworthy_regular_file_entry(entry) {
501 return false;
502 }
503 let racy_options = StatOptions {
504 use_nsec: false,
505 ..stat_options
506 };
507 if entry.stat.is_racy(index.timestamp(), racy_options) {
508 return false;
509 }
510 let Ok(metadata) = IndexMetadata::from_path_no_follow(&root.join(path.as_str())) else {
511 return false;
512 };
513 if !metadata.is_file()
514 || u32::try_from(metadata.len()).ok() != Some(entry.stat.size)
515 || mode_changed(entry.mode, &metadata)
516 {
517 return false;
518 }
519 let Ok(fs_stat) = Stat::from_fs(&metadata) else {
520 return false;
521 };
522 entry.stat.matches(&fs_stat, stat_options)
523}
524
525fn is_trustworthy_regular_file_entry(entry: &gix::index::Entry) -> bool {
526 let untrusted_flags = Flags::INTENT_TO_ADD
527 | Flags::SKIP_WORKTREE
528 | Flags::ASSUME_VALID
529 | Flags::UPDATE
530 | Flags::REMOVE
531 | Flags::CONFLICTED
532 | Flags::WORKTREE_REMOVE;
533 matches!(entry.mode, Mode::FILE | Mode::FILE_EXECUTABLE)
534 && entry.stat.mtime.secs != 0
535 && !entry.flags.intersects(untrusted_flags)
536}
537
538fn mode_changed(mode: Mode, metadata: &IndexMetadata) -> bool {
539 #[cfg(unix)]
540 {
541 (mode == Mode::FILE_EXECUTABLE) != metadata.is_executable()
542 }
543 #[cfg(not(unix))]
544 {
545 let _ = (mode, metadata);
546 false
547 }
548}
549
550fn list_commit(
551 repository: &gix::Repository,
552 commit: CommitId,
553) -> Result<(Listing, HashMap<RepoPath, gix::ObjectId>), GitError> {
554 let entries = repository
555 .find_commit(commit.0)
556 .and_then(|found| found.tree())
557 .and_then(|tree| tree.traverse().breadthfirst.files())
558 .map_err(|source| GitError::CommitTree { commit, source })?;
559 let mut listing = Listing {
560 files: Vec::new(),
561 submodules: Vec::new(),
562 };
563 let mut blobs = HashMap::new();
564 for entry in entries {
565 if entry.mode.is_commit() {
566 listing.submodules.push(repo_path(entry.filepath)?);
567 } else if entry.mode.is_blob() {
568 let path = repo_path(entry.filepath)?;
569 blobs.insert(path.clone(), entry.oid);
570 listing.files.push(path);
571 }
572 }
573 listing.files.sort();
574 listing.submodules.sort();
575 Ok((listing, blobs))
576}
577
578fn repo_path(rela_path: gix::bstr::BString) -> Result<RepoPath, GitError> {
579 let path = String::from_utf8(rela_path.into()).map_err(|source| GitError::NonUtf8Path {
580 path: String::from_utf8_lossy(source.as_bytes()).into_owned(),
581 source,
582 })?;
583 Ok(RepoPath::new(path)?)
584}