rust-lang / git2-rs

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

`branch_upstream_remote` says local branch does not exist when it does #1055

Closed ericswpark closed 1 month ago

ericswpark commented 1 month ago

I have a local git repository with the branch name master that tracks origin/master. I'm trying to write some Rust code to replicate git push && git push --tags.

Here is my code so far:

    let head_ref = repo.head()?.resolve()?;    
    let branch_name = head_ref.shorthand().ok_or_else(|| {
        Error::from_str("Failed to get branch name")
    })?;

    println!("Got branch name {branch_name}");    
    let upstream_remote = repo.branch_upstream_remote(branch_name)?;
    let remote_name = upstream_remote.as_str().ok_or_else(|| {
        Error::from_str("Failed to get remote name")
    })?;
    let mut remote = repo.find_remote(remote_name)?;

    let mut callbacks = RemoteCallbacks::new();
    callbacks.credentials(|_url, _username_from_url, _allowed_types| {
        git2::Cred::ssh_key_from_agent("git")
    });

    let mut push_options = PushOptions::new();
    push_options.remote_callbacks(callbacks);

    remote.push(&[&format!("refs/heads/{}", branch_name)], Some(&mut push_options))?;
    remote.push(&[&format!("refs/tags/{}", &version)], Some(&mut push_options))?;
    // ignore &versions decl -- it is a String that has the tag name in it

When I run the program, however, it panics at the let upstream_remote line, with the following output:

Got branch name master
thread 'main' panicked at src\main.rs:76:xx: Error { code: -1, klass: 3, message: "reference 'master' is not a local branch." }

The error message doesn't make sense, because the previous line of let branch_name got the currently active local branch. Am I calling branch_upstream_remote incorrectly?

ehuss commented 1 month ago

branch_upstream_remote needs it in the form refs/heads/master. Use head_ref.name() instead of shorthand().

ericswpark commented 1 month ago

Great, thank you! That worked. Can this be added to the documentation or is it out of scope? I can submit a PR if it isn't. Feel free to close the issue otherwise :)

ehuss commented 1 month ago

Yea, it could be added to the docs. There is some risk it will get out of sync with libgit2 if that behavior is ever changed, but it seems like a low risk.