Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
project_panel: Explain when a move fails because the destination already exists (#64344)
Zach August11262f92560d
diff --git a/crates/fs/src/fs.rs b/crates/fs/src/fs.rsindex 7cc7b2f53cf..9fc91c5a55d 100644--- a/crates/fs/src/fs.rs+++ b/crates/fs/src/fs.rs@@ -874,7 +874,11 @@ impl Fs for RealFs {if options.ignore_if_exists {return Ok(());} else {- anyhow::bail!("{target:?} already exists");+ return Err(io::Error::new(+ io::ErrorKind::AlreadyExists,+ format!("{target:?} already exists"),+ )+ .into());}}@@ -3137,7 +3141,11 @@ impl Fs for FakeFs {// destroy a file the caller still expects to find.moved = false;} else {- anyhow::bail!("path already exists: {new_path:?}");+ return Err(io::Error::new(+ io::ErrorKind::AlreadyExists,+ format!("path already exists: {new_path:?}"),+ )+ .into());}}btree_map::Entry::Vacant(e) => {diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rsindex a84ab9b427a..615300fae93 100644--- a/crates/project_panel/src/project_panel.rs+++ b/crates/project_panel/src/project_panel.rs@@ -88,7 +88,7 @@ use zed_actions::{use crate::{project_panel_settings::ProjectPanelScrollbarProxy,- undo::{Change, UndoManager},+ undo::{Change, UndoManager, already_exists_error, project_path_display},};const PROJECT_PANEL_KEY: &str = "ProjectPanel";@@ -4267,12 +4267,12 @@ impl ProjectPanel {destination_entry: ProjectEntryId,destination_is_file: bool,cx: &mut Context<Self>,- ) -> Option<Task<Result<CreatedEntry>>> {+ ) -> Option<(ProjectPath, Task<Result<CreatedEntry>>)> {if entry_to_move == destination_entry {return None;}- let (destination_worktree, rename_task) = self.project.update(cx, |project, cx| {+ let (destination_worktree, rename) = self.project.update(cx, |project, cx| {let Some(source_path) = project.path_for_entry(entry_to_move, cx) else {return (None, None);};@@ -4296,24 +4296,20 @@ impl ProjectPanel {let mut new_path = destination_dir.to_rel_path_buf();new_path.push(source_name);- let rename_task = (new_path.as_rel_path() != source_path.path.as_ref()).then(|| {- project.rename_entry(- entry_to_move,- (destination_worktree_id, new_path).into(),- cx,- )++ let new_project_path: ProjectPath = (destination_worktree_id, new_path).into();+ let rename = (new_project_path.path.as_ref() != source_path.path.as_ref()).then(|| {+ let task = project.rename_entry(entry_to_move, new_project_path.clone(), cx);+ (new_project_path, task)});- (- project.worktree_id_for_entry(destination_entry, cx),- rename_task,- )+ (project.worktree_id_for_entry(destination_entry, cx), rename)});if let Some(destination_worktree) = destination_worktree {self.expand_entry(destination_worktree, destination_entry, cx);}- rename_task+ rename}fn index_for_selection(&self, selection: SelectedEntry) -> Option<(usize, usize, usize)> {@@ -5357,14 +5353,25 @@ impl ProjectPanel {.worktree_for_entry(target_entry_id, cx).map(|wt| wt.read(cx).id());- // Collect move tasks paired with their source entry ID so we can correlate- // results with folded selections that need refreshing.- let mut move_tasks: Vec<(ProjectEntryId, Task<Result<CreatedEntry>>)> = Vec::new();+ let path_style = self.project.read(cx).path_style(cx);++ let mut move_tasks: Vec<(+ ProjectEntryId,+ Option<(String, String)>,+ Task<Result<CreatedEntry>>,+ )> = Vec::new();for entry in entries {- if let Some(task) =+ if let Some((destination, task)) =self.move_worktree_entry(entry.entry_id, target_entry_id, is_file, cx){- move_tasks.push((entry.entry_id, task));+ let names = old_paths.get(&entry.entry_id).map(|from| {+ let project = self.project.read(cx);+ (+ project_path_display(project, from, path_style, cx),+ project_path_display(project, &destination, path_style, cx),+ )+ });+ move_tasks.push((entry.entry_id, names, task));}}@@ -5376,9 +5383,10 @@ impl ProjectPanel {if folded_selection_info.is_empty() {cx.spawn_in(window, async move |project_panel, mut cx| {let mut changes = Vec::new();- for (entry_id, task) in move_tasks {+ for (entry_id, names, task) in move_tasks {if let Some(CreatedEntry::Included(new_entry)) = task.await+ .map_err(|err| explain_move_error(err, names.as_ref())).notify_workspace_async_err(workspace.clone(), &mut cx){if let (Some(old_path), Some(worktree_id)) =@@ -5403,9 +5411,10 @@ impl ProjectPanel {// Await all move tasks and collect successful resultslet mut move_results: Vec<(ProjectEntryId, Entry)> = Vec::new();let mut operations = Vec::new();- for (entry_id, task) in move_tasks {+ for (entry_id, names, task) in move_tasks {if let Some(CreatedEntry::Included(new_entry)) = task.await+ .map_err(|err| explain_move_error(err, names.as_ref())).notify_workspace_async_err(workspace.clone(), &mut cx){if let (Some(old_path), Some(worktree_id)) =@@ -8381,6 +8390,15 @@ fn git_status_indicator(git_status: GitSummary) -> Option<(&'static str, Color)>None}+fn explain_move_error(err: anyhow::Error, names: Option<&(String, String)>) -> anyhow::Error {+ match names {+ Some((from, to)) if already_exists_error(&err) => err.context(format!(+ "Failed to move `{from}` to `{to}`. A file or folder already exists there."+ )),+ _ => err,+ }+}+#[cfg(test)]mod project_panel_tests;mod tests;diff --git a/crates/project_panel/src/project_panel_tests.rs b/crates/project_panel/src/project_panel_tests.rsindex 55772893ef7..ff54d3366b2 100644--- a/crates/project_panel/src/project_panel_tests.rs+++ b/crates/project_panel/src/project_panel_tests.rs@@ -26,6 +26,7 @@ use util::{path, paths::PathStyle, rel_path::rel_path};use workspace::{AppState, ItemHandle, MultiWorkspace, Pane, Workspace,item::{Item, ProjectItem, test::TestItem},+ notifications::simple_message_notification::MessageNotification,register_project_item,};@@ -6081,6 +6082,150 @@ async fn test_dragging_same_named_files_preserves_one_source_on_conflict();}+#[gpui::test]+async fn test_drag_onto_existing_name_shows_clear_error(cx: &mut gpui::TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ let settings = *ProjectPanelSettings::get_global(cx);+ ProjectPanelSettings::override_global(+ ProjectPanelSettings {+ auto_fold_dirs: true,+ ..settings+ },+ cx,+ );+ });++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ "/root",+ json!({+ "a": { "1.json": "from a" },+ "1.json": "already here",+ "x": { "y": { "file.txt": "from x" } },+ "target": {+ "x": { "file.txt": "existing directory" },+ "other.txt": ""+ }+ }),+ )+ .await;++ let project = Project::test(fs.clone(), ["/root".as_ref()], cx).await;+ let window = cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));+ let workspace = window+ .read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone())+ .unwrap();+ let cx = &mut VisualTestContext::from_window(window.into(), cx);+ let panel = workspace.update_in(cx, ProjectPanel::new);+ cx.run_until_parked();++ for (source, active_ancestor, target, target_is_file, expected_message) in [+ (+ "root/a/1.json",+ None,+ "root",+ false,+ "Error: Failed to move `a/1.json` to `1.json`. A file or folder already exists there.",+ ),+ (+ "root/a/1.json",+ None,+ "root/1.json",+ true,+ "Error: Failed to move `a/1.json` to `1.json`. A file or folder already exists there.",+ ),+ (+ "root/x/y",+ Some("root/x"),+ "root/target",+ false,+ "Error: Failed to move `x` to `target/x`. A file or folder already exists there.",+ ),+ ] {+ workspace.update(cx, |workspace, cx| {+ for id in workspace.notification_ids() {+ workspace.dismiss_notification(&id, cx);+ }+ });+ if let Some(active_ancestor) = active_ancestor {+ select_folded_path_with_mark(&panel, source, active_ancestor, cx);+ }+ drag_entries_onto(&panel, &[source], target, target_is_file, cx);++ workspace.read_with(cx, |workspace, cx| {+ let notifications = workspace.notification_views();+ assert_eq!(notifications.len(), 1);+ let notification = notifications+ .into_iter()+ .next()+ .unwrap()+ .downcast::<MessageNotification>()+ .unwrap_or_else(|_| panic!("expected an error MessageNotification"));+ let expected_message = if cfg!(windows) {+ expected_message.replace('/', "\\")+ } else {+ expected_message.to_string()+ };+ assert_eq!(+ notification+ .read(cx)+ .copied_text()+ .map(SharedString::as_ref),+ Some(expected_message.as_str())+ );+ });+ }++ for (path, contents) in [+ (path!("/root/a/1.json"), "from a"),+ (path!("/root/1.json"), "already here"),+ (path!("/root/x/y/file.txt"), "from x"),+ (path!("/root/target/x/file.txt"), "existing directory"),+ ] {+ assert_eq!(fs.load(Path::new(path)).await.unwrap(), contents);+ }+}++#[test]+fn test_explain_move_error() {+ let names = ("a/1.json".to_string(), "1.json".to_string());+ let explained_message =+ "Failed to move `a/1.json` to `1.json`. A file or folder already exists there.";++ let local_collision =+ anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::AlreadyExists))+ .context("renaming \"/root/a/1.json\" into \"/root/1.json\"");+ assert_eq!(+ explain_move_error(local_collision, Some(&names)).to_string(),+ explained_message+ );++ let remote_collision = client::RpcError::from_proto(+ &client::proto::Error {+ message: "renaming \"/root/a/1.json\" into \"/root/1.json\": File exists (os error 17)"+ .to_string(),+ code: ErrorCode::AlreadyExists as i32,+ tags: Vec::new(),+ },+ "RenameProjectEntry",+ );+ assert_eq!(+ explain_move_error(remote_collision, Some(&names)).to_string(),+ explained_message+ );++ let path_named_already_exists =+ "renaming \"/root/already exists.txt\" into \"/root/b/already exists.txt\"";+ let permission_denied =+ anyhow::Error::from(std::io::Error::from(std::io::ErrorKind::PermissionDenied))+ .context(path_named_already_exists);+ assert_eq!(+ explain_move_error(permission_denied, Some(&names)).to_string(),+ path_named_already_exists+ );+}+#[gpui::test]async fn test_drag_entries_between_different_worktrees(cx: &mut gpui::TestAppContext) {init_test(cx);diff --git a/crates/project_panel/src/undo.rs b/crates/project_panel/src/undo.rsindex 8de6f778075..e325fb46cb2 100644--- a/crates/project_panel/src/undo.rs+++ b/crates/project_panel/src/undo.rs@@ -132,6 +132,7 @@use crate::{ProjectPanel, RemovalKind};use anyhow::{Context, Result, anyhow};+use client::{ErrorCode, ErrorExt as _, RpcError};use fs::{TrashId, TrashRestoreError};use futures::channel::mpsc;use gpui::{@@ -439,7 +440,7 @@ impl UndoMessage {}}-fn project_path_display(+pub(crate) fn project_path_display(project: &Project,project_path: &ProjectPath,path_style: PathStyle,@@ -450,6 +451,18 @@ fn project_path_display(.unwrap_or_else(|| project_path.path.display(path_style).to_string())}+pub(crate) fn already_exists_error(err: &anyhow::Error) -> bool {+ err.chain().any(|cause| {+ if let Some(io_err) = cause.downcast_ref::<std::io::Error>() {+ io_err.kind() == std::io::ErrorKind::AlreadyExists+ } else if let Some(rpc_error) = cause.downcast_ref::<RpcError>() {+ rpc_error.error_code() == ErrorCode::AlreadyExists+ } else {+ false+ }+ })+}+impl Inner {async fn manage_undo_and_redo(mut self, mut cx: AsyncApp) {loop {@@ -668,16 +681,7 @@ impl Inner {});res?.await.map_err(|err| {- // It is possible for `RealFs::rename` to return an error other than- // `io::Error` when the file already exists, hence why we're also- // checking if the error contains the "already exists" string.- let already_exists = err.chain().any(|cause| {- cause- .downcast_ref::<std::io::Error>()- .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::AlreadyExists)- }) || format!("{err:#}").contains("already exists");-- if already_exists {+ if already_exists_error(&err) {anyhow!("Failed to {operation} `{from_name}` to `{to_name}`. A file or folder already exists there.")diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.protoindex 23faff246f6..2d3fae59ced 100644--- a/crates/proto/proto/zed.proto+++ b/crates/proto/proto/zed.proto@@ -587,6 +587,7 @@ enum ErrorCode {RemoteUpgradeRequired = 17;RateLimitExceeded = 18;CommitFailed = 19;+ AlreadyExists = 20;reserved 6;reserved 14 to 15;}diff --git a/crates/proto/src/error.rs b/crates/proto/src/error.rsindex f551e8c3fc4..2ff2a443570 100644--- a/crates/proto/src/error.rs+++ b/crates/proto/src/error.rs@@ -106,7 +106,7 @@ impl ErrorExt for anyhow::Error {if let Some(rpc_error) = self.downcast_ref::<RpcError>() {rpc_error.to_proto()} else {- ErrorCode::Internal+ code_for_untyped_error(self).message(format!("{self:#}").lines()@@ -131,6 +131,17 @@ impl ErrorExt for anyhow::Error {}}+fn code_for_untyped_error(error: &anyhow::Error) -> ErrorCode {+ let io_error_kind = error+ .chain()+ .find_map(|cause| cause.downcast_ref::<std::io::Error>())+ .map(std::io::Error::kind);+ match io_error_kind {+ Some(std::io::ErrorKind::AlreadyExists) => ErrorCode::AlreadyExists,+ _ => ErrorCode::Internal,+ }+}+impl From<ErrorCode> for anyhow::Error {fn from(value: ErrorCode) -> Self {RpcError {@@ -254,3 +265,27 @@ impl From<ErrorCode> for RpcError {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io;++ #[test]+ fn test_other_untyped_errors_stay_internal() {+ // A different I/O failure, even with "already exists" in a path.+ let error = anyhow::Error::from(io::Error::from(io::ErrorKind::PermissionDenied))+ .context("renaming \"/root/already exists.txt\" into \"/root/b.txt\"");+ assert_eq!(error.to_proto().code(), ErrorCode::Internal);++ // Text alone is never trusted.+ let error = anyhow::anyhow!("path already exists: \"/root/b.txt\"");+ assert_eq!(error.to_proto().code(), ErrorCode::Internal);+ }++ #[test]+ fn test_rpc_error_code_takes_precedence() {+ let error = ErrorCode::Forbidden.anyhow().context("while renaming");+ assert_eq!(error.to_proto().code(), ErrorCode::Forbidden);+ }+}diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex df0c86536b8..290b342aa62 100644--- a/crates/remote_server/src/remote_editing_tests.rs+++ b/crates/remote_server/src/remote_editing_tests.rs@@ -58,7 +58,7 @@ use project::{use remote::{ConnectionState, RemoteClient, RemoteClientEvent};#[cfg(not(windows))]use remote::{MOCK_STDIO_FRAME_HEX, command::RemoteCommand};-use rpc::proto;+use rpc::{ErrorCode, ErrorExt as _, proto};use serde_json::json;use settings::{Settings, SettingsLocation, SettingsStore, SplicingVec, initial_server_settings_content,@@ -3582,6 +3582,60 @@ async fn test_remote_rename_entry(cx: &mut TestAppContext, server_cx: &mut TestA});}+#[gpui::test]+async fn test_remote_rename_entry_onto_existing_path(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+) {+ let fs = FakeFs::new(server_cx.executor());+ fs.insert_tree(+ "/code",+ json!({+ "project1": {+ ".git": {},+ "README.md": "# project 1",+ "README.rst": "existing",+ },+ }),+ )+ .await;++ let (project, _) = init_test(&fs, cx, server_cx).await;+ let (worktree, _) = project+ .update(cx, |project, cx| {+ project.find_or_create_worktree("/code/project1", true, cx)+ })+ .await+ .unwrap();++ cx.run_until_parked();++ let err = project+ .update(cx, |project, cx| {+ let worktree = worktree.read(cx);+ let entry = worktree.entry_for_path(rel_path("README.md")).unwrap();+ project.rename_entry(entry.id, (worktree.id(), rel_path("README.rst")).into(), cx)+ })+ .await+ .unwrap_err();++ assert_eq!(+ err.error_code(),+ ErrorCode::AlreadyExists,+ "the collision should survive the trip from the server: {err:#}"+ );++ // Nothing was overwritten on the server.+ assert_eq!(+ fs.load("/code/project1/README.md".as_ref()).await.unwrap(),+ "# project 1"+ );+ assert_eq!(+ fs.load("/code/project1/README.rst".as_ref()).await.unwrap(),+ "existing"+ );+}+#[gpui::test]async fn test_copy_file_into_remote_project(cx: &mut TestAppContext,diff --git a/crates/workspace/src/notifications.rs b/crates/workspace/src/notifications.rsindex 9a07a77e8a9..ec5bec4a82a 100644--- a/crates/workspace/src/notifications.rs+++ b/crates/workspace/src/notifications.rs@@ -925,6 +925,12 @@ pub mod simple_message_notification {self}+ /// The text copied to the clipboard; for error notifications, the full message.+ #[cfg(any(test, feature = "test-support"))]+ pub fn copied_text(&self) -> Option<&SharedString> {+ self.copy_text.as_ref()+ }+fn auto_dismiss(mut self, severity: ErrorSeverity, cx: &mut Context<Self>) -> Self {if let Some(delay) = severity.auto_dismiss_delay() {self.auto_hide = Some(AutoHideState::new(delay, cx));