Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git: Fix operations timing out and commit-msg hook being skipped (#61185)

Smit Barmase2a983bca8616
diff --git a/crates/askpass/src/askpass.rs b/crates/askpass/src/askpass.rs
index dc5488ac117..af5d0d31adf 100644
--- a/crates/askpass/src/askpass.rs
+++ b/crates/askpass/src/askpass.rs
@@ -156,15 +156,25 @@ impl AskPassSession {
// The caller is responsible for examining the result of their own commands and cancelling this
// future when this is no longer needed. Note that this can only be called once, but due to the
// drop order this takes an &mut, so you can `drop()` it after you're done with the master process.
- pub async fn run(&mut self) -> AskPassResult {
- // This is the default timeout setting used by VSCode.
- let connection_timeout = Duration::from_secs(17);
+ //
+ // When `timeout` is provided, this resolves with `AskPassResult::Timedout` if no askpass prompt
+ // has been opened within that duration. This is intended for connection establishment (e.g.
+ // SSH), where "no prompt and no connection" indicates an unreachable host. Callers wrapping
+ // commands that may legitimately run for a long time without prompting (e.g. git) should pass
+ // `None` and rely on the command's own completion instead.
+ pub async fn run(&mut self, timeout: Option<Duration>) -> AskPassResult {
let askpass_opened_rx = self.askpass_opened_rx.take().expect("Only call run once");
let askpass_kill_master_rx = self
.askpass_kill_master_rx
.take()
.expect("Only call run once");
let executor = self.executor.clone();
+ let timer = async move {
+ match timeout {
+ Some(timeout) => executor.timer(timeout).await,
+ None => std::future::pending().await,
+ }
+ };
select_biased! {
_ = askpass_opened_rx.fuse() => {
@@ -173,7 +183,7 @@ impl AskPassSession {
AskPassResult::CancelledByUser
}
- _ = futures::FutureExt::fuse(executor.timer(connection_timeout)) => {
+ _ = futures::FutureExt::fuse(timer) => {
AskPassResult::Timedout
}
}
diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs
index 2f378f4adac..857a62f1b1d 100644
--- a/crates/git/src/repository.rs
+++ b/crates/git/src/repository.rs
@@ -1013,6 +1013,10 @@ pub trait GitRepository: Send + Sync {
env: Arc<HashMap<String, String>>,
) -> BoxFuture<'_, Result<()>>;
+ /// Only used to serve `proto::RunGitHook` requests from older remote clients;
+ /// new code lets `git commit` run hooks itself.
+ ///
+ /// TODO: remove together with `proto::RunGitHook` (see the deprecation note in git.proto).
fn run_hook(
&self,
hook: RunHook,
@@ -2532,7 +2536,6 @@ impl GitRepository for RealGitRepository {
cmd.envs(env.iter())
.arg(&message.to_string())
.arg("--cleanup=strip")
- .arg("--no-verify")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -3767,12 +3770,15 @@ async fn run_askpass_command(
git_process: util::command::Child,
) -> anyhow::Result<RemoteCommandOutput> {
select_biased! {
- result = ask_pass.run().fuse() => {
+ // Git can legitimately run long without prompting (e.g. large fetches,
+ // hooks), so completion is determined by the process itself.
+ result = ask_pass.run(None).fuse() => {
match result {
AskPassResult::CancelledByUser => {
Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
}
AskPassResult::Timedout => {
+ // Unreachable since no timeout is passed to run()
Err(anyhow!("Connecting to host timed out"))?
}
}
@@ -4936,6 +4942,87 @@ mod tests {
// );
}
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn test_commit_runs_git_hooks(cx: &mut TestAppContext) {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ disable_git_global_config();
+ cx.executor().allow_parking();
+
+ let repo_dir = tempfile::tempdir().unwrap();
+ git_init_repo(repo_dir.path());
+ let repo = RealGitRepository::new(
+ &repo_dir.path().join(".git"),
+ None,
+ Some("git".into()),
+ cx.executor(),
+ )
+ .unwrap();
+
+ let hooks_dir = repo_dir.path().join(".git").join("hooks");
+ fs::create_dir_all(&hooks_dir).unwrap();
+ let write_hook = |name: &str, contents: &str| {
+ let path = hooks_dir.join(name);
+ fs::write(&path, contents).unwrap();
+ fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ };
+
+ write_hook("pre-commit", "#!/bin/sh\nexit 1\n");
+
+ fs::write(repo_dir.path().join("file"), "one").unwrap();
+ repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
+ .await
+ .unwrap();
+
+ // Hooks must not run for untrusted repositories.
+ repo.commit(
+ "Commit in untrusted repo".into(),
+ None,
+ CommitOptions::default(),
+ AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
+ Arc::new(test_commit_envs()),
+ )
+ .await
+ .expect("failing pre-commit hook should be skipped in untrusted repos");
+
+ repo.set_trusted(true);
+
+ fs::write(repo_dir.path().join("file"), "two").unwrap();
+ repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
+ .await
+ .unwrap();
+
+ repo.commit(
+ "Commit blocked by hook".into(),
+ None,
+ CommitOptions::default(),
+ AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
+ Arc::new(test_commit_envs()),
+ )
+ .await
+ .expect_err("failing pre-commit hook should abort the commit");
+
+ write_hook("pre-commit", "#!/bin/sh\nexit 0\n");
+ write_hook(
+ "commit-msg",
+ "#!/bin/sh\necho 'rewritten by commit-msg hook' > \"$1\"\n",
+ );
+
+ repo.commit(
+ "Original message".into(),
+ None,
+ CommitOptions::default(),
+ AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
+ Arc::new(test_commit_envs()),
+ )
+ .await
+ .unwrap();
+
+ let message = git_command_output(repo_dir.path(), ["log", "-1", "--pretty=%B"]);
+ assert_eq!(message, "rewritten by commit-msg hook");
+ }
+
#[gpui::test]
async fn test_load_revisions(cx: &mut TestAppContext) {
disable_git_global_config();
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 26145b4a5c6..1b1f873516a 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -7367,6 +7367,11 @@ impl Repository {
})
}
+ // Kept for wire compatibility: older remote clients run the pre-commit hook explicitly
+ // via `proto::RunGitHook` before committing. New code lets `git commit` run hooks itself.
+ //
+ // TODO: remove together with `proto::RunGitHook` once all supported peers commit without
+ // sending it (see the deprecation note on the message in git.proto).
pub fn run_hook(&mut self, hook: RunHook, _cx: &mut App) -> oneshot::Receiver<Result<()>> {
let id = self.id;
self.send_job(
@@ -7401,20 +7406,16 @@ impl Repository {
name_and_email: Option<(SharedString, SharedString)>,
options: CommitOptions,
askpass: AskPassDelegate,
- cx: &mut App,
+ _cx: &mut App,
) -> oneshot::Receiver<Result<()>> {
let id = self.id;
let askpass_delegates = self.askpass_delegates.clone();
let askpass_id = util::post_inc(&mut self.latest_askpass_id);
- let rx = self.run_hook(RunHook::PreCommit, cx);
-
self.send_job(
"commit",
Some("git commit".into()),
move |git_repo, _cx| async move {
- rx.await??;
-
match git_repo {
RepositoryState::Local(LocalRepositoryState {
backend,
diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.proto
index 1592237cda8..33cbadc13ca 100644
--- a/crates/proto/proto/git.proto
+++ b/crates/proto/proto/git.proto
@@ -682,6 +682,12 @@ message GitWorktreeCreatedAtResponse {
optional Timestamp created_at = 1;
}
+// Deprecated: newer clients let `git commit` run hooks natively instead of
+// requesting them explicitly.
+//
+// TODO: once all supported peers commit without sending `RunGitHook`, remove
+// this message (and its handlers) and replace its tag in the Envelope payload
+// oneof with `reserved 399;` so the tag is never reused.
message RunGitHook {
enum GitHook {
PRE_COMMIT = 0;
diff --git a/crates/remote/src/transport/ssh.rs b/crates/remote/src/transport/ssh.rs
index 463037ccc05..9cd13a01882 100644
--- a/crates/remote/src/transport/ssh.rs
+++ b/crates/remote/src/transport/ssh.rs
@@ -26,7 +26,7 @@ use std::{
Arc,
atomic::{AtomicBool, Ordering},
},
- time::Instant,
+ time::{Duration, Instant},
};
use tempfile::TempDir;
use util::command::{Child, Stdio};
@@ -36,6 +36,9 @@ use util::{
shell::ShellKind,
};
+/// How long to wait for SSH to connect when no askpass prompt has opened.
+const SSH_CONNECTION_PROMPT_TIMEOUT: Duration = Duration::from_secs(17);
+
pub(crate) struct SshRemoteConnection {
socket: SshSocket,
master_process: Mutex<Option<MasterProcess>>,
@@ -654,7 +657,7 @@ impl SshRemoteConnection {
)?;
let result = select_biased! {
- result = askpass.run().fuse() => {
+ result = askpass.run(Some(SSH_CONNECTION_PROMPT_TIMEOUT)).fuse() => {
match result {
AskPassResult::CancelledByUser => {
master_process.as_mut().kill().ok();
@@ -712,7 +715,7 @@ impl SshRemoteConnection {
)?;
let result = select_biased! {
- result = askpass.run().fuse() => {
+ result = askpass.run(Some(SSH_CONNECTION_PROMPT_TIMEOUT)).fuse() => {
match result {
AskPassResult::CancelledByUser => {
master_process.as_mut().kill().ok();