1use crate::{DiskTree, RelPath, TreeError};
7use purrdf_lex::allocation::{Admission, Memory, Resident, StorageError};
8use std::path::{Path, PathBuf};
9
10#[derive(Debug)]
12pub struct Error {
13 operation: &'static str,
14 source: Box<dyn std::error::Error + Send + Sync>,
15}
16
17impl Error {
18 pub(crate) fn storage(&self) -> Option<StorageError> {
19 self.source.downcast_ref::<StorageError>().copied()
20 }
21 fn native(
22 operation: &'static str,
23 source: impl std::error::Error + Send + Sync + 'static,
24 ) -> Self {
25 Self {
26 operation,
27 source: Box::new(source),
28 }
29 }
30
31 fn invalid(operation: &'static str, message: &'static str) -> Self {
32 Self::native(
33 operation,
34 std::io::Error::new(std::io::ErrorKind::InvalidData, message),
35 )
36 }
37}
38
39impl std::fmt::Display for Error {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 write!(f, "native Git {}: {}", self.operation, self.source)
42 }
43}
44
45impl std::error::Error for Error {
46 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
47 Some(self.source.as_ref())
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum EntryKind {
54 Tree,
56 Blob,
58 Symlink,
60 Submodule,
62}
63
64impl EntryKind {
65 fn from_mode(mode: u16) -> Result<Self, Error> {
66 match mode {
67 0o040_000 => Ok(Self::Tree),
68 0o100_644 | 0o100_755 => Ok(Self::Blob),
69 0o120_000 => Ok(Self::Symlink),
70 0o160_000 => Ok(Self::Submodule),
71 _ => Err(Error::invalid(
72 "tree mode",
73 "unsupported committed entry mode",
74 )),
75 }
76 }
77}
78
79#[derive(Debug, Clone)]
81pub struct Entry {
82 pub path: String,
84 pub kind: EntryKind,
86 pub id: String,
88 pub size: usize,
90}
91
92#[derive(Debug, Clone)]
94pub struct Commit {
95 pub id: String,
97 pub tree: String,
99 pub parents: Vec<String>,
101 pub author_date: String,
103 pub commit_seconds: i64,
105 pub subject: String,
107}
108
109#[derive(Debug)]
117pub struct Repository {
118 inner: gix::Repository,
119 directory: PathBuf,
120 selected_index: Option<PathBuf>,
121}
122
123const OBJECT_BOUND: usize = 16 * 1024 * 1024;
124
125impl Repository {
126 pub fn discover(directory: impl AsRef<Path>) -> Result<Option<Self>, Error> {
132 Self::discover_bounded(directory, OBJECT_BOUND)
133 }
134
135 fn discover_bounded(
136 directory: impl AsRef<Path>,
137 allocation_limit: usize,
138 ) -> Result<Option<Self>, Error> {
139 if allocation_limit == 0 || i64::try_from(allocation_limit).is_err() {
140 return Err(Error::invalid(
141 "allocation limit",
142 "native per-allocation grant must be nonzero and fit the configuration integer",
143 ));
144 }
145 let directory = directory
146 .as_ref()
147 .canonicalize()
148 .map_err(|e| Error::native("directory", e))?;
149 let options = gix::open::Options::isolated()
150 .strict_config(true)
151 .config_overrides([
152 "core.useReplaceRefs=false".to_owned(),
153 format!("gitoxide.objects.allocLimit={allocation_limit}"),
154 ]);
155 match gix::discover_opts(
156 &directory,
157 gix::discover::upwards::Options::default(),
158 options,
159 ) {
160 Ok(inner) => Ok(Some(Self {
161 inner,
162 directory,
163 selected_index: None,
164 })),
165 Err(error)
166 if error
167 .downcast_any_ref::<gix::discover::upwards::Error>()
168 .is_some_and(|e| {
169 matches!(
170 e,
171 gix::discover::upwards::Error::NoGitRepository { .. }
172 | gix::discover::upwards::Error::NoGitRepositoryWithinCeiling { .. }
173 | gix::discover::upwards::Error::NoGitRepositoryWithinFs { .. }
174 )
175 }) =>
176 {
177 Ok(None)
178 }
179 Err(error) => Err(Error::native("discover", error)),
180 }
181 }
182
183 pub fn open(directory: impl AsRef<Path>) -> Result<Self, Error> {
188 Self::discover(directory)?
189 .ok_or_else(|| Error::invalid("open", "directory is outside a Git repository"))
190 }
191
192 pub fn open_with_allocation_limit(
201 directory: impl AsRef<Path>,
202 allocation_limit: usize,
203 ) -> Result<Self, Error> {
204 Self::discover_bounded(directory, allocation_limit)?
205 .ok_or_else(|| Error::invalid("open", "directory is outside a Git repository"))
206 }
207
208 pub fn open_with_index(
213 directory: impl AsRef<Path>,
214 index: Option<&Path>,
215 ) -> Result<Self, Error> {
216 let mut repo = Self::open(directory)?;
217 repo.selected_index = index.map(|path| {
218 if path.is_absolute() {
219 path.to_path_buf()
220 } else {
221 repo.directory.join(path)
222 }
223 });
224 Ok(repo)
225 }
226
227 #[must_use]
229 pub fn directory(&self) -> &Path {
230 &self.directory
231 }
232
233 #[must_use]
235 pub fn git_dir(&self) -> &Path {
236 self.inner.git_dir()
237 }
238
239 #[must_use]
241 pub fn common_dir(&self) -> &Path {
242 self.inner.common_dir()
243 }
244
245 #[must_use]
247 pub fn work_dir(&self) -> Option<&Path> {
248 self.inner.workdir()
249 }
250
251 pub fn main_work_dir(&self) -> Result<Option<PathBuf>, Error> {
260 let main = self
261 .inner
262 .main_repo()
263 .map_err(|error| Error::native("main worktree", error))?;
264 main.workdir()
265 .map(|root| {
266 root.canonicalize()
267 .map_err(|error| Error::native("main worktree", error))
268 })
269 .transpose()
270 }
271
272 #[must_use]
274 pub fn index_path(&self) -> PathBuf {
275 self.selected_index
276 .clone()
277 .unwrap_or_else(|| self.git_dir().join("index"))
278 }
279
280 fn entry_size(&self, id: gix::ObjectId, kind: EntryKind) -> Result<usize, Error> {
281 if !matches!(kind, EntryKind::Blob | EntryKind::Symlink) {
282 return Ok(0);
283 }
284 let header = self
285 .inner
286 .find_header(id)
287 .map_err(|error| Error::native("blob header", error))?;
288 if header.kind() != gix::objs::Kind::Blob {
289 return Err(Error::invalid("blob", "blob mode names a non-blob object"));
290 }
291 usize::try_from(header.size()).map_err(|error| Error::native("blob size", error))
292 }
293
294 fn id(&self, text: &str) -> Result<gix::ObjectId, Error> {
295 let id =
296 gix::ObjectId::from_hex(text.as_bytes()).map_err(|e| Error::native("object ID", e))?;
297 if id.kind() != self.inner.object_hash() {
298 return Err(Error::invalid(
299 "object ID",
300 "identifier hash format differs from repository",
301 ));
302 }
303 Ok(id)
304 }
305
306 fn object(&self, id: gix::ObjectId, max: usize) -> Result<gix::Object<'_>, Error> {
307 let header = self
308 .inner
309 .find_header(id)
310 .map_err(|e| Error::native("object header", e))?;
311 if header.size() > max as u64 {
312 return Err(Error::invalid(
313 "object size",
314 "decoded object exceeds the selected byte bound",
315 ));
316 }
317 let object = self
318 .inner
319 .find_object(id)
320 .map_err(|e| Error::native("object", e))?;
321 if object.data.len() > max || object.data.len() as u64 != header.size() {
322 return Err(Error::invalid(
323 "object size",
324 "decoded object differs from admitted size",
325 ));
326 }
327 let actual = gix::objs::compute_hash(id.kind(), object.kind, &object.data)
328 .map_err(|e| Error::native("object hash", e))?;
329 if actual != id {
330 return Err(Error::invalid(
331 "object hash",
332 "object bytes do not match their identity",
333 ));
334 }
335 Ok(object)
336 }
337
338 pub fn resolve_commit(&self, reference: &str) -> Result<String, Error> {
343 let id = if reference == "HEAD" {
344 self.inner
345 .head_id()
346 .map_err(|e| Error::native("HEAD", e))?
347 .detach()
348 } else if reference.starts_with("refs/") {
349 self.inner
350 .find_reference(reference)
351 .map_err(|e| Error::native("reference", e))?
352 .peel_to_id()
353 .map_err(|e| Error::native("reference target", e))?
354 .detach()
355 } else {
356 self.id(reference)?
357 };
358 let object = self.object(id, OBJECT_BOUND)?;
359 if object.kind != gix::objs::Kind::Commit {
360 return Err(Error::invalid("commit", "selected object is not a commit"));
361 }
362 Ok(id.to_string())
363 }
364
365 pub fn default_branch_ref(&self) -> Result<String, Error> {
370 let reference = self
371 .inner
372 .find_reference("refs/remotes/origin/HEAD")
373 .map_err(|e| Error::native("origin HEAD", e))?;
374 match reference.target() {
375 gix::refs::TargetRef::Symbolic(name) => Ok(name.as_bstr().to_string()),
376 gix::refs::TargetRef::Object(_) => Err(Error::invalid(
377 "origin HEAD",
378 "origin HEAD must be a symbolic reference",
379 )),
380 }
381 }
382
383 pub fn merge_base(&self, one: &str, two: &str) -> Result<Option<String>, Error> {
388 self.inner
389 .merge_base(self.id(one)?, self.id(two)?)
390 .map(|id| id.map(|id| id.to_string()))
391 .map_err(|e| Error::native("merge base", e))
392 }
393
394 pub fn tracked_paths(&self, max: usize) -> Result<Option<Vec<String>>, Error> {
402 if self.directory.starts_with(self.git_dir()) {
403 return Ok(None);
404 }
405 let Some(root) = self.work_dir() else {
406 return Ok(None);
407 };
408 let Ok(prefix) = self.directory.strip_prefix(root) else {
409 return Ok(None);
410 };
411 let index_path = self.index_path();
412 let parent = index_path
413 .parent()
414 .ok_or_else(|| Error::invalid("index", "index must have a parent directory"))?;
415 let name = index_path
416 .file_name()
417 .and_then(|name| name.to_str())
418 .ok_or_else(|| Error::invalid("index", "index filename must be UTF-8"))?;
419 let path = RelPath::new(name).map_err(|e| Error::native("index path", e))?;
420 let disk = DiskTree::new(parent).map_err(|e| Error::native("index directory", e))?;
421 match disk.byte_len(&path) {
422 Ok(bytes) if bytes > max as u64 => {
423 return Err(Error::invalid(
424 "index",
425 "index exceeds the selected byte bound",
426 ));
427 }
428 Ok(_) => {}
429 Err(TreeError::NotFound { .. }) if self.selected_index.is_none() => {
430 return Ok(Some(Vec::new()));
431 }
432 Err(e) => return Err(Error::native("index metadata", e)),
433 }
434 let index = gix::index::File::at(
435 index_path,
436 self.inner.object_hash(),
437 false,
438 gix::index::decode::Options {
439 alloc_limit_bytes: Some(max),
440 ..Default::default()
441 },
442 )
443 .map_err(|e| Error::native("index", e))?;
444 let mut paths = Vec::new();
445 let mut acquired = 0usize;
446 for entry in index.entries() {
447 let name = std::str::from_utf8(entry.path(&index))
448 .map_err(|e| Error::native("index path", e))?;
449 canonical_path(name)?;
450 let Ok(relative) = Path::new(name).strip_prefix(prefix) else {
451 continue;
452 };
453 let relative = relative
454 .to_str()
455 .ok_or_else(|| Error::invalid("index path", "non-UTF-8 relative path"))?;
456 acquired = acquired
457 .checked_add(relative.len() + 1)
458 .filter(|n| *n <= max)
459 .ok_or_else(|| {
460 Error::invalid("index paths", "paths exceed the selected byte bound")
461 })?;
462 if paths.last().is_none_or(|last| last != relative) {
463 paths.push(relative.to_owned());
464 }
465 }
466 Ok(Some(paths))
467 }
468
469 pub fn commit(&self, id: &str) -> Result<Commit, Error> {
476 let id = self.id(id)?;
477 let object = self.object(id, OBJECT_BOUND)?;
478 if object.kind != gix::objs::Kind::Commit {
479 return Err(Error::invalid("commit", "object is not a commit"));
480 }
481 let decoded = gix::objs::CommitRef::from_bytes(&object.data, id.kind())
482 .map_err(|e| Error::native("commit decoding", e))?;
483 let author = decoded
484 .author()
485 .map_err(|e| Error::native("author", e))?
486 .time()
487 .map_err(|e| Error::native("author date", e))?;
488 let committer = decoded
489 .committer()
490 .map_err(|e| Error::native("committer", e))?
491 .time()
492 .map_err(|e| Error::native("committer date", e))?;
493 let author_date = author
494 .format(gix::date::time::format::ISO8601_STRICT)
495 .map_err(|e| Error::native("author date", e))?;
496 if decoded.encoding.is_some_and(|encoding| {
497 !encoding.eq_ignore_ascii_case(b"UTF-8") && !encoding.eq_ignore_ascii_case(b"UTF8")
498 }) {
499 return Err(Error::invalid(
500 "commit encoding",
501 "only UTF-8 commit message encodings are supported",
502 ));
503 }
504 let message = std::str::from_utf8(decoded.message)
505 .map_err(|error| Error::native("commit message UTF-8", error))?;
506 let subject = message
507 .split("\n\n")
508 .next()
509 .unwrap_or_default()
510 .lines()
511 .map(str::trim)
512 .collect::<Vec<_>>()
513 .join(" ");
514 Ok(Commit {
515 id: id.to_string(),
516 tree: decoded.tree().to_string(),
517 parents: decoded.parents().map(|p| p.to_string()).collect(),
518 author_date,
519 commit_seconds: committer.seconds,
520 subject,
521 })
522 }
523
524 pub fn is_shallow(&self) -> Result<bool, Error> {
529 self.inner
530 .is_shallow()
531 .map_err(|e| Error::native("shallow metadata", e))
532 }
533
534 pub fn relative_history_paths(&self) -> Result<bool, Error> {
539 self.inner
540 .config_snapshot()
541 .try_boolean("diff.relative")
542 .map(|value| value.unwrap_or(false))
543 .map_err(|error| Error::native("relative history paths", error))
544 }
545
546 pub fn tree(&self, commit: &str, max: usize) -> Result<Vec<Entry>, Error> {
551 self.tree_admitted(commit, max, &mut Memory::new(&mut Resident))
552 }
553
554 pub(crate) fn tree_admitted<S: Admission + ?Sized>(
555 &self,
556 commit: &str,
557 max: usize,
558 memory: &mut Memory<'_, S>,
559 ) -> Result<Vec<Entry>, Error> {
560 let commit = self.commit(commit)?;
561 let mut pending = Vec::new();
562 memory
563 .push(&mut pending, (self.id(&commit.tree)?, String::new()))
564 .map_err(|e| Error::native("tree storage", e))?;
565 let mut entries = Vec::new();
566 let mut acquired = 0usize;
567 while let Some((id, prefix)) = pending.pop() {
568 let object = self.object(id, max)?;
569 if object.kind != gix::objs::Kind::Tree {
570 return Err(Error::invalid("tree", "directory object is not a tree"));
571 }
572 for entry in gix::objs::TreeRefIter::from_bytes(&object.data, id.kind()) {
573 let entry = entry.map_err(|e| Error::native("tree decoding", e))?;
574 let name = std::str::from_utf8(entry.filename)
575 .map_err(|e| Error::native("tree path", e))?;
576 if name.contains('/') {
577 return Err(Error::invalid(
578 "tree path",
579 "tree entry name contains a slash",
580 ));
581 }
582 canonical_path(name)?;
583 let length = prefix
584 .len()
585 .saturating_add(name.len())
586 .saturating_add(usize::from(!prefix.is_empty()));
587 memory
588 .admission_mut()
589 .checkpoint(
590 u64::try_from(length.saturating_add(64))
591 .map_err(|e| Error::native("tree work", e))?,
592 )
593 .map_err(|e| Error::native("tree work", e))?;
594 acquired = acquired
595 .checked_add(length + size_of::<Entry>() + 64)
596 .filter(|n| *n <= max)
597 .ok_or_else(|| {
598 Error::invalid("tree", "complete tree listing exceeds selected byte bound")
599 })?;
600 let path = if prefix.is_empty() {
601 memory.string(name)
602 } else {
603 memory.format(&format_args!("{prefix}/{name}"))
604 }
605 .map_err(|e| Error::native("tree storage", e))?;
606 let kind = EntryKind::from_mode(entry.mode.value())?;
607 let size = self.entry_size(entry.oid.to_owned(), kind)?;
608 if kind == EntryKind::Tree {
609 let copy = memory
610 .string(&path)
611 .map_err(|e| Error::native("tree storage", e))?;
612 memory
613 .push(&mut pending, (entry.oid.to_owned(), copy))
614 .map_err(|e| Error::native("tree storage", e))?;
615 }
616 let id = memory
617 .format(&format_args!("{}", entry.oid))
618 .map_err(|e| Error::native("tree storage", e))?;
619 memory
620 .push(
621 &mut entries,
622 Entry {
623 path,
624 kind,
625 id,
626 size,
627 },
628 )
629 .map_err(|e| Error::native("tree storage", e))?;
630 }
631 memory
632 .release_string(prefix)
633 .map_err(|e| Error::native("tree storage", e))?;
634 }
635 memory
636 .release_vec(pending)
637 .map_err(|e| Error::native("tree storage", e))?;
638 purrdf_lex::walk::try_sort_unstable_by(&mut entries, |a, b| {
639 memory
640 .admission_mut()
641 .checkpoint(
642 u64::try_from(a.path.len().saturating_add(b.path.len()).saturating_add(1))
643 .map_err(|e| Error::native("tree ordering work", e))?,
644 )
645 .map_err(|e| Error::native("tree ordering work", e))?;
646 Ok::<_, Error>(a.path.cmp(&b.path))
647 })?;
648 if entries.windows(2).any(|p| p[0].path == p[1].path) {
649 return Err(Error::invalid("tree", "tree repeats a path"));
650 }
651 Ok(entries)
652 }
653
654 pub fn blob(&self, id: &str, max: usize) -> Result<Vec<u8>, Error> {
659 self.blob_admitted(id, max, &mut Memory::new(&mut Resident))
660 }
661
662 pub(crate) fn blob_admitted<S: Admission + ?Sized>(
663 &self,
664 id: &str,
665 max: usize,
666 memory: &mut Memory<'_, S>,
667 ) -> Result<Vec<u8>, Error> {
668 let object = self.object(self.id(id)?, max)?;
669 if object.kind != gix::objs::Kind::Blob {
670 return Err(Error::invalid("blob", "selected object is not a blob"));
671 }
672 let mut output = Vec::new();
673 memory
674 .reserve(&mut output, object.data.len())
675 .map_err(|e| Error::native("blob storage", e))?;
676 output.extend_from_slice(&object.data);
677 Ok(output)
678 }
679
680 pub fn entry_at(&self, commit: &str, path: &str) -> Result<Option<Entry>, Error> {
685 canonical_path(path)?;
686 let mut id = self.id(&self.commit(commit)?.tree)?;
687 let mut components = path.split('/').peekable();
688 while let Some(component) = components.next() {
689 let object = self.object(id, OBJECT_BOUND)?;
690 if object.kind != gix::objs::Kind::Tree {
691 return Err(Error::invalid("path", "intermediate object is not a tree"));
692 }
693 let mut found = None;
694 let mut names = std::collections::BTreeSet::new();
695 for entry in gix::objs::TreeRefIter::from_bytes(&object.data, id.kind()) {
696 let entry = entry.map_err(|e| Error::native("tree decoding", e))?;
697 let name = std::str::from_utf8(entry.filename)
698 .map_err(|e| Error::native("tree path", e))?;
699 canonical_path(name)?;
700 if name.contains('/') || !names.insert(name) {
701 return Err(Error::invalid(
702 "tree",
703 "invalid or duplicate tree entry name",
704 ));
705 }
706 if name == component {
707 found = Some((entry.mode.value(), entry.oid.to_owned()));
708 }
709 }
710 let Some((mode, next)) = found else {
711 return Ok(None);
712 };
713 let kind = EntryKind::from_mode(mode)?;
714 if components.peek().is_some() {
715 if kind != EntryKind::Tree {
716 return Err(Error::invalid(
717 "path",
718 "intermediate path is not a directory",
719 ));
720 }
721 id = next;
722 } else {
723 let size = self.entry_size(next, kind)?;
724 return Ok(Some(Entry {
725 path: path.to_owned(),
726 kind,
727 id: next.to_string(),
728 size,
729 }));
730 }
731 }
732 Err(Error::invalid("path", "empty path"))
733 }
734
735 pub fn ancestors(&self, max: usize) -> Result<Vec<Commit>, Error> {
740 let head = self.commit(&self.resolve_commit("HEAD")?)?;
741 let mut pending = std::collections::BinaryHeap::new();
742 pending.push((head.commit_seconds, head.id));
743 let mut seen = std::collections::BTreeSet::new();
744 let mut output = Vec::new();
745 let mut acquired = 0usize;
746 while let Some((_, id)) = pending.pop() {
747 if !seen.insert(id.clone()) {
748 continue;
749 }
750 let commit = self.commit(&id)?;
751 acquired = acquired
752 .checked_add(commit.subject.len() + commit.parents.len() * 64 + 256)
753 .filter(|n| *n <= max)
754 .ok_or_else(|| {
755 Error::invalid("history", "commit traversal exceeds selected byte bound")
756 })?;
757 for parent in &commit.parents {
758 if !seen.contains(parent) {
759 let metadata = self.commit(parent)?;
760 pending.push((metadata.commit_seconds, metadata.id));
761 }
762 }
763 output.push(commit);
764 }
765 Ok(output)
766 }
767}
768
769fn canonical_path(path: &str) -> Result<(), Error> {
770 if path.is_empty()
771 || path
772 .split('/')
773 .any(|p| p.is_empty() || matches!(p, "." | "..") || p.contains(['\\', '\0']))
774 {
775 return Err(Error::invalid(
776 "path",
777 "Git paths must have nonempty canonical components",
778 ));
779 }
780 Ok(())
781}