Skip to main content

workon/
get_remote_callbacks.rs

1use git2::{Config, RemoteCallbacks};
2use git2_credentials::CredentialHandler;
3
4use crate::error::Result;
5use crate::ssh_config::apply_identity_agent;
6
7/// Build [`git2::RemoteCallbacks`] that handle credential prompts via the system
8/// credential store (SSH keys, keychain, etc.).
9///
10/// Uses [`git2_credentials::CredentialHandler`] which respects `~/.gitconfig`
11/// credential settings and SSH agent.
12///
13/// If `url` is provided, `~/.ssh/config` is consulted for an `IdentityAgent`
14/// directive matching the URL's host. When found, `SSH_AUTH_SOCK` is updated
15/// so that libgit2 connects to the configured agent (e.g. 1Password SSH agent).
16pub fn get_remote_callbacks<'a>(url: Option<&str>) -> Result<RemoteCallbacks<'a>> {
17    if let Some(url) = url {
18        apply_identity_agent(url);
19    }
20
21    let mut callbacks = RemoteCallbacks::new();
22    let git_config = Config::open_default()?;
23    let mut credential_handler = CredentialHandler::new(git_config);
24
25    callbacks.credentials(move |url, username, allowed| {
26        credential_handler.try_next_credential(url, username, allowed)
27    });
28    Ok(callbacks)
29}