Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
git: Correctly filter ignored paths inside gitdirs on all platforms (#54548)
Cole Millercd944ad8d6a2
diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rsindex 5877cb1ac11..5e658659e2b 100644--- a/crates/worktree/src/worktree.rs+++ b/crates/worktree/src/worktree.rs@@ -4319,49 +4319,34 @@ impl BackgroundScanner {events = Self::normalized_events_for_worktree(&state, &root_canonical_path, events);}+ fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {+ if let Some(last_range) = ranges.last_mut()+ && last_range.end == ix+ {+ last_range.end += 1;+ } else {+ ranges.push(ix..ix + 1);+ }+ }++ // Check for events inside .git directories, so that we know which repositories need their git state reloaded.+ //// Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.// Ignore these, to avoid Zed unnecessarily rescanning git metadata.let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];- let mut relative_paths = Vec::with_capacity(events.len());let mut dot_git_abs_paths = Vec::new();let mut work_dirs_needing_exclude_update = Vec::new();- events.sort_unstable_by(|left, right| left.path.cmp(&right.path));- events.dedup_by(|left, right| {- if left.path == right.path {- if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {- right.kind = left.kind;- }- true- } else if left.path.starts_with(&right.path) {- if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {- right.kind = left.kind;- }- true- } else {- false- }- });+{let snapshot = &self.state.lock().await.snapshot;let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();- fn skip_ix(ranges: &mut SmallVec<[Range<usize>; 4]>, ix: usize) {- if let Some(last_range) = ranges.last_mut()- && last_range.end == ix- {- last_range.end += 1;- } else {- ranges.push(ix..ix + 1);- }- }-for (ix, event) in events.iter().enumerate() {let abs_path = SanitizedPath::new(&event.path);- let mut is_git_related = false;let mut dot_git_paths = None;for ancestor in abs_path.as_path().ancestors() {@@ -4376,12 +4361,14 @@ impl BackgroundScanner {}if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {- let condition = skipped_files_in_dot_git.iter().any(|skipped| {+ let skip = skipped_files_in_dot_git.iter().any(|skipped| {OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str()}) || skipped_dirs_in_dot_git.iter()- .any(|skipped_git_subdir| path_in_git_dir.starts_with(skipped_git_subdir));- if condition {+ .any(|skipped_git_subdir| path_in_git_dir.starts_with(skipped_git_subdir))+ || path_in_git_dir == Path::new("")+ && self.fs.is_dir(&dot_git_abs_path).await;+ if skip {log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");@@ -4389,42 +4376,64 @@ impl BackgroundScanner {continue;}- is_git_related = true;if !dot_git_abs_paths.contains(&dot_git_abs_path) {dot_git_abs_paths.push(dot_git_abs_path);}}+ if abs_path+ .as_path()+ .ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE))+ {+ if let Some(repository) = snapshot.git_repositories.values().find(|repo| {+ repo.common_dir_abs_path.join(REPO_EXCLUDE) == abs_path.as_path()+ }) {+ work_dirs_needing_exclude_update+ .push(repository.work_directory_abs_path.clone());+ }+ }+ }++ for range_to_drop in ranges_to_drop.into_iter().rev() {+ events.drain(range_to_drop);+ }+ }++ events.sort_unstable_by(|left, right| left.path.cmp(&right.path));+ events.dedup_by(|left, right| {+ if left.path == right.path {+ if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {+ right.kind = left.kind;+ }+ true+ } else if left.path.starts_with(&right.path) {+ if matches!(left.kind, Some(fs::PathEventKind::Rescan)) {+ right.kind = left.kind;+ }+ true+ } else {+ false+ }+ });++ let mut relative_paths = Vec::with_capacity(events.len());++ {+ let snapshot = &self.state.lock().await.snapshot;++ let mut ranges_to_drop = SmallVec::<[Range<usize>; 4]>::new();++ for (ix, event) in events.iter().enumerate() {+ let abs_path = SanitizedPath::new(&event.path);let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)&& let Ok(path) = RelPath::new(path, PathStyle::local()){path} else {- if is_git_related {- log::debug!(- "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",- );- } else {- log::error!(- "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",- );- }skip_ix(&mut ranges_to_drop, ix);continue;};- let absolute_path = abs_path.to_path_buf();- if absolute_path.ends_with(Path::new(DOT_GIT).join(REPO_EXCLUDE)) {- if let Some(repository) = snapshot- .git_repositories- .values()- .find(|repo| repo.common_dir_abs_path.join(REPO_EXCLUDE) == absolute_path)- {- work_dirs_needing_exclude_update- .push(repository.work_directory_abs_path.clone());- }- }-if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {for (_, repo) in snapshot.git_repositories@@ -4451,9 +4460,6 @@ impl BackgroundScanner {}if self.settings.is_path_excluded(&relative_path) {- if !is_git_related {- log::debug!("ignoring FS event for excluded path {relative_path:?}");- }skip_ix(&mut ranges_to_drop, ix);continue;}diff --git a/crates/worktree/tests/integration/main.rs b/crates/worktree/tests/integration/main.rsindex 922da7f1bf2..2fedafc591f 100644--- a/crates/worktree/tests/integration/main.rs+++ b/crates/worktree/tests/integration/main.rs@@ -2,7 +2,7 @@ mod worktree_settings;use anyhow::Result;use encoding_rs;-use fs::{FakeFs, Fs, RealFs, RemoveOptions};+use fs::{FakeFs, Fs, PathEventKind, RealFs, RemoveOptions};use git::{DOT_GIT, GITIGNORE, REPO_EXCLUDE};use gpui::{AppContext as _, BackgroundExecutor, BorrowAppContext, Context, Task, TestAppContext};use parking_lot::Mutex;@@ -3218,6 +3218,126 @@ async fn test_linked_worktree_event_in_unregistered_common_git_dir_does_not_panitree.flush_fs_events(cx).await;}+#[gpui::test]+async fn test_dot_git_dir_event_does_not_suppress_children(+ executor: BackgroundExecutor,+ cx: &mut TestAppContext,+) {+ // On Windows, modifying a file inside .git causes ReadDirectoryChangesW to also emit+ // a Modify event for the .git directory itself (because its last-write timestamp changes).+ // When these events arrive in the same batch, a naive ancestor-based dedup would collapse+ // all child events into the .git directory event, losing the information about which+ // specific files changed. This test verifies that the git-related event processing happens+ // before the dedup, so that meaningful .git child events still trigger UpdatedGitRepositories.+ init_test(cx);++ let fs = FakeFs::new(executor.clone());+ let project_dir = Path::new(path!("/project"));+ fs.insert_tree(+ project_dir,+ json!({+ ".git": {},+ "src": {+ "main.rs": "fn main() {}",+ },+ }),+ )+ .await;++ let worktree = Worktree::local(+ project_dir,+ true,+ fs.clone(),+ Default::default(),+ true,+ WorktreeId::from_proto(0),+ &mut cx.to_async(),+ )+ .await+ .unwrap();+ worktree+ .update(cx, |worktree, _| {+ worktree.as_local().unwrap().scan_complete()+ })+ .await;+ cx.run_until_parked();++ let dot_git = project_dir.join(DOT_GIT);++ // Case 1: Events for .git AND .git/index.lock should NOT emit UpdatedGitRepositories+ // (index.lock is in the skipped files list)+ {+ let mut events = cx.events(&worktree);+ fs.pause_events();+ fs.emit_fs_event(dot_git.clone(), Some(PathEventKind::Changed));+ fs.emit_fs_event(dot_git.join("index.lock"), Some(PathEventKind::Created));+ fs.unpause_events_and_flush();+ executor.run_until_parked();++ let got_git_update = drain_git_repo_updates(&mut events);+ assert!(+ !got_git_update,+ "should NOT emit UpdatedGitRepositories when .git batch only contains index.lock"+ );+ }++ // Case 2: Event for just .git (bare directory event) should NOT emit UpdatedGitRepositories+ {+ let mut events = cx.events(&worktree);+ fs.pause_events();+ fs.emit_fs_event(dot_git.clone(), Some(PathEventKind::Changed));+ fs.unpause_events_and_flush();+ executor.run_until_parked();++ let got_git_update = drain_git_repo_updates(&mut events);+ assert!(+ !got_git_update,+ "should NOT emit UpdatedGitRepositories for a bare .git directory event"+ );+ }++ // Case 3: Events for .git AND .git/index should emit UpdatedGitRepositories+ {+ let mut events = cx.events(&worktree);+ fs.pause_events();+ fs.emit_fs_event(dot_git.clone(), Some(PathEventKind::Changed));+ fs.emit_fs_event(dot_git.join("index"), Some(PathEventKind::Changed));+ fs.unpause_events_and_flush();+ executor.run_until_parked();++ let got_git_update = drain_git_repo_updates(&mut events);+ assert!(+ got_git_update,+ "should emit UpdatedGitRepositories when .git batch contains index"+ );+ }++ // Case 4: Event for .git/index only should emit UpdatedGitRepositories+ {+ let mut events = cx.events(&worktree);+ fs.pause_events();+ fs.emit_fs_event(dot_git.join("index"), Some(PathEventKind::Changed));+ fs.unpause_events_and_flush();+ executor.run_until_parked();++ let got_git_update = drain_git_repo_updates(&mut events);+ assert!(+ got_git_update,+ "should emit UpdatedGitRepositories for a .git/index event"+ );+ }+}++fn drain_git_repo_updates(events: &mut futures::channel::mpsc::UnboundedReceiver<Event>) -> bool {+ let mut found = false;+ while let Ok(event) = events.try_recv() {+ if matches!(event, Event::UpdatedGitRepositories(_)) {+ found = true;+ }+ }+ found+}+fn init_test(cx: &mut gpui::TestAppContext) {zlog::init_test();