Push the current branch to the remote.
(&self, git_repo: &GitRepository)
| 249 | |
| 250 | /// Push the current branch to the remote. |
| 251 | fn push_to_remote(&self, git_repo: &GitRepository) -> CliResult<()> { |
| 252 | let head = git_repo.head().map_err(|e| CliError::GitError { |
| 253 | message: format!("Failed to get HEAD: {}", e), |
| 254 | })?; |
| 255 | let branch_name = head.shorthand().unwrap_or("HEAD"); |
| 256 | let refspec = format!("refs/heads/{}:refs/heads/{}", branch_name, branch_name); |
| 257 | |
| 258 | let mut remote = git_repo |
| 259 | .find_remote(&self.remote) |
| 260 | .map_err(|e| CliError::GitError { |
| 261 | message: format!("Remote '{}' not found: {}", self.remote, e), |
| 262 | })?; |
| 263 | |
| 264 | let mut push_options = git2::PushOptions::new(); |
| 265 | let mut callbacks = git2::RemoteCallbacks::new(); |
| 266 | callbacks.credentials(|_url, username_from_url, allowed_types| { |
| 267 | if allowed_types.contains(git2::CredentialType::SSH_KEY) { |
| 268 | let user = username_from_url.unwrap_or("git"); |
| 269 | git2::Cred::ssh_key_from_agent(user) |
| 270 | } else if allowed_types.contains(git2::CredentialType::DEFAULT) { |
| 271 | git2::Cred::default() |
| 272 | } else { |
| 273 | Err(git2::Error::from_str("no suitable credential type")) |
| 274 | } |
| 275 | }); |
| 276 | push_options.remote_callbacks(callbacks); |
| 277 | |
| 278 | remote |
| 279 | .push(&[&refspec], Some(&mut push_options)) |
| 280 | .map_err(|e| CliError::GitError { |
| 281 | message: format!("Push failed: {}", e), |
| 282 | })?; |
| 283 | |
| 284 | Ok(()) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[cfg(test)] |