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.

Support loading Git commit templates when remote (#55490)

Om Chillure775e51f95cdf
diff --git a/crates/collab/src/rpc.rs b/crates/collab/src/rpc.rs
index 5c30a49afab..4def99e182f 100644
--- a/crates/collab/src/rpc.rs
+++ b/crates/collab/src/rpc.rs
@@ -519,7 +519,8 @@ impl Server {
.add_request_handler(forward_mutating_project_request::<proto::CheckForPushedCommits>)
.add_request_handler(forward_mutating_project_request::<proto::ToggleLspLogs>)
.add_message_handler(broadcast_project_message_from_host::<proto::LanguageServerLog>)
- .add_request_handler(forward_project_search_chunk);
+ .add_request_handler(forward_project_search_chunk)
+ .add_request_handler(forward_read_only_project_request::<proto::LoadCommitTemplate>);
Arc::new(server)
}
diff --git a/crates/collab/tests/integration/git_tests.rs b/crates/collab/tests/integration/git_tests.rs
index d5f71085d5d..1397bd271b1 100644
--- a/crates/collab/tests/integration/git_tests.rs
+++ b/crates/collab/tests/integration/git_tests.rs
@@ -8,7 +8,9 @@ use client::RECEIVE_TIMEOUT;
use collections::HashMap;
use git::{
Oid,
- repository::{CommitData, InitialGraphCommitData, RepoPath, Worktree as GitWorktree},
+ repository::{
+ CommitData, GitCommitTemplate, InitialGraphCommitData, RepoPath, Worktree as GitWorktree,
+ },
status::{DiffStat, FileStatus, StatusCode, TrackedStatus},
};
use git_ui::git_graph::GitGraph;
@@ -1403,3 +1405,60 @@ async fn test_diff_stat_sync_between_host_and_downstream_client(
"remote diff stats should be restored from the database after rejoining the call"
);
}
+
+#[gpui::test]
+async fn test_load_commit_template_over_collab(
+ executor: BackgroundExecutor,
+ cx_a: &mut TestAppContext,
+ cx_b: &mut TestAppContext,
+) {
+ let mut server = TestServer::start(executor.clone()).await;
+ let client_a = server.create_client(cx_a, "user_a").await;
+ let client_b = server.create_client(cx_b, "user_b").await;
+
+ server
+ .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
+ .await;
+ let active_call_a = cx_a.read(ActiveCall::global);
+
+ client_a
+ .fs()
+ .insert_tree(
+ path!("/project"),
+ json!({
+ ".git": {},
+ "README.md": "# Project's README"
+ }),
+ )
+ .await;
+
+ client_a
+ .fs()
+ .with_git_state(Path::new(path!("/project/.git")), false, |state| {
+ state.commit_template = Some(GitCommitTemplate {
+ template: "feat: add awesome feature".to_string(),
+ })
+ })
+ .expect("Should update git state");
+
+ let (project_a, _) = client_a.build_local_project(path!("/project"), cx_a).await;
+ let project_id = active_call_a
+ .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
+ .await
+ .unwrap();
+
+ let project_b = client_b.join_remote_project(project_id, cx_b).await;
+ executor.run_until_parked();
+
+ let repository_b = project_b.update(cx_b, |project, cx| project.active_repository(cx).unwrap());
+ let commit_template = repository_b
+ .update(cx_b, |repository, _cx| {
+ repository.load_commit_template_text()
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ .expect("Guest should be able to load the host's commit template");
+
+ assert_eq!(commit_template.template, "feat: add awesome feature");
+}
diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rs
index 02610f0fdb5..e2f72b9cdbf 100644
--- a/crates/fs/src/fake_git_repo.rs
+++ b/crates/fs/src/fake_git_repo.rs
@@ -79,6 +79,7 @@ pub struct FakeGitRepositoryState {
pub graph_commits: Vec<Arc<InitialGraphCommitData>>,
pub commit_data: HashMap<Oid, FakeCommitDataEntry>,
pub stash_entries: GitStash,
+ pub commit_template: Option<GitCommitTemplate>,
}
impl FakeGitRepositoryState {
@@ -104,6 +105,7 @@ impl FakeGitRepositoryState {
commit_data: Default::default(),
commit_history: Vec::new(),
stash_entries: Default::default(),
+ commit_template: None,
}
}
}
@@ -163,7 +165,7 @@ impl FakeGitRepository {
impl GitRepository for FakeGitRepository {
fn load_commit_template(&self) -> BoxFuture<'_, Result<Option<GitCommitTemplate>>> {
- async { Ok(None) }.boxed()
+ self.with_state_async(false, |state| Ok(state.commit_template.clone()))
}
fn load_blob_content(&self, oid: git::Oid) -> BoxFuture<'_, Result<String>> {
diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs
index 7db03873391..af402961899 100644
--- a/crates/git_ui/src/git_panel.rs
+++ b/crates/git_ui/src/git_panel.rs
@@ -4400,44 +4400,12 @@ impl GitPanel {
self.reopen_commit_buffer_task = cx.spawn_in(window, async move |git_panel, cx| {
let result = async {
+ // Set up the buffer before awaiting the commit template as the
+ // request may never resolve (for example, a collab host that
+ // doesn't know about `LoadCommitTemplate`) and must not block the
+ // commit editor from attaching to the shared buffer.
let buffer = load_buffer.await?;
- let template = load_template.await?;
-
- git_panel.update_in(cx, move |git_panel, window, cx| {
- git_panel.commit_template = template;
- let restored_commit_message = git_panel
- .pending_commit_message_restores
- .remove(&active_repository_abs_path);
- if let Some(restored_commit_message) = restored_commit_message {
- git_panel.amend_pending = restored_commit_message.amend_pending;
- git_panel.original_commit_message =
- restored_commit_message.original_message;
- cx.notify();
- if let Some(message) = restored_commit_message.message
- && buffer.read(cx).text().trim().is_empty()
- {
- buffer.update(cx, |buffer, cx| {
- let start = buffer.anchor_before(0);
- let end = buffer.anchor_after(buffer.len());
- buffer.edit([(start..end, message)], None, cx);
- });
- }
- }
- if buffer.read(cx).text().trim().is_empty() {
- let template_text = git_panel
- .commit_template
- .as_ref()
- .map(|t| t.template.clone())
- .unwrap_or_default();
- if !template_text.is_empty() {
- buffer.update(cx, |buffer, cx| {
- let start = buffer.anchor_before(0);
- let end = buffer.anchor_after(buffer.len());
- buffer.edit([(start..end, template_text)], None, cx);
- });
- }
- }
-
+ git_panel.update_in(cx, |git_panel, window, cx| {
if git_panel
.commit_editor
.read(cx)
@@ -4459,16 +4427,62 @@ impl GitPanel {
});
}
+ // Create subscription such that, any edit on the commit
+ // editor's buffer will be serialized and saved to the database
+ // in order to be able to restore it in case there's a
+ // disconnect.
git_panel._commit_message_buffer_subscription =
- Some(cx.subscribe(&buffer, |this, _, event, cx| {
+ Some(cx.subscribe(&buffer, |git_panel, _, event, cx| {
if matches!(event, BufferEvent::Edited { .. }) {
- this.serialize(cx);
+ git_panel.serialize(cx);
}
}));
})?;
+
+ // Check whether there's a pending commit message for this
+ // repository and, if that's the case, update the buffer's
+ // text.
+ git_panel.update(cx, |git_panel, cx| {
+ if let Some(restored_commit_message) = git_panel
+ .pending_commit_message_restores
+ .remove(&active_repository_abs_path)
+ {
+ git_panel.amend_pending = restored_commit_message.amend_pending;
+ git_panel.original_commit_message =
+ restored_commit_message.original_message;
+ cx.notify();
+
+ if let Some(message) = restored_commit_message.message
+ && buffer.read(cx).text().trim().is_empty()
+ {
+ buffer.update(cx, |buffer, cx| {
+ buffer.set_text(message, cx);
+ });
+ }
+ }
+ })?;
+
+ // Only apply the template if it's non-empty and the buffer has no
+ // content, so we never override a commit message that was already
+ // in progress.
+ let commit_template = load_template.await?;
+ git_panel.update(cx, |git_panel, cx| {
+ git_panel.commit_template = commit_template;
+
+ if let Some(commit_template) = git_panel.commit_template.as_ref()
+ && !commit_template.template.is_empty()
+ && buffer.read(cx).text().trim().is_empty()
+ {
+ buffer.update(cx, |buffer, cx| {
+ buffer.set_text(commit_template.template.clone(), cx);
+ });
+ }
+ })?;
+
anyhow::Ok(())
}
.await;
+
result.log_err();
});
}
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index f96df289484..f7c2320d1fa 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -810,6 +810,7 @@ impl GitStore {
client.add_entity_request_handler(Self::handle_git_diff);
client.add_entity_request_handler(Self::handle_tree_diff);
client.add_entity_request_handler(Self::handle_get_blob_content);
+ client.add_entity_request_handler(Self::handle_load_commit_template);
client.add_entity_request_handler(Self::handle_open_unstaged_diff);
client.add_entity_request_handler(Self::handle_open_uncommitted_diff);
client.add_entity_message_handler(Self::handle_update_diff_bases);
@@ -4124,6 +4125,24 @@ impl GitStore {
Ok(proto::GetBlobContentResponse { content })
}
+ async fn handle_load_commit_template(
+ this: Entity<Self>,
+ request: TypedEnvelope<proto::LoadCommitTemplate>,
+ mut cx: AsyncApp,
+ ) -> Result<proto::LoadCommitTemplateResponse> {
+ let repository_id = RepositoryId(request.payload.repository_id);
+ let rx = this
+ .update(&mut cx, |this, cx| {
+ let repository = this.repositories().get(&repository_id)?;
+ Some(repository.update(cx, |repo, _| repo.load_commit_template_text()))
+ })
+ .context("missing repository")?;
+ let template = rx.await??;
+ Ok(proto::LoadCommitTemplateResponse {
+ template: template.map(|t| t.template),
+ })
+ }
+
async fn handle_open_unstaged_diff(
this: Entity<Self>,
request: TypedEnvelope<proto::OpenUnstagedDiff>,
@@ -9169,6 +9188,7 @@ impl Repository {
pub fn load_commit_template_text(
&mut self,
) -> oneshot::Receiver<Result<Option<GitCommitTemplate>>> {
+ let repository_id = self.snapshot.id;
self.send_job(
"load_commit_template_text",
None,
@@ -9177,7 +9197,17 @@ impl Repository {
RepositoryState::Local(LocalRepositoryState { backend, .. }) => {
backend.load_commit_template().await
}
- RepositoryState::Remote(_) => Ok(None),
+ RepositoryState::Remote(RemoteRepositoryState { client, project_id }) => {
+ let response = client
+ .request(proto::LoadCommitTemplate {
+ project_id: project_id.to_proto(),
+ repository_id: repository_id.0,
+ })
+ .await?;
+ Ok(response
+ .template
+ .map(|template| GitCommitTemplate { template }))
+ }
}
},
)
diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.proto
index 8570f86d9f3..64687374c61 100644
--- a/crates/proto/proto/git.proto
+++ b/crates/proto/proto/git.proto
@@ -574,6 +574,15 @@ message GetBlobContentResponse {
string content = 1;
}
+message LoadCommitTemplate {
+ uint64 project_id = 1;
+ uint64 repository_id = 2;
+}
+
+message LoadCommitTemplateResponse {
+ optional string template = 1;
+}
+
message GitGetWorktrees {
uint64 project_id = 1;
uint64 repository_id = 2;
diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.proto
index ae02f34190a..e4011bcf97f 100644
--- a/crates/proto/proto/zed.proto
+++ b/crates/proto/proto/zed.proto
@@ -499,7 +499,9 @@ message Envelope {
RestoreProjectEntry restore_project_entry = 468;
RestoreProjectEntryResponse restore_project_entry_response = 469;
GitAddPathToGitignore git_add_path_to_gitignore = 470;
- GitAddPathToGitInfoExclude git_add_path_to_git_info_exclude = 471; // current max
+ GitAddPathToGitInfoExclude git_add_path_to_git_info_exclude = 471;
+ LoadCommitTemplate load_commit_template = 472;
+ LoadCommitTemplateResponse load_commit_template_response = 473; // current max
}
reserved 87 to 88;
diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rs
index f9ab3789ada..47dbb972e4b 100644
--- a/crates/proto/src/proto.rs
+++ b/crates/proto/src/proto.rs
@@ -354,6 +354,8 @@ messages!(
(GetTreeDiffResponse, Background),
(GetBlobContent, Background),
(GetBlobContentResponse, Background),
+ (LoadCommitTemplate, Background),
+ (LoadCommitTemplateResponse, Background),
(GitClone, Background),
(GitCloneResponse, Background),
(ToggleLspLogs, Background),
@@ -593,6 +595,7 @@ request_messages!(
(PullWorkspaceDiagnostics, Ack),
(GetDefaultBranch, GetDefaultBranchResponse),
(GetBlobContent, GetBlobContentResponse),
+ (LoadCommitTemplate, LoadCommitTemplateResponse),
(GetTreeDiff, GetTreeDiffResponse),
(GitClone, GitCloneResponse),
(ToggleLspLogs, Ack),
@@ -812,6 +815,7 @@ entity_messages!(
GetDefaultBranch,
GetTreeDiff,
GetBlobContent,
+ LoadCommitTemplate,
GitClone,
GetAgentServerCommand,
GetContextServerCommand,
diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rs
index 163bdbe8978..16633b156d5 100644
--- a/crates/remote_server/src/remote_editing_tests.rs
+++ b/crates/remote_server/src/remote_editing_tests.rs
@@ -22,7 +22,7 @@ use extension::ExtensionHostProxy;
use fs::{FakeFs, Fs};
use git::{
Oid,
- repository::{CommitData, RepoPath, Worktree as GitWorktree},
+ repository::{CommitData, GitCommitTemplate, RepoPath, Worktree as GitWorktree},
};
use gpui::{AppContext as _, Entity, SharedString, TestAppContext, UpdateGlobal, VisualContext};
use http_client::{BlockedHttpClient, FakeHttpClient};
@@ -3613,6 +3613,48 @@ async fn test_remote_restore_unstaged_hunk_clears_diff(
});
}
+#[gpui::test]
+async fn test_remote_load_commit_template(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {
+ let fs = FakeFs::new(server_cx.executor());
+
+ fs.insert_tree(
+ path!("/root"),
+ json!({
+ "project": {
+ ".git": {},
+ "README.md": "# Project's README"
+ }
+ }),
+ )
+ .await;
+
+ fs.with_git_state(Path::new(path!("/root/project/.git")), false, |state| {
+ state.commit_template = Some(GitCommitTemplate {
+ template: "chore: commit template".to_string(),
+ })
+ })
+ .expect("Should successfully update repository state");
+
+ let (project, _) = init_test(&fs, cx, server_cx).await;
+ project
+ .update(cx, |project, cx| {
+ project.find_or_create_worktree(path!("/root/project"), true, cx)
+ })
+ .await
+ .unwrap();
+ cx.run_until_parked();
+
+ let repository = project.update(cx, |project, cx| project.active_repository(cx).unwrap());
+ let commit_template = repository
+ .update(cx, |repository, _| repository.load_commit_template_text())
+ .await
+ .unwrap()
+ .unwrap()
+ .expect("Loading commit template in remote should work");
+
+ assert_eq!(commit_template.template, "chore: commit template");
+}
+
#[gpui::test]
async fn test_remote_delete_project_entry_with_trash(
cx: &mut TestAppContext,