Skip to main content

ObjectId

Struct ObjectId 

Source
pub struct ObjectId(/* private fields */);
Expand description

A 20-byte SHA-1 object identifier.

Implementations§

Source§

impl ObjectId

Source

pub const fn zero() -> Self

The all-zero object id (Git’s “null” OID).

Used for index placeholders such as intent-to-add entries and for special cases in plumbing output.

Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self>

Construct from a 20-byte slice.

§Errors

Returns Error::InvalidObjectId when bytes is not exactly 20 bytes.

Source

pub fn as_bytes(&self) -> &[u8; 20]

Raw 20-byte digest.

Source

pub fn is_zero(&self) -> bool

Check if this is the null (all-zero) object ID.

Source

pub fn to_hex(&self) -> String

Lowercase hex representation (40 characters).

Examples found in repository?
examples/rev_parse.rs (line 57)
11fn main() -> grit_lib::error::Result<()> {
12    let root = tempfile::tempdir()?;
13    let repo = init_repository(root.path(), false, "main", None, "files")?;
14
15    use grit_lib::index::{Index, IndexEntry, MODE_REGULAR};
16    let blob_oid = repo.odb.write(ObjectKind::Blob, b"x\n")?;
17    let path = b"a".to_vec();
18    let entry = IndexEntry {
19        ctime_sec: 0,
20        ctime_nsec: 0,
21        mtime_sec: 0,
22        mtime_nsec: 0,
23        dev: 0,
24        ino: 0,
25        mode: MODE_REGULAR,
26        uid: 0,
27        gid: 0,
28        size: 0,
29        oid: blob_oid,
30        flags: 1,
31        flags_extended: None,
32        path,
33        base_index_pos: 0,
34    };
35    let mut index = Index::new();
36    index.add_or_replace(entry);
37    repo.write_index(&mut index)?;
38    let index = repo.load_index()?;
39    let tree_oid = write_tree_from_index(&repo.odb, &index, "")?;
40    let commit = CommitData {
41        tree: tree_oid,
42        parents: Vec::new(),
43        author: "Example <example@example.com> 1700000000 +0000".to_owned(),
44        committer: "Example <example@example.com> 1700000000 +0000".to_owned(),
45        author_raw: Vec::new(),
46        committer_raw: Vec::new(),
47        encoding: None,
48        message: "r\n".to_owned(),
49        raw_message: None,
50    };
51    let oid = repo
52        .odb
53        .write(ObjectKind::Commit, &serialize_commit(&commit))?;
54    refs::write_ref(&repo.git_dir, "refs/heads/main", &oid)?;
55
56    let head = resolve_revision(&repo, "HEAD")?;
57    let full = resolve_revision(&repo, &oid.to_hex())?;
58    println!("HEAD resolves to {head}");
59    println!("full hex resolves to {full}");
60    assert_eq!(head, full);
61
62    Ok(())
63}
More examples
Hide additional examples
examples/cherry_pick.rs (line 168)
48fn main() -> grit_lib::error::Result<()> {
49    let root = tempfile::tempdir()?;
50    let repo = init_repository(root.path(), false, "main", None, "files")?;
51
52    use grit_lib::index::{Index, IndexEntry, MODE_REGULAR};
53
54    // Base commit on main: one file.
55    let blob_a = repo.odb.write(ObjectKind::Blob, b"base\n")?;
56    let mut index = Index::new();
57    index.add_or_replace(IndexEntry {
58        ctime_sec: 0,
59        ctime_nsec: 0,
60        mtime_sec: 0,
61        mtime_nsec: 0,
62        dev: 0,
63        ino: 0,
64        mode: MODE_REGULAR,
65        uid: 0,
66        gid: 0,
67        size: 0,
68        oid: blob_a,
69        flags: 7,
70        flags_extended: None,
71        path: b"base.txt".to_vec(),
72        base_index_pos: 0,
73    });
74    repo.write_index(&mut index)?;
75    let index = repo.load_index()?;
76    let tree_a = write_tree_from_index(&repo.odb, &index, "")?;
77    let commit_a = commit_from_tree(&repo, tree_a, &[], "initial\n")?;
78    refs::write_ref(&repo.git_dir, "refs/heads/main", &commit_a)?;
79
80    // Topic commit: parent A, adds picked.txt (not on main yet).
81    let blob_pick = repo.odb.write(ObjectKind::Blob, b"hello from topic\n")?;
82    let mut index = Index::new();
83    index.add_or_replace(IndexEntry {
84        ctime_sec: 0,
85        ctime_nsec: 0,
86        mtime_sec: 0,
87        mtime_nsec: 0,
88        dev: 0,
89        ino: 0,
90        mode: MODE_REGULAR,
91        uid: 0,
92        gid: 0,
93        size: 0,
94        oid: blob_a,
95        flags: 7,
96        flags_extended: None,
97        path: b"base.txt".to_vec(),
98        base_index_pos: 0,
99    });
100    index.add_or_replace(IndexEntry {
101        ctime_sec: 0,
102        ctime_nsec: 0,
103        mtime_sec: 0,
104        mtime_nsec: 0,
105        dev: 0,
106        ino: 0,
107        mode: MODE_REGULAR,
108        uid: 0,
109        gid: 0,
110        size: 0,
111        oid: blob_pick,
112        flags: 9,
113        flags_extended: None,
114        path: b"picked.txt".to_vec(),
115        base_index_pos: 0,
116    });
117    repo.write_index(&mut index)?;
118    let index = repo.load_index()?;
119    let tree_b = write_tree_from_index(&repo.odb, &index, "")?;
120    let commit_b = commit_from_tree(&repo, tree_b, &[commit_a], "add picked file\n")?;
121    refs::write_ref(&repo.git_dir, "refs/heads/topic", &commit_b)?;
122
123    // Cherry-pick `topic` onto `main` (still at A).
124    let head = resolve_revision(&repo, "main")?;
125    let picked = resolve_revision(&repo, "topic")?;
126    let picked_obj = repo.odb.read(&picked)?;
127    let picked_data = parse_commit(&picked_obj.data)?;
128    let parent = picked_data.parents.first().copied().ok_or_else(|| {
129        grit_lib::error::Error::CorruptObject("picked commit has no parent".into())
130    })?;
131
132    let base_tree = tree_of_commit(&repo, parent)?;
133    let ours_tree = tree_of_commit(&repo, head)?;
134    let theirs_tree = picked_data.tree;
135
136    let merged = merge_trees_three_way(
137        &repo,
138        base_tree,
139        ours_tree,
140        theirs_tree,
141        MergeFavor::default(),
142        WhitespaceMergeOptions::default(),
143        grit_lib::merge_trees::TreeMergeConflictPresentation {
144            label_ours: "HEAD",
145            label_theirs: grit_lib::merge_trees::TheirsConflictLabel::Fixed("picked"),
146            label_base: "parent of picked commit",
147            style: grit_lib::merge_file::ConflictStyle::Merge,
148            checkout_merge: false,
149        },
150    )?;
151
152    if !merged.conflict_content.is_empty() {
153        return Err(grit_lib::error::Error::Message(format!(
154            "merge produced {} conflict path(s); this example expects a clean pick",
155            merged.conflict_content.len()
156        )));
157    }
158
159    let new_tree = write_tree_from_index(&repo.odb, &merged.index, "")?;
160    let config = ConfigSet::load_repo_local_only(&repo.git_dir)?;
161    let msg = commit_trailers::finalize_cherry_pick_message(
162        &picked_data.message,
163        true,
164        false,
165        "Example",
166        "example@example.com",
167        &config,
168        &picked.to_hex(),
169    );
170    let new_commit = commit_from_tree(&repo, new_tree, &[head], &msg)?;
171    refs::write_ref(&repo.git_dir, "refs/heads/main", &new_commit)?;
172
173    println!("cherry-picked {} onto {}", picked, head);
174    println!("new main: {new_commit}");
175    let out = repo.odb.read(&new_commit)?;
176    println!("message:\n{}", parse_commit(&out.data)?.message);
177
178    Ok(())
179}
Source

pub fn loose_prefix(&self) -> String

The two-character directory prefix used by the loose object store.

Returns the first two hex chars (e.g. "ab" for "ab3f…").

Source

pub fn from_hex(s: &str) -> Result<Self>

Parse an object ID from a hex string.

§Errors

Returns Error::InvalidObjectId if the string is not a valid 40-character hex OID.

Source

pub fn loose_suffix(&self) -> String

The 38-character suffix used as the filename inside the loose prefix dir.

Trait Implementations§

Source§

impl Clone for ObjectId

Source§

fn clone(&self) -> ObjectId

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ObjectId

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ObjectId

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for ObjectId

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for ObjectId

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for ObjectId

Source§

fn cmp(&self, other: &ObjectId) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for ObjectId

Source§

fn eq(&self, other: &ObjectId) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for ObjectId

Source§

fn partial_cmp(&self, other: &ObjectId) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for ObjectId

Source§

impl Eq for ObjectId

Source§

impl StructuralPartialEq for ObjectId

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.