Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow find object by prefix #1014

Merged
merged 1 commit into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions libgit2-sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2205,6 +2205,13 @@ extern "C" {
id: *const git_oid,
kind: git_object_t,
) -> c_int;
pub fn git_object_lookup_prefix(
dest: *mut *mut git_object,
repo: *mut git_repository,
id: *const git_oid,
len: size_t,
kind: git_object_t,
) -> c_int;
pub fn git_object_type(obj: *const git_object) -> git_object_t;
pub fn git_object_peel(
peeled: *mut *mut git_object,
Expand Down
30 changes: 30 additions & 0 deletions src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1459,6 +1459,25 @@ impl Repository {
}
}

/// Lookup a reference to one of the objects by id prefix in a repository.
pub fn find_object_by_prefix(
&self,
prefix_hash: &str,
kind: Option<ObjectType>,
) -> Result<Object<'_>, Error> {
let mut raw = ptr::null_mut();
unsafe {
try_call!(raw::git_object_lookup_prefix(
&mut raw,
self.raw(),
Oid::from_str(prefix_hash)?.raw(),
prefix_hash.len(),
kind
));
Ok(Binding::from_raw(raw))
}
}

/// Create a new direct reference.
///
/// This function will return an error if a reference already exists with
Expand Down Expand Up @@ -3678,6 +3697,17 @@ mod tests {
assert_eq!(repo.head().unwrap().target().unwrap(), main_oid);
}

#[test]
fn smoke_find_object_by_prefix() {
let (_td, repo) = crate::test::repo_init();
let head = repo.head().unwrap().target().unwrap();
let head = repo.find_commit(head).unwrap();
let head_id = head.id();
let head_prefix = &head_id.to_string()[..7];
let obj = repo.find_object_by_prefix(head_prefix, None).unwrap();
assert_eq!(obj.id(), head_id);
}

/// create the following:
/// /---o4
/// /---o3
Expand Down