From fcc22791e57d691e24545938318c10d982984b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hannes=20K=C3=B6rber?= Date: Thu, 23 Dec 2021 18:33:14 +0100 Subject: [PATCH] Refuse to push against non-pushable remotes (e.g. HTTPS for now) --- src/lib.rs | 16 +++++++++++++--- src/repo.rs | 9 +++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fa869f0..b6151af 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,7 +66,7 @@ pub fn path_as_string(path: &Path) -> String { path.to_path_buf().into_os_string().into_string().unwrap() } -fn env_home() -> PathBuf { +pub fn env_home() -> PathBuf { match std::env::var("HOME") { Ok(path) => Path::new(&path).to_path_buf(), Err(e) => { @@ -541,6 +541,13 @@ pub fn add_worktree( Err(_) => repo.create_branch(&branch_name, &checkout_commit)?, }; + fn push(remote: &mut repo::RemoteHandle, branch_name: &str, remote_branch_name: &str, repo: &repo::Repo) -> Result<(), String>{ + if !remote.is_pushable()? { + return Err(format!("Cannot push to non-pushable remote {}", remote.url())); + } + remote.push(branch_name, remote_branch_name, repo) + } + if !no_track { if let Some((remote_name, remote_branch_name)) = track { if remote_branch_exists { @@ -551,7 +558,7 @@ pub fn add_worktree( .map_err(|error| format!("Error getting remote {}: {}", remote_name, error))? .ok_or_else(|| format!("Remote {} not found", remote_name))?; - remote.push(&target_branch.name()?, remote_branch_name, &repo)?; + push(&mut remote, &target_branch.name()?, remote_branch_name, &repo)?; target_branch.set_upstream(remote_name, remote_branch_name)?; } @@ -572,7 +579,10 @@ pub fn add_worktree( .map_err(|error| format!("Error getting remote {}: {}", remote_name, error))? .ok_or_else(|| format!("Remote {} not found", remote_name))?; - remote.push(&target_branch.name()?, &remote_branch_name, &repo)?; + if !remote.is_pushable()? { + return Err(format!("Cannot push to non-pushable remote {}", remote.url())); + } + push(&mut remote, &target_branch.name()?, &remote_branch_name, &repo)?; target_branch.set_upstream(&remote_name, &remote_branch_name)?; } diff --git a/src/repo.rs b/src/repo.rs index 2f7f95b..682ae9d 100644 --- a/src/repo.rs +++ b/src/repo.rs @@ -980,12 +980,21 @@ impl RemoteHandle<'_> { .to_string() } + pub fn is_pushable(&self) -> Result { + let remote_type = detect_remote_type(self.0.url().expect("Remote name is not valid utf-8")).ok_or_else(|| String::from("Could not detect remote type"))?; + Ok(matches!(remote_type, RemoteType::Ssh | RemoteType::File)) + } + pub fn push( &mut self, local_branch_name: &str, remote_branch_name: &str, _repo: &Repo, ) -> Result<(), String> { + if !self.is_pushable()? { + return Err(String::from("Trying to push to a non-pushable remote")); + } + let mut callbacks = git2::RemoteCallbacks::new(); callbacks.push_update_reference(|_, status| { if let Some(message) = status {