workon/
get_remote_callbacks.rs1use auth_git2::GitAuthenticator;
2use git2::{Config, ConfigLevel, RemoteCallbacks, Repository};
3
4use crate::error::Result;
5use crate::ssh_config::apply_identity_agent;
6
7pub struct RemoteAuth {
15 authenticator: GitAuthenticator,
16 config: Config,
17}
18
19impl RemoteAuth {
20 pub fn callbacks(&self) -> RemoteCallbacks<'_> {
22 let mut callbacks = RemoteCallbacks::new();
23 callbacks.credentials(self.authenticator.credentials(&self.config));
24 callbacks
25 }
26}
27
28pub fn get_remote_callbacks(repo: &Repository, url: Option<&str>) -> Result<RemoteAuth> {
32 build_auth(repo.config()?, url)
33}
34
35pub fn get_remote_callbacks_default(url: Option<&str>) -> Result<RemoteAuth> {
39 build_auth(open_default_config_lenient()?, url)
40}
41
42fn build_auth(config: Config, url: Option<&str>) -> Result<RemoteAuth> {
43 if let Some(url) = url {
44 apply_identity_agent(url);
45 }
46 Ok(RemoteAuth {
47 authenticator: GitAuthenticator::default(),
48 config,
49 })
50}
51
52fn open_default_config_lenient() -> std::result::Result<Config, git2::Error> {
59 if let Ok(c) = Config::open_default() {
60 return Ok(c);
61 }
62 let mut config = Config::new()?;
63 if let Ok(path) = Config::find_global() {
64 let _ = config.add_file(&path, ConfigLevel::Global, false);
65 }
66 if let Ok(path) = Config::find_xdg() {
67 let _ = config.add_file(&path, ConfigLevel::XDG, false);
68 }
69 if let Ok(path) = Config::find_system() {
70 let _ = config.add_file(&path, ConfigLevel::System, false);
71 }
72 Ok(config)
73}