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

Add bindings for git_index_find_prefix #903

Merged
merged 4 commits into from
Feb 27, 2023
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
5 changes: 5 additions & 0 deletions libgit2-sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2953,6 +2953,11 @@ extern "C" {
pub fn git_index_entrycount(entry: *const git_index) -> size_t;
pub fn git_index_find(at_pos: *mut size_t, index: *mut git_index, path: *const c_char)
-> c_int;
pub fn git_index_find_prefix(
at_pos: *mut size_t,
index: *mut git_index,
prefix: *const c_char,
) -> c_int;
pub fn git_index_free(index: *mut git_index);
pub fn git_index_get_byindex(index: *mut git_index, n: size_t) -> *const git_index_entry;
pub fn git_index_get_bypath(
Expand Down
39 changes: 38 additions & 1 deletion src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,22 @@ impl Index {
Ok(Binding::from_raw(&raw as *const _))
}
}

/// Find the first position of any entries matching a prefix.
///
/// To find the first position of a path inside a given folder, suffix the prefix with a '/'.
pub fn find_prefix<T: IntoCString>(&self, prefix: T) -> Result<usize, Error> {
let mut at_pos: size_t = 0;
let entry_path = prefix.into_c_string()?;
unsafe {
try_call!(raw::git_index_find_prefix(
&mut at_pos,
self.raw,
entry_path
));
Ok(at_pos)
}
}
}

impl Binding for Index {
Expand Down Expand Up @@ -746,7 +762,7 @@ mod tests {
use std::path::Path;
use tempfile::TempDir;

use crate::{Index, IndexEntry, IndexTime, Oid, Repository, ResetType};
use crate::{ErrorCode, Index, IndexEntry, IndexTime, Oid, Repository, ResetType};

#[test]
fn smoke() {
Expand Down Expand Up @@ -857,6 +873,27 @@ mod tests {
assert_eq!(e.path.len(), 6);
}

#[test]
fn add_then_find() {
let mut index = Index::new().unwrap();
let mut e = entry();
e.path = b"foo/bar".to_vec();
index.add(&e).unwrap();
let mut e = entry();
e.path = b"foo2/bar".to_vec();
index.add(&e).unwrap();
assert_eq!(index.get(0).unwrap().path, b"foo/bar");
assert_eq!(
index.get_path(Path::new("foo/bar"), 0).unwrap().path,
b"foo/bar"
);
assert_eq!(index.find_prefix(Path::new("foo2/")), Ok(1));
assert_eq!(
index.find_prefix(Path::new("empty/")).unwrap_err().code(),
ErrorCode::NotFound
);
}

#[test]
fn add_frombuffer_then_read() {
let (_td, repo) = crate::test::repo_init();
Expand Down