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