Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project: Add remote support for adding paths to .gitignore (#56368)
Xiaobo Liuedeaf598c749
diff --git a/crates/collab/src/rpc.rs b/crates/collab/src/rpc.rsindex effe9fb2705..5c30a49afab 100644--- a/crates/collab/src/rpc.rs+++ b/crates/collab/src/rpc.rs@@ -482,8 +482,12 @@ impl Server {.add_request_handler(forward_read_only_project_request::<proto::GetRemotes>).add_request_handler(forward_read_only_project_request::<proto::GitShow>).add_request_handler(forward_read_only_project_request::<proto::LoadCommitDiff>)- .add_request_handler(forward_read_only_project_request::<proto::GitReset>)- .add_request_handler(forward_read_only_project_request::<proto::GitCheckoutFiles>)+ .add_request_handler(forward_mutating_project_request::<proto::GitReset>)+ .add_request_handler(forward_mutating_project_request::<proto::GitCheckoutFiles>)+ .add_request_handler(forward_mutating_project_request::<proto::GitAddPathToGitignore>)+ .add_request_handler(+ forward_mutating_project_request::<proto::GitAddPathToGitInfoExclude>,+ ).add_request_handler(forward_mutating_project_request::<proto::SetIndexText>).add_request_handler(forward_mutating_project_request::<proto::ToggleBreakpoint>).add_message_handler(broadcast_project_message_from_host::<proto::BreakpointsForFile>)diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rsindex ef6b7fe30e9..94ebed251c6 100644--- a/crates/project/src/git_store.rs+++ b/crates/project/src/git_store.rs@@ -801,6 +801,8 @@ impl GitStore {client.add_entity_request_handler(Self::handle_diff_checkpoints);client.add_entity_request_handler(Self::handle_load_commit_diff);client.add_entity_request_handler(Self::handle_checkout_files);+ client.add_entity_request_handler(Self::handle_add_path_to_gitignore);+ client.add_entity_request_handler(Self::handle_add_path_to_git_info_exclude);client.add_entity_request_handler(Self::handle_open_commit_message_buffer);client.add_entity_request_handler(Self::handle_set_index_text);client.add_entity_request_handler(Self::handle_askpass);@@ -3898,6 +3900,40 @@ impl GitStore {Ok(proto::Ack {})}+ async fn handle_add_path_to_gitignore(+ this: Entity<Self>,+ envelope: TypedEnvelope<proto::GitAddPathToGitignore>,+ mut cx: AsyncApp,+ ) -> Result<proto::Ack> {+ let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);+ let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;+ let repo_path = RepoPath::from_proto(&envelope.payload.path)?;++ repository_handle+ .update(&mut cx, |repository_handle, _| {+ repository_handle.add_path_to_gitignore(&repo_path, envelope.payload.is_dir)+ })+ .await??;+ Ok(proto::Ack {})+ }++ async fn handle_add_path_to_git_info_exclude(+ this: Entity<Self>,+ envelope: TypedEnvelope<proto::GitAddPathToGitInfoExclude>,+ mut cx: AsyncApp,+ ) -> Result<proto::Ack> {+ let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);+ let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;+ let repo_path = RepoPath::from_proto(&envelope.payload.path)?;++ repository_handle+ .update(&mut cx, |repository_handle, _| {+ repository_handle.add_path_to_git_info_exclude(&repo_path, envelope.payload.is_dir)+ })+ .await??;+ Ok(proto::Ack {})+ }+async fn handle_open_commit_message_buffer(this: Entity<Self>,envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,@@ -7269,8 +7305,10 @@ impl Repository {repo_path: &RepoPath,is_dir: bool,) -> oneshot::Receiver<Result<()>> {+ let id = self.id;let work_dir = self.snapshot.work_directory_abs_path.clone();let path_display = repo_path.as_ref().display(PathStyle::Unix);+ let path = repo_path.as_unix_str().to_owned();let file_path_str = if is_dir {format!("{}/", path_display)} else {@@ -7290,9 +7328,18 @@ impl Repository {).await}- RepositoryState::Remote(_) => Err(anyhow::anyhow!(- "Cannot modify .gitignore on remote repository"- )),+ RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {+ client+ .request(proto::GitAddPathToGitignore {+ project_id: project_id.0,+ repository_id: id.to_proto(),+ path,+ is_dir,+ })+ .await+ .context("sending add path to .gitignore request")?;+ Ok(())+ }}},)@@ -7303,8 +7350,10 @@ impl Repository {repo_path: &RepoPath,is_dir: bool,) -> oneshot::Receiver<Result<()>> {+ let id = self.id;let repository_dir = self.snapshot.repository_dir_abs_path.clone();let path_display = repo_path.as_ref().display(PathStyle::Unix);+ let path = repo_path.as_unix_str().to_owned();let file_path_str = if is_dir {format!("{}/", path_display)} else {@@ -7324,9 +7373,18 @@ impl Repository {).await}- RepositoryState::Remote(_) => Err(anyhow::anyhow!(- "Cannot modify .git/info/exclude on remote repository"- )),+ RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {+ client+ .request(proto::GitAddPathToGitInfoExclude {+ project_id: project_id.0,+ repository_id: id.to_proto(),+ path,+ is_dir,+ })+ .await+ .context("sending add path to .git/info/exclude request")?;+ Ok(())+ }}},)@@ -9930,7 +9988,20 @@ async fn append_pattern_to_ignore_file(file_path: PathBuf,pattern: String,) -> Result<()> {- let existing_content = fs.load(&file_path).await.unwrap_or_default();+ let existing_content = match fs.load(&file_path).await {+ Ok(content) => content,+ Err(error)+ if error+ .root_cause()+ .downcast_ref::<std::io::Error>()+ .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>+ {+ String::new()+ }+ Err(error) => {+ return Err(error).with_context(|| format!("loading {}", file_path.display()));+ }+ };if existing_content.lines().any(|line| line.trim() == pattern) {return Ok(());diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.protoindex bb8a8b89a0f..1d1e635cac1 100644--- a/crates/proto/proto/git.proto+++ b/crates/proto/proto/git.proto@@ -322,6 +322,22 @@ message GitCheckoutFiles {repeated string paths = 5;}+message GitAddPathToGitignore {+ uint64 project_id = 1;+ reserved 2;+ uint64 repository_id = 3;+ string path = 4;+ bool is_dir = 5;+}++message GitAddPathToGitInfoExclude {+ uint64 project_id = 1;+ reserved 2;+ uint64 repository_id = 3;+ string path = 4;+ bool is_dir = 5;+}+// Move to `git.proto` once collab's min version is >=0.171.0.message StatusEntry {string repo_path = 1;diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.protoindex c4a378ee12d..ae02f34190a 100644--- a/crates/proto/proto/zed.proto+++ b/crates/proto/proto/zed.proto@@ -497,7 +497,9 @@ message Envelope {TrashProjectEntry trash_project_entry = 466;TrashProjectEntryResponse trash_project_entry_response = 467;RestoreProjectEntry restore_project_entry = 468;- RestoreProjectEntryResponse restore_project_entry_response = 469; // current max+ RestoreProjectEntryResponse restore_project_entry_response = 469;+ GitAddPathToGitignore git_add_path_to_gitignore = 470;+ GitAddPathToGitInfoExclude git_add_path_to_git_info_exclude = 471; // current max}reserved 87 to 88;diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rsindex 20ed7b9d7cd..f9ab3789ada 100644--- a/crates/proto/src/proto.rs+++ b/crates/proto/src/proto.rs@@ -305,6 +305,8 @@ messages!((GitReset, Background),(GitDeleteBranch, Background),(GitCheckoutFiles, Background),+ (GitAddPathToGitignore, Background),+ (GitAddPathToGitInfoExclude, Background),(GitShow, Background),(GitCommitDetails, Background),(GitCreateCheckpoint, Background),@@ -568,6 +570,8 @@ request_messages!((GitReset, Ack),(GitDeleteBranch, Ack),(GitCheckoutFiles, Ack),+ (GitAddPathToGitignore, Ack),+ (GitAddPathToGitInfoExclude, Ack),(SetIndexText, Ack),(Push, RemoteMessageResponse),(Fetch, RemoteMessageResponse),@@ -779,6 +783,8 @@ entity_messages!(GitReset,GitDeleteBranch,GitCheckoutFiles,+ GitAddPathToGitignore,+ GitAddPathToGitInfoExclude,SetIndexText,ToggleLspLogs,GetDirectoryEnvironment,diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex 31fb7d14211..163bdbe8978 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, Worktree as GitWorktree},+ repository::{CommitData, RepoPath, Worktree as GitWorktree},};use gpui::{AppContext as _, Entity, SharedString, TestAppContext, UpdateGlobal, VisualContext};use http_client::{BlockedHttpClient, FakeHttpClient};@@ -2423,6 +2423,127 @@ async fn test_remote_archive_git_operations_are_supported(.expect("restore_archive_checkpoint should succeed for remote repository");}+#[gpui::test]+async fn test_add_path_to_gitignore_in_remote_repository(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+) {+ let fs = FakeFs::new(server_cx.executor());+ fs.insert_tree(+ "/project",+ json!({+ ".git": {},+ ".gitignore": "existing\n",+ "logs": {+ "app.log": ""+ },+ "tmp.txt": "",+ }),+ )+ .await;+ fs.set_branch_name(Path::new("/project/.git"), Some("main"));+ fs.set_head_for_repo(+ Path::new("/project/.git"),+ &[(".gitignore", "existing\n".into())],+ "head-sha",+ );++ let (project, _headless) = init_test(&fs, cx, server_cx).await;+ project+ .update(cx, |project, cx| {+ project.find_or_create_worktree(Path::new("/project"), true, cx)+ })+ .await+ .expect("should open remote worktree");+ cx.run_until_parked();++ let repository = project.read_with(cx, |project, cx| {+ project+ .active_repository(cx)+ .expect("remote project should have an active repository")+ });++ for (path, is_dir) in [("tmp.txt", false), ("logs", true), ("tmp.txt", false)] {+ let repo_path = RepoPath::new(path).expect("path should be a valid repo path");+ cx.update(|cx| {+ repository.update(cx, |repository, _| {+ repository.add_path_to_gitignore(&repo_path, is_dir)+ })+ })+ .await+ .expect("add to .gitignore request should complete")+ .expect("add to .gitignore should succeed for remote repository");+ }++ server_cx.run_until_parked();+ cx.run_until_parked();++ assert_eq!(+ fs.load(Path::new("/project/.gitignore"))+ .await+ .expect(".gitignore should be readable"),+ "existing\ntmp.txt\nlogs/\n"+ );+}++#[gpui::test]+async fn test_add_path_to_git_info_exclude_in_remote_repository(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+) {+ let fs = FakeFs::new(server_cx.executor());+ fs.insert_tree(+ "/project",+ json!({+ ".git": {},+ "logs": {+ "app.log": ""+ },+ "tmp.txt": "",+ }),+ )+ .await;+ fs.set_branch_name(Path::new("/project/.git"), Some("main"));+ fs.set_head_for_repo(Path::new("/project/.git"), &[], "head-sha");++ let (project, _headless) = init_test(&fs, cx, server_cx).await;+ project+ .update(cx, |project, cx| {+ project.find_or_create_worktree(Path::new("/project"), true, cx)+ })+ .await+ .expect("should open remote worktree");+ cx.run_until_parked();++ let repository = project.read_with(cx, |project, cx| {+ project+ .active_repository(cx)+ .expect("remote project should have an active repository")+ });++ for (path, is_dir) in [("tmp.txt", false), ("logs", true), ("tmp.txt", false)] {+ let repo_path = RepoPath::new(path).expect("path should be a valid repo path");+ cx.update(|cx| {+ repository.update(cx, |repository, _| {+ repository.add_path_to_git_info_exclude(&repo_path, is_dir)+ })+ })+ .await+ .expect("add to info/exclude request should complete")+ .expect("add to info/exclude should succeed for remote repository");+ }++ server_cx.run_until_parked();+ cx.run_until_parked();++ assert_eq!(+ fs.load(Path::new("/project/.git/info/exclude"))+ .await+ .expect("info/exclude should be readable"),+ "tmp.txt\nlogs/\n"+ );+}+#[gpui::test]async fn test_remote_git_diffs(cx: &mut TestAppContext, server_cx: &mut TestAppContext) {let text_2 = "