davidB / git2_credentials

Provide credentials function to used with git2::RemoteCallbacks.credentials
Apache License 2.0
21 stars 4 forks source link

unable to use to push commits #49

Closed Lunarequest closed 7 months ago

Lunarequest commented 7 months ago

I tried to use this for the callbacks for pushing commits,

use anyhow::{Context, Result};
use git2::{Config, PushOptions, RemoteCallbacks, Repository};
use git2_credentials::CredentialHandler;

pub fn git_push(repo: &Repository) -> Result<()> {
    let head = repo.head()?.resolve()?;
    let config = Config::open_default().context("failed to open gitconfig")?;
    let mut cred_handler = CredentialHandler::new(config);
    let mut callbacks = RemoteCallbacks::new();

    callbacks.credentials(move |url, username, allowed_types| {
        cred_handler.try_next_credential(url, username, allowed_types)
    });
    let mut remote = repo
        .find_remote("origin")
        .map_err(|_| git2::Error::from_str("failed to resolve remote origin"))?;

    let mut push_options = PushOptions::new();

    remote.push(
        &[&format!("refs/heads/{}", head.shorthand().unwrap())],
        Some(&mut push_options),
    )?;
    Ok(())
}

this should be simple enough to to push any commits that are present in the working tree in the current branch. However when ever you try and run this you get a authentication error as such Error: authentication required but no callback set; class=Ssh (23); code=Auth (-16) I'm quite perplexed since this should work just fine. If I've made a silly mistake please point me in the right direction

davidB commented 7 months ago

How did you solve the issue?

Lunarequest commented 7 months ago

i missed adding the handler to the push_options