|
1 | | -use git2::{Branch, BranchType, Branches, Commit, Oid, PushOptions, RemoteCallbacks, Repository}; |
| 1 | +use git2::{ |
| 2 | + Branch, BranchType, Branches, Commit, Cred, Oid, PushOptions, RemoteCallbacks, Repository, |
| 3 | +}; |
2 | 4 | use std::path::{Path, PathBuf}; |
3 | 5 |
|
4 | 6 | /// Get repo from path |
@@ -115,17 +117,31 @@ pub fn commit(repo: &mut Repository, msg: &str) -> Result<(), git2::Error> { |
115 | 117 | } |
116 | 118 |
|
117 | 119 | /// Push changes to remote |
118 | | -pub fn push(repo: &Repository) -> Result<(), git2::Error> { |
| 120 | +pub fn push(repo: &Repository, username: &str) -> Result<(), git2::Error> { |
119 | 121 | // Setup remote |
120 | 122 | let mut opts = PushOptions::default(); |
121 | | - let callbacks = RemoteCallbacks::new(); |
| 123 | + let mut callbacks = RemoteCallbacks::new(); |
| 124 | + |
| 125 | + // Configure authentication credentials |
| 126 | + callbacks.credentials(|_url, username_from_url, _allowed_types| { |
| 127 | + Cred::ssh_key_from_agent(username_from_url.unwrap_or(username)) |
| 128 | + }); |
| 129 | + |
| 130 | + // Set the callbacks for the remote |
122 | 131 | opts.remote_callbacks(callbacks); |
123 | 132 |
|
124 | 133 | // Assume the remote's name is "origin" |
125 | 134 | let mut remote = repo.find_remote("origin")?; |
126 | 135 |
|
127 | | - // Push to remote |
128 | | - remote.push::<&str>(&[], Some(&mut opts))?; |
| 136 | + // Push changes of the current checkout branch |
| 137 | + let current_branch = get_branch_name(repo).expect("Error getting branch"); |
| 138 | + let refspec = format!( |
| 139 | + "refs/heads/{}:refs/heads/{}", |
| 140 | + current_branch, current_branch |
| 141 | + ); |
| 142 | + |
| 143 | + // Push changes based on settings |
| 144 | + remote.push(&[refspec], Some(&mut opts))?; |
129 | 145 |
|
130 | 146 | Ok(()) |
131 | 147 | } |
|
0 commit comments