How is "git pull" done with the git2-rs Rust crate?

Viewed 905

I'm using git2-rs to implement some standard git functionality in a Rust application. I've been reading up on git internals and understand that at a high level "git pull" is a "git fetch" followed by a "git merge", but am still having trouble understanding how to make it work with git2-rs. There is a discussion on an issue here where it's agreed that a git2-rs "git pull" example would be nice, but one was never created. There is an example of doing a hard reset in that discussion, but I want to avoid overwriting local changes (thus the merge). I have been unable to find an example in any other codebases that use git2-rs as well.

The "git reset" example here shows how to get an OID after a fetch I think, but the merge function takes an AnnotatedCommit, and I'm not sure how to convert between the two, or even if that's the right direction to go.

1 Answers

Try something like:

        let our_commit = find_last_commit()?;
        let reference = repo.find_reference("FETCH_HEAD")?;
        let their_commit = reference.peel_to_commit()?;
        let _index = repo
                .merge_commits(&our_commit, &their_commit, Some(&MergeOptions::new()))?;

using

   pub fn find_last_commit(repo: &Repository) -> Result<Commit, RepoError> {
        let obj = repo.head()?.resolve()?.peel(ObjectType::Commit)?;
        match obj.into_commit() {
            Ok(c) => Ok(c),
            _ => Err(RepoError::new("commit error")),
        }
    } 
Related