Skip to content

feat: support https push #353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion asyncgit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ rayon-core = "1.8"
crossbeam-channel = "0.5"
log = "0.4"
thiserror = "1.0"
url = "2.1.1"

[dev-dependencies]
tempfile = "3.1"
invalidstring = { path = "../invalidstring", version = "0.1" }
invalidstring = { path = "../invalidstring", version = "0.1" }
serial_test = "0.5.0"
3 changes: 3 additions & 0 deletions asyncgit/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ pub enum Error {
#[error("git: no head found")]
NoHead,

#[error("git: remote url not found")]
UnknownRemote,

#[error("io error:{0}")]
Io(#[from] std::io::Error),

Expand Down
4 changes: 4 additions & 0 deletions asyncgit/src/push.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::sync::cred::BasicAuthCredential;
use crate::{
error::{Error, Result},
sync, AsyncNotification, CWD,
Expand Down Expand Up @@ -88,6 +89,8 @@ pub struct PushRequest {
pub remote: String,
///
pub branch: String,
///
pub basic_credential: Option<BasicAuthCredential>,
}

#[derive(Default, Clone, Debug)]
Expand Down Expand Up @@ -161,6 +164,7 @@ impl AsyncPush {
CWD,
params.remote.as_str(),
params.branch.as_str(),
params.basic_credential,
progress_sender.clone(),
);

Expand Down
257 changes: 257 additions & 0 deletions asyncgit/src/sync/cred.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
//! credentials git helper

use git2::{Config, CredentialHelper};

use crate::error::{Error, Result};
use crate::CWD;

/// basic Authentication Credentials
#[derive(Debug, Clone, Default, PartialEq)]
pub struct BasicAuthCredential {
///
pub username: Option<String>,
///
pub password: Option<String>,
}

impl BasicAuthCredential {
///
pub fn is_complete(&self) -> bool {
self.username.is_some() && self.password.is_some()
}
///
pub fn new(
username: Option<String>,
password: Option<String>,
) -> Self {
BasicAuthCredential { username, password }
}
}

/// know if username and password are needed for this url
pub fn need_username_password(remote: &str) -> Result<bool> {
let repo = crate::sync::utils::repo(CWD)?;
let url = repo
.find_remote(remote)?
.url()
.ok_or(Error::UnknownRemote)?
.to_owned();
let is_http = url.starts_with("http");
Ok(is_http)
}

/// extract username and password
pub fn extract_username_password(
remote: &str,
) -> Result<BasicAuthCredential> {
let repo = crate::sync::utils::repo(CWD)?;
let url = repo
.find_remote(remote)?
.url()
.ok_or(Error::UnknownRemote)?
.to_owned();
let mut helper = CredentialHelper::new(&url);

if let Ok(config) = Config::open_default() {
helper.config(&config);
}
Ok(match helper.execute() {
Some((username, password)) => {
BasicAuthCredential::new(Some(username), Some(password))
}
None => extract_cred_from_url(&url),
})
}

/// extract credentials from url
pub fn extract_cred_from_url(url: &str) -> BasicAuthCredential {
if let Ok(url) = url::Url::parse(url) {
BasicAuthCredential::new(
if url.username() == "" {
None
} else {
Some(url.username().to_owned())
},
url.password().map(|pwd| pwd.to_owned()),
)
} else {
BasicAuthCredential::new(None, None)
}
}

#[cfg(test)]
mod tests {
use crate::sync::cred::{
extract_cred_from_url, extract_username_password,
need_username_password, BasicAuthCredential,
};
use crate::sync::tests::repo_init;
use crate::sync::DEFAULT_REMOTE_NAME;
use serial_test::serial;
use std::env;

#[test]
fn test_credential_complete() {
assert_eq!(
BasicAuthCredential::new(
Some("username".to_owned()),
Some("password".to_owned())
)
.is_complete(),
true
);
}

#[test]
fn test_credential_not_complete() {
assert_eq!(
BasicAuthCredential::new(
None,
Some("password".to_owned())
)
.is_complete(),
false
);
assert_eq!(
BasicAuthCredential::new(
Some("username".to_owned()),
None
)
.is_complete(),
false
);
assert_eq!(
BasicAuthCredential::new(None, None).is_complete(),
false
);
}

#[test]
fn test_extract_username_from_url() {
assert_eq!(
extract_cred_from_url("https://[email protected]"),
BasicAuthCredential::new(Some("user".to_owned()), None)
);
}

#[test]
fn test_extract_username_password_from_url() {
assert_eq!(
extract_cred_from_url("https://user:[email protected]"),
BasicAuthCredential::new(
Some("user".to_owned()),
Some("pwd".to_owned())
)
);
}

#[test]
fn test_extract_nothing_from_url() {
assert_eq!(
extract_cred_from_url("https://github.com"),
BasicAuthCredential::new(None, None)
);
}

#[test]
#[serial]
fn test_need_username_password_if_https() {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();
repo.remote(DEFAULT_REMOTE_NAME, "http://[email protected]")
.unwrap();

assert_eq!(
need_username_password(DEFAULT_REMOTE_NAME).unwrap(),
true
);
}

#[test]
#[serial]
fn test_dont_need_username_password_if_ssh() {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();
repo.remote(DEFAULT_REMOTE_NAME, "[email protected]:user/repo")
.unwrap();

assert_eq!(
need_username_password(DEFAULT_REMOTE_NAME).unwrap(),
false
);
}

#[test]
#[serial]
#[should_panic]
fn test_error_if_no_remote_when_trying_to_retrieve_if_need_username_password(
) {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();

need_username_password(DEFAULT_REMOTE_NAME).unwrap();
}

#[test]
#[serial]
fn test_extract_username_password_from_repo() {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();
repo.remote(
DEFAULT_REMOTE_NAME,
"http://user:[email protected]",
)
.unwrap();

assert_eq!(
extract_username_password(DEFAULT_REMOTE_NAME).unwrap(),
BasicAuthCredential::new(
Some("user".to_owned()),
Some("pass".to_owned())
)
);
}

#[test]
#[serial]
fn test_extract_username_from_repo() {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();
repo.remote(DEFAULT_REMOTE_NAME, "http://[email protected]")
.unwrap();

assert_eq!(
extract_username_password(DEFAULT_REMOTE_NAME).unwrap(),
BasicAuthCredential::new(Some("user".to_owned()), None)
);
}

#[test]
#[serial]
#[should_panic]
fn test_error_if_no_remote_when_trying_to_extract_username_password(
) {
let (_td, repo) = repo_init().unwrap();
let root = repo.path().parent().unwrap();
let repo_path = root.as_os_str().to_str().unwrap();

env::set_current_dir(repo_path).unwrap();

extract_username_password(DEFAULT_REMOTE_NAME).unwrap();
}
}
2 changes: 2 additions & 0 deletions asyncgit/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod commit;
mod commit_details;
mod commit_files;
mod commits_info;
pub mod cred;
pub mod diff;
mod hooks;
mod hunks;
Expand Down Expand Up @@ -35,6 +36,7 @@ pub use ignore::add_to_ignore;
pub use logwalker::LogWalker;
pub use remotes::{
fetch_origin, get_remotes, push, ProgressNotification,
DEFAULT_REMOTE_NAME,
};
pub use reset::{reset_stage, reset_workdir};
pub use stash::{get_stashes, stash_apply, stash_drop, stash_save};
Expand Down
Loading