Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the behaviour of `git checkout ...` in Rust git2

I am using the Rust git2 crate to clone Git repositories like this

use git2::Repository;

fn main() {
    let repo = Repository::clone(
        "https://github.com/rossmacarthur/dotfiles",
        "dotfiles"
     ).expect("failed to clone repository");

     repo.checkout("mybranch");  // need something like this.
}

I want to be able to checkout a branch or a commit or a tag.

I have looked at the following documentation but am still not sure which method to use

  • https://docs.rs/git2/0.8.0/git2/struct.Repository.html#method.checkout_head
  • https://docs.rs/git2/0.8.0/git2/struct.Repository.html#method.checkout_tree
  • https://docs.rs/git2/0.8.0/git2/struct.Repository.html#method.checkout_index

I am able to do the following but it only changes the files

let object = repo
    .revparse_single("mybranch")
    .expect("failed to find identifier");
repo.checkout_tree(&object, None)
    .expect(&format!("failed to checkout '{:?}'", object));

And if I do a reset it changes the HEAD but not the current branch

repo.reset(&object, git2::ResetType::Soft, None)
    .expect(&format!("failed to checkout '{:?}'", object));
like image 750
Ross MacArthur Avatar asked Mar 13 '19 11:03

Ross MacArthur


2 Answers

With a more recent version of git2 (v0.13.18):

use git2::Repository;

fn main() {
    let repo = Repository::clone("https://github.com/rossmacarthur/dotfiles", "/tmp/dots")
        .expect("Failed to clone repo");

    let refname = "master"; // or a tag (v0.1.1) or a commit (8e8128)
    let (object, reference) = repo.revparse_ext(refname).expect("Object not found");
    
    repo.checkout_tree(&object, None)
        .expect("Failed to checkout");

    match reference {
        // gref is an actual reference like branches or tags
        Some(gref) => repo.set_head(gref.name().unwrap()),
        // this is a commit, not a reference
        None => repo.set_head_detached(object.id()),
    }
    .expect("Failed to set HEAD");
}

Note that checkout_tree only sets the contents of the working tree, and set_head only sets the HEAD. Running only one of them will leave the directory in a dirty state.

like image 172
sudormrfbin Avatar answered Nov 17 '22 09:11

sudormrfbin


The examples below are Rust v1.34 and git2 v0.8.

To checkout a branch:

use git2::*;

fn main() {
    let repo = Repository::clone(
        "https://github.com/rossmacarthur/dotfiles",
        "dotfiles"
    ).expect("failed to clone repository");

    let branch_name = "my_branch";

    let head = repo.head().unwrap();
    let oid = head.target().unwrap();
    let commit = repo.find_commit(oid).unwrap();

    let branch = repo.branch(
        branch_name,
        &commit,
        false,
    );

    let obj = repo.revparse_single(&("refs/heads/".to_owned() + 
        branch_name)).unwrap();

    repo.checkout_tree(
        &obj,
        None
    );

    repo.set_head(&("refs/heads/".to_owned() + branch_name));
}

To checkout a commit:

use git2::*;

fn main() {
    let repo = Repository::clone(
        "https://github.com/rossmacarthur/dotfiles",
        "dotfiles"
    ).expect("failed to clone repository");

    let my_oid_str = "9411953f92d100f767e6de6325b17afae5231779";

    let oid = Oid::from_str(my_oid_str).unwrap();
    let commit = repo.find_commit(oid).unwrap();

    let branch = repo.branch(
        my_oid_str,
        &commit,
        false,
    );

    let obj = repo.revparse_single(&("refs/heads/".to_owned() + my_oid_str)).unwrap(); 

    repo.checkout_tree(
        &obj,
        None,
    );

    repo.set_head(&("refs/heads/".to_owned() + my_oid_str));

}

To checkout a tag try something like this:

use git2::*;

fn main() {
    // No relation to the example project below.
    // It looks interesting and it has tags!
    let repo = Repository::clone(
        "https://github.com/narke/colorForth.git",
        "colorforth"
    ).expect("failed to clone repository");

    let tag_name = "v2012";

    let references = repo.references().unwrap();

    for reference in references {
        let _reference = reference.unwrap();

        if _reference.is_tag() == true {
            let tag = _reference.peel_to_tag().unwrap();
            if tag.name().unwrap() == tag_name {
                let target_oid = tag.target().unwrap().id();
                let commit = repo.find_commit(target_oid).unwrap();

                let branch = repo.branch(
                    tag_name,
                    &commit,
                    false,
                );

                let obj = repo.revparse_single(&("refs/heads/".to_owned() + tag_name)).unwrap();

                repo.checkout_tree(
                    &obj,
                    None,
                );

                repo.set_head(&("refs/heads/".to_owned() + tag_name)); 
            }
        }

    }
}

I bet there is generally a better way but the question has been unanswered for months and this is how I figured it out moments ago.

like image 16
szignal Avatar answered Nov 17 '22 11:11

szignal