rust-lang / git2-rs

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

How to resolve `HEAD` on an empty repository? #1012

Closed eirnym closed 5 months ago

eirnym commented 5 months ago

Hi,

I have an issue with new repositories and git2::Repository::head() method.

HEAD reference is resolving properly in an active repository and I get all information I need.

I have a brand new repository with no commits pointing to a reference refs/heads/main has been created by default and command line command git symbolic-ref HEAD shows me refs/heads/main, which is my goal to get using this library as well.

I expect to obtain a symbolic reference name even there's no commits in a repository.

I've tried:


let head = repo.head()? // results in an error
let ref = repo.find_reference("HEAD")?; // ref.name() is just Some("HEAD")
let resolved = ref.resolve()?;  // results in an error

Error I get looks like Git(Error { code: -3, klass: 4, message: "reference 'refs/heads/main' not found" }). This is true, as it resolves to no commits.

Currently I use 0.18.1

How could I do this with this library?

eirnym commented 5 months ago

I found a solution after reading help more carefully. I need to call reference.symbolic_target() to get the symbolic target.