rust-lang / git2-rs

libgit2 bindings for Rust
https://docs.rs/git2
Apache License 2.0
1.65k stars 381 forks source link

Is there a way to create and checkout a branch? #959

Closed on3iro closed 1 year ago

on3iro commented 1 year ago

Hi,

I just recently stumbled over this great lib and am making my first steps in using it. The task I want to achieve is seemingly simple, but I can't quite get it to work correctly:

I would like to create a branch an check it out afterwards.

What I have so far is this:

    let repo = match Repository::open(std::env::current_dir().unwrap()) {
        Ok(repo) => repo,
        Err(err) => {
            println!("Could not open git repository: {}", err);
            std::process::exit(1);
        }
    };

    let branch = repo
        .branch(
            &new_version,
            &repo.head().unwrap().peel_to_commit().unwrap(),
            false,
        )
        .unwrap();

    repo.checkout_tree(branch.get().peel_to_tree().unwrap().as_object(), None)
        .unwrap();

Creating the branch from HEAD works as expected, however I can't figure out how to switch to the branch afterwards. My approach doesn't seem to do anything.

Any ideas on how I could achieve this?

Thanks in advance

on3iro commented 1 year ago

Ok I figured it out, I needed to set the repo head manually:

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