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.

Remove deleted files from file finder's history items (#65660)

Kirill Bulatovcc23f35a7ded
diff --git a/Cargo.lock b/Cargo.lock
index 409faf3c300..2456c21c85b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6424,6 +6424,9 @@ dependencies = [
"picker_preview",
"pretty_assertions",
"project",
+ "release_channel",
+ "remote",
+ "remote_server",
"serde_json",
"settings",
"theme",
diff --git a/crates/file_finder/Cargo.toml b/crates/file_finder/Cargo.toml
index 36fde5b4d64..d6f73912543 100644
--- a/crates/file_finder/Cargo.toml
+++ b/crates/file_finder/Cargo.toml
@@ -43,6 +43,9 @@ gpui = { workspace = true, features = ["test-support"] }
picker = { workspace = true, features = ["test-support"] }
pretty_assertions.workspace = true
+release_channel.workspace = true
+remote = { workspace = true, features = ["test-support"] }
+remote_server = { workspace = true, features = ["test-support"] }
serde_json.workspace = true
theme = { workspace = true, features = ["test-support"] }
workspace = { workspace = true, features = ["test-support"] }
diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs
index 82085cb8c52..9b650f7cc56 100644
--- a/crates/file_finder/src/file_finder.rs
+++ b/crates/file_finder/src/file_finder.rs
@@ -8,7 +8,7 @@ pub use open_path_prompt::OpenPathDelegate;
use channel::ChannelStore;
use client::ChannelId;
-use collections::HashMap;
+use collections::{HashMap, HashSet};
use editor::Editor;
use file_icons::FileIcons;
use fuzzy::{StringMatch, StringMatchCandidate};
@@ -116,7 +116,6 @@ impl FileFinder {
cx: &mut Context<Workspace>,
) -> Task<()> {
let project = workspace.project().read(cx);
- let fs = project.fs();
let currently_opened_path = workspace.active_item(cx).and_then(|item| {
let project_path = item.project_path(cx)?;
@@ -131,22 +130,9 @@ impl FileFinder {
.recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
.into_iter()
.filter_map(|(project_path, abs_path)| {
- if project.entry_for_path(&project_path, cx).is_some() {
- return Some(Task::ready(Some(FoundPath::new(project_path, abs_path?))));
- }
- let abs_path = abs_path?;
- if project.is_local() {
- let fs = fs.clone();
- Some(cx.background_spawn(async move {
- if fs.is_file(&abs_path).await {
- Some(FoundPath::new(project_path, abs_path))
- } else {
- None
- }
- }))
- } else {
- Some(Task::ready(Some(FoundPath::new(project_path, abs_path))))
- }
+ let path = FoundPath::new(project_path, abs_path?);
+ let is_file = path.is_file(project, cx);
+ Some(cx.background_spawn(async move { is_file.await.then_some(path) }))
})
.collect::<Vec<_>>();
cx.spawn_in(window, async move |workspace, cx| {
@@ -232,6 +218,7 @@ impl FileFinder {
picker.set_query(&seed_query, window, cx);
picker.select_query(window, cx);
}
+ picker.delegate.refresh_history(window, cx);
});
Self {
picker,
@@ -426,6 +413,7 @@ pub struct FileFinderDelegate {
cancel_flag: Arc<AtomicBool>,
search_in_flight: Arc<AtomicBool>,
history_items: Vec<FoundPath>,
+ history_refresh: Task<()>,
separate_history: bool,
first_update: bool,
focus_handle: FocusHandle,
@@ -893,6 +881,27 @@ impl FoundPath {
fn new(project: ProjectPath, absolute: PathBuf) -> Self {
Self { project, absolute }
}
+
+ fn is_file(&self, project: &Project, cx: &App) -> Task<bool> {
+ if let Some(entry) = project.entry_for_path(&self.project, cx) {
+ return Task::ready(entry.is_file());
+ }
+ if project.is_local() {
+ let fs = project.fs().clone();
+ let path = self.absolute.clone();
+ cx.background_spawn(async move { fs.is_file(&path).await })
+ } else if project.is_via_remote_server() {
+ let Some(path) = self.absolute.to_str() else {
+ return Task::ready(false);
+ };
+ let resolve_path = project.resolve_abs_path(path, cx);
+ cx.background_spawn(
+ async move { resolve_path.await.is_some_and(|path| path.is_file()) },
+ )
+ } else {
+ Task::ready(true)
+ }
+ }
}
const SEARCH_DEBOUNCE: Duration = Duration::from_millis(100);
@@ -1041,6 +1050,7 @@ impl FileFinderDelegate {
cancel_flag: Arc::new(AtomicBool::new(false)),
search_in_flight: Arc::new(AtomicBool::new(false)),
history_items,
+ history_refresh: Task::ready(()),
separate_history,
first_update: true,
focus_handle: cx.focus_handle(),
@@ -1059,6 +1069,7 @@ impl FileFinderDelegate {
match event {
project::Event::WorktreeUpdatedEntries(_, _) => {
file_finder.picker.update(cx, |picker, cx| {
+ picker.delegate.refresh_history(window, cx);
picker.delegate.debounce_next_refresh = true;
picker.refresh(window, cx);
})
@@ -1074,6 +1085,98 @@ impl FileFinderDelegate {
.detach();
}
+ fn refresh_history(&mut self, window: &mut Window, cx: &mut Context<Picker<Self>>) {
+ let project = self.project.read(cx);
+ let paths = self
+ .history_items
+ .iter()
+ .chain(self.currently_opened_path.iter())
+ .cloned()
+ .chain(
+ self.selected_matches
+ .iter()
+ .filter_map(|entry| match &entry.0 {
+ Match::History { path, .. } => Some(path.clone()),
+ Match::Search(path_match) => {
+ let path =
+ project_path_for_search_match(&self.project, &path_match.0, cx);
+ let absolute = project.absolute_path(&path, cx)?;
+ Some(FoundPath::new(path, absolute))
+ }
+ Match::Channel { .. } | Match::CreateNew(_) => None,
+ }),
+ )
+ .filter(|path| {
+ project
+ .entry_for_path(&path.project, cx)
+ .is_none_or(|entry| !entry.is_file())
+ })
+ .map(|path| (path.project.clone(), path))
+ .collect::<HashMap<_, _>>();
+ if paths.is_empty() {
+ self.history_refresh = Task::ready(());
+ return;
+ }
+ let checks = paths
+ .into_values()
+ .map(|path| {
+ let is_file = path.is_file(project, cx);
+ async move { (!is_file.await).then_some(path.project) }
+ })
+ .collect::<Vec<_>>();
+ self.history_refresh = cx.spawn_in(window, async move |picker, cx| {
+ let removed_paths = join_all(checks)
+ .await
+ .into_iter()
+ .flatten()
+ .collect::<HashSet<_>>();
+ if removed_paths.is_empty() {
+ return;
+ }
+ picker
+ .update_in(cx, |picker, window, cx| {
+ picker.delegate.remove_invalid_paths(&removed_paths, cx);
+ picker.delegate.debounce_next_refresh = true;
+ picker.refresh(window, cx);
+ })
+ .ok();
+ });
+ }
+
+ fn remove_invalid_paths(&mut self, removed_paths: &HashSet<ProjectPath>, cx: &App) {
+ let retain_path = |path: &ProjectPath| !removed_paths.contains(path);
+ self.history_items.retain(|path| retain_path(&path.project));
+ if self
+ .currently_opened_path
+ .as_ref()
+ .is_some_and(|path| !retain_path(&path.project))
+ {
+ self.currently_opened_path = None;
+ }
+
+ let project = &self.project;
+ let retain_match = |entry: &Match| match entry {
+ Match::History { path, .. } => retain_path(&path.project),
+ Match::Search(path_match) => {
+ retain_path(&project_path_for_search_match(project, &path_match.0, cx))
+ }
+ Match::Channel { .. } | Match::CreateNew(_) => true,
+ };
+ self.selected_matches.retain(|entry| retain_match(&entry.0));
+
+ let mut index = 0;
+ let mut selected_index = self.selected_index;
+ self.matches.matches.retain(|entry| {
+ let retain = retain_match(entry);
+ if !retain && index < self.selected_index {
+ selected_index -= 1;
+ }
+ index += 1;
+ retain
+ });
+ self.selected_index = selected_index.min(self.matches.len().saturating_sub(1));
+ }
+
fn prepend_selected_matches(&mut self) {
if self.selected_matches.is_empty() {
return;
diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rs
index 08f99609454..ea32c0c7abc 100644
--- a/crates/file_finder/src/file_finder_tests.rs
+++ b/crates/file_finder/src/file_finder_tests.rs
@@ -6,6 +6,8 @@ use gpui::{Entity, TestAppContext, VisualTestContext};
use menu::{Cancel, Confirm, SelectNext, SelectPrevious};
use pretty_assertions::{assert_eq, assert_matches};
use project::{FS_WATCH_LATENCY, RemoveOptions};
+use remote::RemoteClient;
+use remote_server::{HeadlessAppState, HeadlessProject};
use serde_json::json;
use settings::{SettingsStore, SplicingVec};
use util::{path, rel_path::rel_path};
@@ -3540,6 +3542,359 @@ async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext)
});
}
+#[gpui::test]
+async fn test_deleted_remote_history_items_not_shown(
+ cx: &mut TestAppContext,
+ server_cx: &mut TestAppContext,
+) {
+ cx.update(|cx| release_channel::init("0.0.0".parse().unwrap(), cx));
+ server_cx.update(|cx| release_channel::init("0.0.0".parse().unwrap(), cx));
+ let app_state = init_test(cx);
+ let server_app_state = init_test(server_cx);
+ server_app_state
+ .fs
+ .as_fake()
+ .insert_tree(
+ path!("/remote"),
+ json!({
+ "external.rs": "",
+ "src": {
+ "root.rs": "",
+ "nested": {
+ "deleted.rs": "",
+ "retained.rs": "",
+ },
+ },
+ }),
+ )
+ .await;
+
+ let (options, session, _) = RemoteClient::fake_server(cx, server_cx);
+ server_cx.update(HeadlessProject::init);
+ let _headless_project = server_cx.new(|cx| {
+ HeadlessProject::new(
+ HeadlessAppState {
+ session,
+ fs: server_app_state.fs.clone(),
+ http_client: server_app_state.client.http_client(),
+ node_runtime: server_app_state.node_runtime.clone(),
+ languages: server_app_state.languages.clone(),
+ extension_host_proxy: Arc::default(),
+ startup_time: std::time::Instant::now(),
+ },
+ false,
+ cx,
+ )
+ });
+
+ let remote = RemoteClient::connect_mock(options, cx).await;
+
+ let project = cx.update(|cx| {
+ Project::init(&app_state.client, cx);
+ Project::remote(
+ remote,
+ app_state.client.clone(),
+ app_state.node_runtime.clone(),
+ app_state.user_store.clone(),
+ app_state.languages.clone(),
+ app_state.fs.clone(),
+ false,
+ cx,
+ )
+ });
+ project
+ .update(cx, |project, cx| {
+ project.find_or_create_worktree(path!("/remote/src"), true, cx)
+ })
+ .await
+ .unwrap();
+
+ let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
+ window.activate_window();
+ let workspace =
+ cx.new(|cx| Workspace::new(None, project.clone(), app_state.clone(), window, cx));
+ window.focus(&workspace.read(cx).focus_handle(cx), cx);
+ MultiWorkspace::new(workspace, window, cx)
+ });
+ let workspace = multi_workspace.read_with(cx, |workspace, _| workspace.workspace().clone());
+ workspace
+ .update_in(cx, |workspace, window, cx| {
+ workspace.open_abs_path(
+ PathBuf::from(path!("/remote/external.rs")),
+ OpenOptions {
+ visible: Some(OpenVisible::None),
+ ..OpenOptions::default()
+ },
+ window,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.dispatch_action(CloseActiveItem {
+ save_intent: None,
+ close_pinned: false,
+ });
+ workspace
+ .update_in(cx, |workspace, window, cx| {
+ workspace.open_abs_path(
+ PathBuf::from(path!("/remote/src/nested/retained.rs")),
+ OpenOptions::default(),
+ window,
+ cx,
+ )
+ })
+ .await
+ .unwrap();
+ cx.dispatch_action(CloseActiveItem {
+ save_intent: None,
+ close_pinned: false,
+ });
+ open_close_queried_buffer("deleted", 1, "deleted.rs", &workspace, cx).await;
+ open_close_queried_buffer("root", 1, "root.rs", &workspace, cx).await;
+ cx.run_until_parked();
+
+ for path in [
+ path!("/remote/src/root.rs"),
+ path!("/remote/src/nested/deleted.rs"),
+ ] {
+ server_app_state
+ .fs
+ .remove_file(Path::new(path), RemoveOptions::default())
+ .await
+ .unwrap();
+ }
+ advance_worktree_update_refresh(cx);
+ project.read_with(cx, |project, cx| {
+ for path in [
+ path!("/remote/src/root.rs"),
+ path!("/remote/src/nested/deleted.rs"),
+ ] {
+ let path = project
+ .project_path_for_absolute_path(Path::new(path), cx)
+ .unwrap();
+ assert!(project.entry_for_path(&path, cx).is_none());
+ }
+ });
+
+ let picker = open_file_picker(&workspace, cx);
+ picker.update(cx, |picker, cx| {
+ assert_eq!(
+ picker
+ .delegate
+ .matches
+ .matches
+ .iter()
+ .filter_map(|entry| match entry {
+ Match::History { path, .. } => Some(path.absolute.clone()),
+ _ => None,
+ })
+ .collect::<Vec<_>>(),
+ vec![
+ PathBuf::from(path!("/remote/src/nested/retained.rs")),
+ PathBuf::from(path!("/remote/external.rs")),
+ ],
+ );
+ let external = picker.delegate.history_items.last().unwrap();
+ assert!(
+ project
+ .read(cx)
+ .worktree_for_id(external.project.worktree_id, cx)
+ .is_none()
+ );
+ });
+
+ simulate_input(cx, "deleted");
+ picker.update(cx, |picker, _| {
+ assert_matches!(
+ picker.delegate.matches.matches.as_slice(),
+ [Match::CreateNew(_)]
+ );
+ });
+}
+
+#[gpui::test]
+async fn test_deleted_history_items_removed_while_picker_is_open(cx: &mut TestAppContext) {
+ let app_state = init_test(cx);
+ app_state
+ .fs
+ .as_fake()
+ .insert_tree(
+ path!("/src"),
+ json!({
+ "root.rs": "",
+ "nested": {
+ "deleted.rs": "",
+ "retained.rs": "",
+ },
+ }),
+ )
+ .await;
+
+ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
+ let (multi_workspace, cx) =
+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
+ let workspace = multi_workspace.read_with(cx, |workspace, _| workspace.workspace().clone());
+ open_close_queried_buffer("retained", 1, "retained.rs", &workspace, cx).await;
+ open_close_queried_buffer("deleted", 1, "deleted.rs", &workspace, cx).await;
+ open_close_queried_buffer("root", 1, "root.rs", &workspace, cx).await;
+
+ let picker = open_file_picker(&workspace, cx);
+ picker.update(cx, |picker, _| {
+ assert_eq!(picker.delegate.matches.len(), 3);
+ assert_match_selection(picker, 0, "root.rs");
+ });
+ cx.dispatch_action(SelectNext);
+ app_state
+ .fs
+ .remove_file(Path::new(path!("/src/root.rs")), RemoveOptions::default())
+ .await
+ .unwrap();
+ advance_worktree_update_refresh(cx);
+
+ picker.update(cx, |picker, _| {
+ assert_eq!(picker.delegate.matches.len(), 2);
+ assert_match_selection(picker, 0, "deleted.rs");
+ assert_match_at_position(picker, 1, "retained.rs");
+ });
+
+ simulate_input(cx, "rs");
+ picker.update_in(cx, |picker, window, cx| {
+ assert_match_at_position(picker, 0, "deleted.rs");
+ picker.delegate.toggle_item_selected(0, window, cx);
+ assert_eq!(picker.delegate.selected_item_count(), 1);
+ });
+ app_state
+ .fs
+ .remove_file(
+ Path::new(path!("/src/nested/deleted.rs")),
+ RemoveOptions::default(),
+ )
+ .await
+ .unwrap();
+ advance_worktree_update_refresh(cx);
+
+ picker.update(cx, |picker, _| {
+ assert_eq!(picker.delegate.matches.len(), 2);
+ assert_match_selection(picker, 0, "retained.rs");
+ assert_eq!(picker.delegate.selected_item_count(), 0);
+ assert_matches!(picker.delegate.matches.get(0), Some(Match::History { .. }));
+ assert_matches!(picker.delegate.matches.get(1), Some(Match::CreateNew(_)));
+ });
+
+ cx.dispatch_action(Cancel);
+ let picker = open_file_picker(&workspace, cx);
+ picker.update(cx, |picker, _| {
+ assert_eq!(picker.delegate.matches.len(), 1);
+ assert_match_selection(picker, 0, "retained.rs");
+ });
+ cx.dispatch_action(Confirm);
+ let picker = open_file_picker(&workspace, cx);
+ simulate_input(cx, "retained");
+ app_state
+ .fs
+ .remove_file(
+ Path::new(path!("/src/nested/retained.rs")),
+ RemoveOptions::default(),
+ )
+ .await
+ .unwrap();
+ advance_worktree_update_refresh(cx);
+ picker.update(cx, |picker, _| {
+ assert!(picker.delegate.currently_opened_path.is_none());
+ assert_matches!(
+ picker.delegate.matches.matches.as_slice(),
+ [Match::CreateNew(_)]
+ );
+ });
+}
+
+#[gpui::test]
+async fn test_history_refresh_preserves_other_worktrees_and_excluded_files(
+ cx: &mut TestAppContext,
+) {
+ let app_state = init_test(cx);
+ app_state
+ .fs
+ .as_fake()
+ .insert_tree(
+ path!("/root"),
+ json!({
+ "one": { "nested": { "file.rs": "" } },
+ "two": { "nested": { "file.rs": "" } },
+ }),
+ )
+ .await;
+ let project = Project::test(
+ app_state.fs.clone(),
+ [path!("/root/one").as_ref(), path!("/root/two").as_ref()],
+ cx,
+ )
+ .await;
+ let (multi_workspace, cx) =
+ cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
+ let workspace = multi_workspace.read_with(cx, |workspace, _| workspace.workspace().clone());
+ for path in [
+ path!("/root/one/nested/file.rs"),
+ path!("/root/two/nested/file.rs"),
+ ] {
+ workspace
+ .update_in(cx, |workspace, window, cx| {
+ workspace.open_abs_path(PathBuf::from(path), OpenOptions::default(), window, cx)
+ })
+ .await
+ .unwrap();
+ cx.dispatch_action(CloseActiveItem {
+ save_intent: None,
+ close_pinned: false,
+ });
+ }
+ let picker = open_file_picker(&workspace, cx);
+ picker.update(cx, |picker, _| assert_eq!(picker.delegate.matches.len(), 2));
+ app_state
+ .fs
+ .remove_file(
+ Path::new(path!("/root/one/nested/file.rs")),
+ RemoveOptions::default(),
+ )
+ .await
+ .unwrap();
+ advance_worktree_update_refresh(cx);
+ picker.update_in(cx, |picker, window, cx| {
+ assert_eq!(picker.delegate.matches.len(), 1);
+ assert_eq!(
+ picker.delegate.history_items[0].absolute,
+ Path::new(path!("/root/two/nested/file.rs"))
+ );
+ picker.delegate.toggle_item_selected(0, window, cx);
+ });
+
+ cx.update(|_, cx| {
+ cx.update_global::<SettingsStore, _>(|store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.project.worktree.file_scan_exclusions =
+ Some(SplicingVec::from(vec!["**/file.rs".to_string()]));
+ });
+ });
+ });
+ advance_worktree_update_refresh(cx);
+ picker.update(cx, |picker, cx| {
+ let retained_path = &picker.delegate.history_items[0];
+ assert!(
+ project
+ .read(cx)
+ .entry_for_path(&retained_path.project, cx)
+ .is_none()
+ );
+ assert_eq!(picker.delegate.matches.len(), 1);
+ assert_eq!(picker.delegate.selected_item_count(), 1);
+ assert_eq!(
+ retained_path.absolute,
+ Path::new(path!("/root/two/nested/file.rs"))
+ );
+ });
+}
+
#[gpui::test]
async fn test_search_results_refreshed_on_worktree_updates(cx: &mut gpui::TestAppContext) {
let app_state = init_test(cx);