Skip to main content

grit_lib/objects/
handle.rs

1//! Repository-scoped object database access via [`Objects`].
2use crate::change_id::{set_change_id, ChangeIdPolicy};
3use crate::error::ObjectError;
4use crate::error::{Error, Result};
5use crate::fsck_standalone::{fsck_object, FsckObjectOptions};
6use crate::objects::write::{
7    canonical_tree_entries, validate_tree_entry_stored_kinds, WriteTreeOptions,
8};
9use crate::objects::{
10    serialize_commit, serialize_tree, CommitData, NewCommit, Object, ObjectId, ObjectInfo,
11    ObjectKind, TreeEntry,
12};
13use crate::porcelain::commit::stamp_change_id_on_new_commit;
14use crate::repo::Repository;
15
16/// Read and write Git objects through a [`Repository`] handle.
17#[derive(Debug, Copy, Clone)]
18pub struct Objects<'repo> {
19    repo: &'repo Repository,
20}
21
22impl<'repo> Objects<'repo> {
23    /// Bind object operations to `repo`.
24    #[inline]
25    #[must_use]
26    pub fn new(repo: &'repo Repository) -> Self {
27        Self { repo }
28    }
29
30    /// Underlying repository.
31    #[inline]
32    #[must_use]
33    pub fn repository(&self) -> &'repo Repository {
34        self.repo
35    }
36
37    /// Returns whether `oid` is present in this repository's object database.
38    ///
39    /// # Errors
40    ///
41    /// Propagates a backend failure when no object source has `oid` (see
42    /// [`crate::odb::Odb::contains`]) instead of reporting it as missing.
43    ///
44    /// # Examples
45    ///
46    /// ```
47    /// # fn main() -> grit_lib::error::Result<()> {
48    /// use grit_lib::objects::ObjectKind;
49    /// use grit_lib::repo::{InitOptions, Repository};
50    /// let dir = std::env::temp_dir().join("grit-objects-handle-doc");
51    /// let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
52    /// let oid = repo.objects().write(ObjectKind::Blob, b"hello")?;
53    /// assert!(repo.objects().contains(&oid)?);
54    /// # Ok(())
55    /// # }
56    /// ```
57    #[inline]
58    pub fn contains(&self, oid: &ObjectId) -> Result<bool> {
59        self.repo.odb().contains(oid)
60    }
61
62    /// Read the object named `oid`.
63    ///
64    /// # Errors
65    ///
66    /// Returns [`crate::error::ObjectError::NotFound`] when the object is missing.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// # fn main() -> grit_lib::error::Result<()> {
72    /// use grit_lib::objects::ObjectKind;
73    /// use grit_lib::repo::{InitOptions, Repository};
74    /// let dir = std::env::temp_dir().join("grit-objects-read-doc");
75    /// let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
76    /// let oid = repo.objects().write(ObjectKind::Blob, b"payload")?;
77    /// let obj = repo.objects().read(&oid)?;
78    /// assert_eq!(obj.data, b"payload");
79    /// # Ok(())
80    /// # }
81    /// ```
82    #[inline]
83    pub fn read(&self, oid: &ObjectId) -> Result<Object> {
84        self.repo.odb().read(oid)
85    }
86
87    /// Read object type and size without inflating full blob bodies when possible.
88    ///
89    /// # Errors
90    ///
91    /// Propagates object lookup failures from the ODB.
92    #[inline]
93    pub fn read_info(&self, oid: &ObjectId) -> Result<ObjectInfo> {
94        self.repo.odb().read_info(oid)
95    }
96
97    /// Read `oid` and parse it as a commit (annotated tags are not followed).
98    ///
99    /// # Errors
100    ///
101    /// See [`crate::objects::odb::Odb::read_commit`]: a missing object, an object that is not
102    /// a commit ([`crate::error::ObjectError::UnexpectedKind`]), or a malformed commit.
103    ///
104    /// # Examples
105    ///
106    /// ```
107    /// # fn main() -> grit_lib::error::Result<()> {
108    /// use grit_lib::objects::ObjectKind;
109    /// use grit_lib::repo::{InitOptions, Repository};
110    /// let dir = std::env::temp_dir().join("grit-objects-read-commit-doc");
111    /// let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
112    /// let tree = repo.objects().write(ObjectKind::Tree, b"")?;
113    /// let body = format!(
114    ///     "tree {tree}\nauthor A <a@example.com> 0 +0000\ncommitter A <a@example.com> 0 +0000\n\nfirst\n"
115    /// );
116    /// let commit = repo.objects().write(ObjectKind::Commit, body.as_bytes())?;
117    /// assert_eq!(repo.objects().read_commit(&commit)?.message, "first\n");
118    /// assert_eq!(repo.objects().commit_tree(&commit)?, tree);
119    /// assert!(repo.objects().read_commit(&tree).is_err());
120    /// # Ok(())
121    /// # }
122    /// ```
123    #[inline]
124    pub fn read_commit(&self, oid: &ObjectId) -> Result<CommitData> {
125        self.repo.odb().read_commit(oid)
126    }
127
128    /// The root tree of the commit `oid`, decoding only the commit headers.
129    ///
130    /// # Errors
131    ///
132    /// Same as [`Self::read_commit`].
133    #[inline]
134    pub fn commit_tree(&self, oid: &ObjectId) -> Result<ObjectId> {
135        self.repo.odb().commit_tree(oid)
136    }
137
138    /// Hash `data` as a Git object of `kind` without writing to disk.
139    ///
140    /// # Errors
141    ///
142    /// Returns [`crate::error::ObjectError::HashCollision`] when sha1dc detects a chosen-prefix collision.
143    #[inline]
144    pub fn hash(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
145        self.repo.odb().hash(kind, data)
146    }
147
148    /// Validate and store an object, returning its id.
149    ///
150    /// Tree, commit and tag payloads must pass the same checks as `git hash-object -t <kind>`
151    /// (without `--literally`): sorted, duplicate-free tree entries with allowed modes and
152    /// names, and well-formed `tree`/`parent`/`author`/`committer`/`tagger` headers. Blobs
153    /// are stored as given. To build trees and commits from typed values instead of raw
154    /// bytes, use [`Self::write_tree`] and [`Self::write_commit`].
155    ///
156    /// # Errors
157    ///
158    /// - [`crate::error::ObjectError::Invalid`] when the payload would fail `git fsck`;
159    ///   nothing is written.
160    /// - [`crate::error::ObjectError::HashCollision`] and zlib or filesystem errors from the ODB.
161    ///
162    /// # Examples
163    ///
164    /// See also the [`guide_objects`](https://grit-scm.com/docs/library/objects/) example program.
165    pub fn write(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
166        fsck_object(
167            kind,
168            data,
169            FsckObjectOptions::new(self.repo.odb().hash_algo()),
170        )
171        .map_err(|check| Error::Object(ObjectError::Invalid { kind, check }))?;
172        self.repo.odb().write(kind, data)
173    }
174
175    /// Store `data` as an object of `kind` without validating its structure.
176    ///
177    /// The equivalent of `git hash-object --literally`: use it only to reproduce or test
178    /// corrupt objects. Repositories containing such objects fail `git fsck`.
179    ///
180    /// # Errors
181    ///
182    /// [`crate::error::ObjectError::HashCollision`] and zlib or filesystem errors from the ODB.
183    #[inline]
184    pub fn write_literally(&self, kind: ObjectKind, data: &[u8]) -> Result<ObjectId> {
185        self.repo.odb().write(kind, data)
186    }
187
188    /// Write a tree object from `entries`, given in any order.
189    ///
190    /// Entries are sorted into Git's tree order. Each entry's object must exist in this
191    /// repository with the kind implied by its mode (tree or blob; gitlink `160000` entries
192    /// may reference a commit that is not stored), matching `git mktree` without `--missing`.
193    /// Use
194    /// [`Self::write_tree_with`] with [`WriteTreeOptions::allow_missing`] when building
195    /// trees bottom-up or referencing objects a partial clone has not fetched.
196    ///
197    /// # Errors
198    ///
199    /// - [`crate::error::ObjectError::InvalidTreeEntry`] when an entry has an empty, `.`, `..`,
200    ///   `.git`-alias or slash/NUL-containing name, a mode other than `100644`, `100755`,
201    ///   `120000`, `40000` or `160000`, the null object id, an object id of the wrong hash
202    ///   algorithm, a name over 4096 bytes, a name used by another entry, or a symlink to a
203    ///   reserved metadata file name (`.gitmodules`, `.gitattributes`, and related spellings).
204    /// - [`crate::error::ObjectError::NotFound`] when a required entry object is missing.
205    /// - [`crate::error::ObjectError::UnexpectedKind`] when a stored object has the wrong kind.
206    /// - [`crate::error::ObjectError::HashCollision`] and zlib or filesystem errors from the ODB.
207    ///
208    /// # Examples
209    ///
210    /// ```
211    /// # fn main() -> grit_lib::error::Result<()> {
212    /// use grit_lib::objects::{ObjectKind, TreeEntry};
213    /// use grit_lib::repo::{InitOptions, Repository};
214    /// let dir = tempfile::tempdir()?;
215    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::new().with_bare(true))?;
216    /// let blob = repo.objects().write(ObjectKind::Blob, b"hello\n")?;
217    /// let entry = |name: &str| TreeEntry { mode: 0o100644, name: name.into(), oid: blob };
218    /// let tree = repo.objects().write_tree([entry("b"), entry("a")])?;
219    /// let names: Vec<_> = grit_lib::objects::parse_tree(&repo.objects().read(&tree)?.data)?
220    ///     .into_iter()
221    ///     .map(|e| e.name)
222    ///     .collect();
223    /// assert_eq!(names, [b"a".to_vec(), b"b".to_vec()]);
224    /// # Ok(())
225    /// # }
226    /// ```
227    pub fn write_tree(&self, entries: impl IntoIterator<Item = TreeEntry>) -> Result<ObjectId> {
228        self.write_tree_with(entries, WriteTreeOptions::default())
229    }
230
231    /// Write a tree object from `entries` with `options`.
232    ///
233    /// Same validation and sorting as [`Self::write_tree`], except that missing blob and
234    /// tree oids are accepted when [`WriteTreeOptions::allow_missing`] is set.
235    ///
236    /// # Errors
237    ///
238    /// Same as [`Self::write_tree`].
239    pub fn write_tree_with(
240        &self,
241        entries: impl IntoIterator<Item = TreeEntry>,
242        options: WriteTreeOptions,
243    ) -> Result<ObjectId> {
244        let odb = self.repo.odb();
245        let algo = odb.hash_algo();
246        let canonical = canonical_tree_entries(entries, algo)?;
247        validate_tree_entry_stored_kinds(odb, &canonical, options.allow_missing)?;
248        let data = serialize_tree(&canonical);
249        debug_assert!(
250            fsck_object(ObjectKind::Tree, &data, FsckObjectOptions::new(algo)).is_ok(),
251            "canonical_tree_entries let through a tree fsck rejects"
252        );
253        odb.write(ObjectKind::Tree, &data)
254    }
255
256    /// Write the commit described by `commit` and return its id.
257    ///
258    /// The tree must exist and be a tree, and every parent must exist and be a commit
259    /// (the checks `git commit-tree` makes). When `grit.changeIds` is enabled (the
260    /// default) and no id was set with [`NewCommit::with_change_id`], the commit gets a
261    /// fresh `change-id` header. The commit is not signed and no ref is updated; use
262    /// [`crate::porcelain::commit::create_commit`] to commit the index onto a branch.
263    ///
264    /// # Errors
265    ///
266    /// - [`crate::error::ObjectError::InvalidSignature`] when the author or committer has a
267    ///   `<`, `>` or control character in its name or email, a time before the Unix
268    ///   epoch, or a UTC offset with a seconds component.
269    /// - [`crate::error::ObjectError::NotFound`] when the tree or a parent is missing, and
270    ///   [`crate::error::ObjectError::UnexpectedKind`] when one has the wrong kind.
271    /// - Config loading errors from [`Repository::config`] (read for `grit.changeIds`).
272    /// - The errors of [`Self::write`].
273    ///
274    /// # Examples
275    ///
276    /// See [`NewCommit`].
277    pub fn write_commit(&self, commit: &NewCommit) -> Result<ObjectId> {
278        for signature in commit.signatures() {
279            signature.validate()?;
280        }
281        let (tree, parents) = commit.tree_and_parents();
282        self.expect_kind(tree, ObjectKind::Tree)?;
283        for parent in parents {
284            self.expect_kind(parent, ObjectKind::Commit)?;
285        }
286        let mut data = commit.to_commit_data();
287        match commit.change_id() {
288            Some(id) => set_change_id(&mut data, id),
289            None => {
290                let policy = ChangeIdPolicy::from_config(self.repo.config().snapshot()?.as_ref());
291                stamp_change_id_on_new_commit(self.repo, &policy, &mut data)?;
292            }
293        }
294        self.write(ObjectKind::Commit, &serialize_commit(&data))
295    }
296
297    fn expect_kind(&self, oid: &ObjectId, expected: ObjectKind) -> Result<()> {
298        let actual = self.read_info(oid)?.kind;
299        if actual != expected {
300            return Err(Error::Object(ObjectError::UnexpectedKind {
301                oid: *oid,
302                expected,
303                actual,
304            }));
305        }
306        Ok(())
307    }
308}