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.

Allow file watchers to handle case insensitive file systems (#59579)

Anthony Eid6febe1c45a6d
diff --git a/Cargo.lock b/Cargo.lock
index 98740df2a37..2d7c91d9f70 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6874,6 +6874,7 @@ dependencies = [
"thiserror 2.0.17",
"time",
"trash",
+ "unicode-normalization",
"util",
"windows 0.61.3",
]
diff --git a/crates/fs/Cargo.toml b/crates/fs/Cargo.toml
index 01526ae07a3..5f95536e6c5 100644
--- a/crates/fs/Cargo.toml
+++ b/crates/fs/Cargo.toml
@@ -53,6 +53,9 @@ dunce.workspace = true
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
ashpd.workspace = true
+[target.'cfg(target_os = "macos")'.dependencies]
+unicode-normalization = "0.1"
+
[dev-dependencies]
fs = { workspace = true, features = ["test-support"] }
gpui = { workspace = true, features = ["test-support"] }
diff --git a/crates/fs/src/fs_watcher.rs b/crates/fs/src/fs_watcher.rs
index 98184da38e3..49d0d429d8e 100644
--- a/crates/fs/src/fs_watcher.rs
+++ b/crates/fs/src/fs_watcher.rs
@@ -2,7 +2,8 @@ use gpui::{BackgroundExecutor, Task};
use notify::{Event, EventKind};
use parking_lot::Mutex;
use std::{
- collections::{BTreeMap, HashMap},
+ collections::HashMap,
+ fs,
ops::DerefMut,
path::Path,
sync::{Arc, LazyLock, OnceLock},
@@ -23,7 +24,7 @@ pub struct FsWatcher {
executor: BackgroundExecutor,
tx: async_channel::Sender<()>,
pending_path_events: Arc<Mutex<Vec<PathEvent>>>,
- registrations: Arc<Mutex<BTreeMap<Arc<std::path::Path>, FsWatcherRegistration>>>,
+ registrations: Arc<Mutex<HashMap<WatchKey, FsWatcherRegistration>>>,
pending_registrations: Arc<Mutex<HashMap<Arc<std::path::Path>, Task<()>>>>,
}
@@ -49,13 +50,19 @@ impl FsWatcher {
}
fn add_existing_path(&self, path: Arc<Path>) -> anyhow::Result<()> {
- let registration_path = path.clone();
- if let Some(registration) =
- register_existing_path(path, self.tx.clone(), self.pending_path_events.clone())?
- {
- self.registrations
- .lock()
- .insert(registration_path, registration);
+ let case_insensitive = case_insensitive_path(&path);
+ let key = WatchKey::for_registration(SanitizedPath::new(&path), case_insensitive);
+ if self.registrations.lock().contains_key(&key) {
+ log::trace!("path to watch is already watched: {path:?}");
+ return Ok(());
+ }
+ if let Some(registration) = register_existing_path(
+ path,
+ case_insensitive,
+ self.tx.clone(),
+ self.pending_path_events.clone(),
+ )? {
+ self.registrations.lock().insert(key, registration);
}
Ok(())
}
@@ -82,7 +89,7 @@ impl Drop for FsWatcher {
fn drop(&mut self) {
self.pending_registrations.lock().clear();
- let mut registrations = BTreeMap::new();
+ let mut registrations = HashMap::new();
{
let old = &mut self.registrations.lock();
std::mem::swap(old.deref_mut(), &mut registrations);
@@ -99,36 +106,25 @@ impl Watcher for FsWatcher {
fn add(&self, path: &std::path::Path) -> anyhow::Result<()> {
log::trace!("watcher add: {path:?}");
- let (path_is_covered_by_recursive_registration, path_is_already_watched) = {
- let registrations = self.registrations.lock();
- (
- path.ancestors().skip(1).any(|ancestor| {
- registrations.get(ancestor).is_some_and(|registration| {
- registration.mode == WatcherMode::Poll
- || cfg!(any(target_os = "windows", target_os = "macos"))
- })
- }),
- registrations.contains_key(path),
- )
- };
-
- if path_is_covered_by_recursive_registration {
- log::trace!("path to watch is covered by existing registration: {path:?}");
- return Ok(());
- }
-
- if path_is_already_watched {
- log::trace!("path to watch is already watched: {path:?}");
+ let path: Arc<Path> = path.into();
+ if path_covered_by_recursive_registration(
+ &self.registrations.lock(),
+ SanitizedPath::new(&path),
+ ) {
+ log::trace!("path to watch is covered by an existing registration: {path:?}");
return Ok(());
}
- if self.pending_registrations.lock().contains_key(path) {
+ if self
+ .pending_registrations
+ .lock()
+ .contains_key(path.as_ref())
+ {
log::trace!("path to watch is already pending: {path:?}");
return Ok(());
}
- let path: Arc<std::path::Path> = path.into();
- if std::fs::symlink_metadata(path.as_ref()).is_err() {
+ if fs::symlink_metadata(path.as_ref()).is_err() {
self.add_pending_path(path);
return Ok(());
}
@@ -140,15 +136,40 @@ impl Watcher for FsWatcher {
log::trace!("remove watched path: {path:?}");
self.pending_registrations.lock().remove(path);
- let Some(registration) = self.registrations.lock().remove(path) else {
- return Ok(());
+ let sanitized = SanitizedPath::new(path);
+ let registration = {
+ let mut registrations = self.registrations.lock();
+ registrations
+ .remove(&WatchKey::exact(sanitized))
+ .or_else(|| registrations.remove(&WatchKey::folded(sanitized)))
};
-
- global_watcher().remove(registration.id);
+ if let Some(registration) = registration {
+ global_watcher().remove(registration.id);
+ }
Ok(())
}
}
+/// Whether a recursive registration on a strict ancestor of `path` already covers
+/// it. Both key spellings are probed so a folded registration still matches; only
+/// poll watches and native macOS/Windows watches are recursive.
+fn path_covered_by_recursive_registration(
+ registrations: &HashMap<WatchKey, FsWatcherRegistration>,
+ path: &SanitizedPath,
+) -> bool {
+ path.as_path().ancestors().skip(1).any(|ancestor| {
+ let ancestor = SanitizedPath::unchecked_new(ancestor);
+ [WatchKey::exact(ancestor), WatchKey::folded(ancestor)]
+ .iter()
+ .any(|key| {
+ registrations.get(key).is_some_and(|registration| {
+ registration.mode == WatcherMode::Poll
+ || cfg!(any(target_os = "windows", target_os = "macos"))
+ })
+ })
+ })
+}
+
/// Detect whether a path requires polling instead of native file watching.
///
/// Returns `true` for filesystem types where inotify/FSEvents/ReadDirectoryChanges
@@ -182,6 +203,7 @@ pub fn requires_poll_watcher(path: &Path) -> bool {
fn register_existing_path(
path: Arc<Path>,
+ case_insensitive: bool,
tx: async_channel::Sender<()>,
pending_path_events: Arc<Mutex<Vec<PathEvent>>>,
) -> anyhow::Result<Option<FsWatcherRegistration>> {
@@ -198,17 +220,22 @@ fn register_existing_path(
};
let root_path = SanitizedPath::new_arc(path.as_ref());
let path_for_callback = path.clone();
- let Some(registration_id) =
- global_watcher().add(path, mode, move |event: &notify::Event| {
+ let Some(registration_id) = global_watcher().add(
+ path,
+ mode,
+ case_insensitive,
+ move |event: &notify::Event| {
log::trace!("watcher received event: {event:?}");
push_notify_event(
&tx,
&pending_path_events,
&root_path,
+ case_insensitive,
path_for_callback.as_ref(),
event,
);
- })?
+ },
+ )?
else {
return Ok(None);
};
@@ -326,12 +353,128 @@ fn is_wsl_drvfs_path(path: &Path) -> bool {
&& (after_mnt.len() == 1 || after_mnt.as_bytes()[1] == b'/')
}
+/// Whether the volume backing `path` does case-insensitive name lookups, used to
+/// pick exact vs. folded matching.
+#[cfg(target_os = "macos")]
+fn case_insensitive_path(path: &Path) -> bool {
+ use std::os::unix::ffi::OsStrExt as _;
+
+ // `pathconf(_PC_CASE_SENSITIVE)` returns 1 (sensitive), 0 (insensitive), or -1
+ // on error; default errors to insensitive (the APFS/HFS+ default).
+ let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
+ return true;
+ };
+ // SAFETY: We just initialized c_path, so it's a valid pointer
+ unsafe { libc::pathconf(c_path.as_ptr(), libc::_PC_CASE_SENSITIVE) == 0 }
+}
+
+#[cfg(target_os = "linux")]
+fn case_insensitive_path(path: &Path) -> bool {
+ use std::os::unix::ffi::OsStrExt as _;
+
+ // Only ext4/f2fs casefold (`+F`) dirs are insensitive, reported by `statx` via
+ // STATX_ATTR_CASEFOLD; any failure (e.g. pre-4.11 ENOSYS) means case-sensitive.
+ const STATX_ATTR_CASEFOLD: u64 = 0x0000_2000;
+ let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
+ return false;
+ };
+ let mut buf = std::mem::MaybeUninit::<libc::statx>::zeroed();
+
+ // SAFETY: c_path is still valid, buffer has been zeroed
+ if unsafe { libc::statx(libc::AT_FDCWD, c_path.as_ptr(), 0, 0, buf.as_mut_ptr()) } != 0 {
+ return false;
+ }
+
+ // SAFETY: libc statx initialized this buffer, otherwise we would've returned on a error
+ // in that function call
+ let buf = unsafe { buf.assume_init() };
+ buf.stx_attributes_mask & STATX_ATTR_CASEFOLD != 0
+ && buf.stx_attributes & STATX_ATTR_CASEFOLD != 0
+}
+
+#[cfg(target_os = "windows")]
+fn case_insensitive_path(_path: &Path) -> bool {
+ // todo(windows): Windows defaults to case in sensitive, but
+ // they can mark specific directories as case sensitive. Mainly
+ // for WSL use cases
+ true
+}
+
+#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
+fn case_insensitive_path(_path: &Path) -> bool {
+ // Other BSDs default to case-sensitive local filesystems.
+ false
+}
+
+/// Whether `path` is `root` or sits beneath it, folding case on case-insensitive
+/// volumes so a differently-cased spelling still matches.
+fn path_is_under(path: &SanitizedPath, root: &SanitizedPath, case_insensitive: bool) -> bool {
+ if case_insensitive {
+ let path = path.as_path().to_string_lossy().to_lowercase();
+ let root = root.as_path().to_string_lossy().to_lowercase();
+ Path::new(&path).starts_with(Path::new(&root))
+ } else {
+ path.starts_with(root)
+ }
+}
+
+/// Lookup key for a watch path, shared by add, remove, and dispatch so they all
+/// agree on whether two spellings denote the same directory.
+///
+/// On case-sensitive volumes the exact (sanitized) path is the key, so genuinely
+/// distinct directories stay distinct. On case-insensitive volumes the folded
+/// (lowercased) spelling is the key, so any casing of a directory collides.
+///
+/// The two variants are distinct map keys, so a case-sensitive registration can
+/// never be hit by a folded lookup (or vice versa); dispatch can therefore probe
+/// both forms of an event path without risking a cross-rule false match.
+///
+/// NOTE: folding only normalizes case. macOS (APFS/HFS+) is also Unicode
+/// normalization-insensitive (NFC vs NFD); that normalization is intentionally
+/// centralized here so it can be added in one place later without touching the
+/// add/remove/dispatch call sites.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+enum WatchKey {
+ Exact(Arc<Path>),
+ Folded(Arc<str>),
+}
+
+impl WatchKey {
+ fn exact(path: &SanitizedPath) -> Self {
+ Self::Exact(Arc::from(path.as_path()))
+ }
+
+ fn folded(path: &SanitizedPath) -> Self {
+ let lossy = path.as_path().to_string_lossy();
+ // macOS (APFS/HFS+) compares names normalization-insensitively (NFC vs
+ // NFD), and FSEvents can report NFD while a config/LSP supplies NFC, so
+ // normalize before folding case. Windows (NTFS) and Linux are
+ // normalization-sensitive, so there we only fold case.
+ #[cfg(target_os = "macos")]
+ let folded = {
+ use unicode_normalization::UnicodeNormalization as _;
+ lossy.chars().nfc().collect::<String>().to_lowercase()
+ };
+ #[cfg(not(target_os = "macos"))]
+ let folded = lossy.to_lowercase();
+ Self::Folded(folded.into())
+ }
+
+ fn for_registration(path: &SanitizedPath, case_insensitive: bool) -> Self {
+ if case_insensitive {
+ Self::folded(path)
+ } else {
+ Self::exact(path)
+ }
+ }
+}
+
async fn poll_path_until_created(
executor: BackgroundExecutor,
path: Arc<Path>,
tx: async_channel::Sender<()>,
pending_path_events: Arc<Mutex<Vec<PathEvent>>>,
- registrations: Arc<Mutex<BTreeMap<Arc<Path>, FsWatcherRegistration>>>,
+ registrations: Arc<Mutex<HashMap<WatchKey, FsWatcherRegistration>>>,
pending_registrations: Arc<Mutex<HashMap<Arc<Path>, Task<()>>>>,
) {
loop {
@@ -345,12 +488,22 @@ async fn poll_path_until_created(
continue;
}
- if registrations.lock().contains_key(path.as_ref()) {
+ // Probe case sensitivity now that the path exists, rather than at add
+ // time when it didn't.
+ let case_insensitive = case_insensitive_path(path.as_ref());
+ let key = WatchKey::for_registration(SanitizedPath::new(&path), case_insensitive);
+
+ if registrations.lock().contains_key(&key) {
pending_registrations.lock().remove(path.as_ref());
return;
}
- match register_existing_path(path.clone(), tx.clone(), pending_path_events.clone()) {
+ match register_existing_path(
+ path.clone(),
+ case_insensitive,
+ tx.clone(),
+ pending_path_events.clone(),
+ ) {
Ok(Some(registration)) => {
{
let mut pending_registrations = pending_registrations.lock();
@@ -358,7 +511,7 @@ async fn poll_path_until_created(
global_watcher().remove(registration.id);
return;
}
- registrations.lock().insert(path.clone(), registration);
+ registrations.lock().insert(key, registration);
}
enqueue_path_events(
&tx,
@@ -408,6 +561,7 @@ fn push_notify_event(
tx: &smol::channel::Sender<()>,
pending_path_events: &Arc<Mutex<Vec<PathEvent>>>,
root_path: &SanitizedPath,
+ case_insensitive: bool,
watched_root: &Path,
event: &notify::Event,
) {
@@ -422,7 +576,7 @@ fn push_notify_event(
.iter()
.filter_map(|event_path| {
let event_path = SanitizedPath::new(event_path);
- event_path.starts_with(root_path).then(|| PathEvent {
+ path_is_under(event_path, root_path, case_insensitive).then(|| PathEvent {
path: event_path.as_path().to_path_buf(),
kind,
})
@@ -521,6 +675,7 @@ pub struct WatcherRegistrationId(u32);
struct WatcherRegistrationState {
callback: Arc<dyn Fn(&notify::Event) + Send + Sync>,
+ key: WatchKey,
path: Arc<SanitizedPath>,
mode: WatcherMode,
}
@@ -530,10 +685,64 @@ struct PathRegistrationState {
has_os_watcher: bool,
}
+/// The registered watch paths for one watcher mode, keyed by [`WatchKey`] so that
+/// add (dedup), remove, and dispatch share a single notion of path identity.
+#[derive(Default)]
+struct WatchPaths(HashMap<WatchKey, PathRegistrationState>);
+
+impl WatchPaths {
+ fn contains(&self, key: &WatchKey) -> bool {
+ self.0.contains_key(key)
+ }
+
+ fn get_mut(&mut self, key: &WatchKey) -> Option<&mut PathRegistrationState> {
+ self.0.get_mut(key)
+ }
+
+ fn entry(
+ &mut self,
+ key: WatchKey,
+ ) -> std::collections::hash_map::Entry<'_, WatchKey, PathRegistrationState> {
+ self.0.entry(key)
+ }
+
+ fn remove(&mut self, key: &WatchKey) {
+ self.0.remove(key);
+ }
+
+ /// True if a recursive registration on a strict ancestor already covers
+ /// `path`. Only poll watches and native macOS/Windows watches are recursive.
+ fn covered_by_recursive_ancestor(&self, path: &SanitizedPath, mode: WatcherMode) -> bool {
+ if mode != WatcherMode::Poll && !cfg!(any(target_os = "windows", target_os = "macos")) {
+ return false;
+ }
+ path.as_path().ancestors().skip(1).any(|ancestor| {
+ let ancestor = SanitizedPath::unchecked_new(ancestor);
+ self.0.contains_key(&WatchKey::exact(ancestor))
+ || self.0.contains_key(&WatchKey::folded(ancestor))
+ })
+ }
+
+ /// Collects the watcher ids of every registration whose directory is an
+ /// ancestor of (or equal to) `path`. Both exact and folded keys are probed,
+ /// so a real-cased event path matches a folded registration and vice versa.
+ fn watcher_ids_covering(&self, path: &SanitizedPath, ids: &mut Vec<WatcherRegistrationId>) {
+ for ancestor in path.as_path().ancestors() {
+ let ancestor = SanitizedPath::unchecked_new(ancestor);
+ if let Some(registration) = self.0.get(&WatchKey::exact(ancestor)) {
+ ids.extend_from_slice(&registration.watcher_ids);
+ }
+ if let Some(registration) = self.0.get(&WatchKey::folded(ancestor)) {
+ ids.extend_from_slice(&registration.watcher_ids);
+ }
+ }
+ }
+}
+
struct WatcherState {
watchers: HashMap<WatcherRegistrationId, WatcherRegistrationState>,
- native_path_registrations: HashMap<Arc<SanitizedPath>, PathRegistrationState>,
- poll_path_registrations: HashMap<Arc<SanitizedPath>, PathRegistrationState>,
+ native_path_registrations: WatchPaths,
+ poll_path_registrations: WatchPaths,
cooldown_until: Option<Instant>,
last_registration: WatcherRegistrationId,
}
@@ -544,10 +753,7 @@ impl WatcherState {
.is_some_and(|cooldown_until| cooldown_until > Instant::now())
}
- fn path_registrations(
- &mut self,
- mode: WatcherMode,
- ) -> &mut HashMap<Arc<SanitizedPath>, PathRegistrationState> {
+ fn path_registrations(&mut self, mode: WatcherMode) -> &mut WatchPaths {
match mode {
WatcherMode::Native => &mut self.native_path_registrations,
WatcherMode::Poll => &mut self.poll_path_registrations,
@@ -560,14 +766,14 @@ impl WatcherState {
) -> Option<(Arc<SanitizedPath>, WatcherMode)> {
let registration_state = self.watchers.remove(&id)?;
let path_registrations = self.path_registrations(registration_state.mode);
- let path_state = path_registrations.get_mut(&registration_state.path)?;
+ let path_state = path_registrations.get_mut(&registration_state.key)?;
path_state.watcher_ids.retain(|&existing| existing != id);
if !path_state.watcher_ids.is_empty() {
return None;
}
let was_actually_watched = path_state.has_os_watcher;
- path_registrations.remove(&registration_state.path);
+ path_registrations.remove(&registration_state.key);
was_actually_watched.then_some((registration_state.path, registration_state.mode))
}
@@ -606,15 +812,17 @@ impl GlobalWatcher {
&self,
path: Arc<std::path::Path>,
mode: WatcherMode,
+ case_insensitive: bool,
cb: impl Fn(&notify::Event) + Send + Sync + 'static,
) -> anyhow::Result<Option<WatcherRegistrationId>> {
let path = SanitizedPath::from_arc(path);
+ let key = WatchKey::for_registration(&path, case_insensitive);
let mut state = self.state.lock();
let (path_already_covered, path_already_registered) = {
let registrations_for_mode = state.path_registrations(mode);
(
- path_already_covered(path.as_ref(), registrations_for_mode, mode),
- registrations_for_mode.contains_key(&path),
+ registrations_for_mode.covered_by_recursive_ancestor(&path, mode),
+ registrations_for_mode.contains(&key),
)
};
@@ -640,13 +848,14 @@ impl GlobalWatcher {
let registration_state = WatcherRegistrationState {
callback: Arc::new(cb),
- path: path.clone(),
+ key: key.clone(),
+ path,
mode,
};
state.watchers.insert(id, registration_state);
state
.path_registrations(mode)
- .entry(path)
+ .entry(key)
.and_modify(|registration| registration.watcher_ids.push(id))
.or_insert_with(|| PathRegistrationState {
watcher_ids: vec![id],
@@ -705,12 +914,7 @@ impl GlobalWatcher {
let mut ids = Vec::new();
for path in &event.paths {
let sanitized = SanitizedPath::new(path);
- for ancestor in sanitized.as_path().ancestors() {
- let ancestor = SanitizedPath::unchecked_new(ancestor);
- if let Some(registration) = path_registrations.get(ancestor) {
- ids.extend_from_slice(&registration.watcher_ids);
- }
- }
+ path_registrations.watcher_ids_covering(sanitized, &mut ids);
}
ids.sort_unstable_by_key(|id| id.0);
ids.dedup();
@@ -837,19 +1041,6 @@ impl GlobalWatcher {
}
}
-fn path_already_covered(
- path: &SanitizedPath,
- path_registrations: &HashMap<Arc<SanitizedPath>, PathRegistrationState>,
- mode: WatcherMode,
-) -> bool {
- (mode == WatcherMode::Poll || cfg!(any(target_os = "windows", target_os = "macos")))
- && path
- .as_path()
- .ancestors()
- .skip(1)
- .any(|ancestor| path_registrations.contains_key(SanitizedPath::unchecked_new(ancestor)))
-}
-
fn is_max_files_watch_error(error: &anyhow::Error) -> bool {
error
.downcast_ref::<notify::Error>()
@@ -1009,11 +1200,11 @@ mod tests {
let child = Arc::<Path>::from(Path::new("/repo/foo.csproj"));
let parent_registration = watcher
- .add(parent.as_ref().into(), WatcherMode::Poll, |_| {})
+ .add(parent.as_ref().into(), WatcherMode::Poll, false, |_| {})
.expect("add parent watch")
.expect("parent watch registered");
let child_registration = watcher
- .add(child.as_ref().into(), WatcherMode::Poll, |_| {})
+ .add(child.as_ref().into(), WatcherMode::Poll, false, |_| {})
.expect("add covered child watch")
.expect("child watch registered");
@@ -1037,10 +1228,10 @@ mod tests {
let second_path = Arc::<Path>::from(Path::new("/repo/second"));
let first_registration = watcher
- .add(first_path.clone(), WatcherMode::Native, |_| {})
+ .add(first_path.clone(), WatcherMode::Native, false, |_| {})
.expect("native watch limit is handled");
let second_registration = watcher
- .add(second_path, WatcherMode::Native, |_| {})
+ .add(second_path, WatcherMode::Native, false, |_| {})
.expect("native watch limit backoff is handled");
assert!(first_registration.is_none());
@@ -1068,6 +1259,7 @@ mod tests {
.add(
Arc::<Path>::from(Path::new(dir)),
WatcherMode::Native,
+ false,
move |_| {
fired.lock().push(label.clone());
},
@@ -1105,6 +1297,153 @@ mod tests {
assert_eq!(got, vec!["/repo/a".to_owned(), "/repo/a/nested".to_owned()]);
}
+ fn fired_count() -> (
+ Arc<Mutex<usize>>,
+ impl Fn(&notify::Event) + Send + Sync + 'static,
+ ) {
+ let fired = Arc::new(Mutex::new(0usize));
+ let cb = {
+ let fired = fired.clone();
+ move |_: &notify::Event| *fired.lock() += 1
+ };
+ (fired, cb)
+ }
+
+ #[test]
+ fn watch_key_folds_case_but_keeps_exact_distinct() {
+ let mixed = SanitizedPath::new(Path::new("/Repo/Proj"));
+ let lower = SanitizedPath::new(Path::new("/repo/proj"));
+
+ // Folded keys collide regardless of casing; exact keys do not.
+ assert_eq!(WatchKey::folded(mixed), WatchKey::folded(lower));
+ assert_ne!(WatchKey::exact(mixed), WatchKey::exact(lower));
+ // Exact and folded live in different key spaces even for the same path.
+ assert_ne!(WatchKey::exact(mixed), WatchKey::folded(mixed));
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn watch_key_folds_unicode_normalization_on_macos() {
+ // "Café" precomposed (NFC) vs decomposed (NFD) are different byte
+ // sequences but the same directory on a normalization-insensitive volume.
+ let nfc = Path::new("/repo/Caf\u{00e9}");
+ let nfd = Path::new("/repo/Cafe\u{0301}");
+ assert_ne!(nfc, nfd);
+ assert_eq!(
+ WatchKey::folded(SanitizedPath::new(nfc)),
+ WatchKey::folded(SanitizedPath::new(nfd)),
+ );
+ }
+
+ #[test]
+ fn case_insensitive_registration_matches_differently_cased_event() {
+ let (fired, cb) = fired_count();
+ let watcher = test_watcher_with_backends(Some(Default::default()), None);
+ watcher
+ .add(
+ Path::new("/Repo/Project").into(),
+ WatcherMode::Native,
+ true,
+ cb,
+ )
+ .expect("add")
+ .expect("registered");
+
+ // Event arrives lowercased (as TSGO/macOS may report it).
+ watcher.dispatch(
+ WatcherMode::Native,
+ Ok(modify_event("/repo/project/file.txt")),
+ );
+ assert_eq!(*fired.lock(), 1);
+ }
+
+ #[test]
+ fn case_insensitive_registration_survives_case_only_rename() {
+ let (fired, cb) = fired_count();
+ let watcher = test_watcher_with_backends(Some(Default::default()), None);
+ watcher
+ .add(
+ Path::new("/Repo/Proj").into(),
+ WatcherMode::Native,
+ true,
+ cb,
+ )
+ .expect("add")
+ .expect("registered");
+
+ // The watched directory was renamed to a different casing; events now
+ // arrive under the new spelling.
+ watcher.dispatch(WatcherMode::Native, Ok(modify_event("/Repo/PROJ/file.txt")));
+ assert_eq!(*fired.lock(), 1);
+ }
+
+ #[test]
+ fn case_sensitive_registration_ignores_differently_cased_event() {
+ let (fired, cb) = fired_count();
+ let watcher = test_watcher_with_backends(Some(Default::default()), None);
+ watcher
+ .add(
+ Path::new("/Repo/proj").into(),
+ WatcherMode::Native,
+ false,
+ cb,
+ )
+ .expect("add")
+ .expect("registered");
+
+ // On a case-sensitive volume these are genuinely different directories.
+ watcher.dispatch(WatcherMode::Native, Ok(modify_event("/Repo/PROJ/file.txt")));
+ assert_eq!(*fired.lock(), 0);
+ }
+
+ #[test]
+ fn differently_cased_adds_dedupe_on_case_insensitive_volume() {
+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));
+ let watcher = test_watcher_with_backends(Some(backend.clone()), None);
+ watcher
+ .add(
+ Path::new("/Repo/Proj").into(),
+ WatcherMode::Native,
+ true,
+ |_| {},
+ )
+ .expect("add")
+ .expect("registered");
+ watcher
+ .add(
+ Path::new("/repo/proj").into(),
+ WatcherMode::Native,
+ true,
+ |_| {},
+ )
+ .expect("add")
+ .expect("registered");
+
+ // The second, differently-cased spelling reuses the same OS watch.
+ assert_eq!(backend.lock().watch_calls.len(), 1);
+ }
+
+ #[test]
+ fn recursive_parent_covers_differently_cased_child() {
+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));
+ let watcher = test_watcher(backend.clone());
+ watcher
+ .add(Path::new("/Repo").into(), WatcherMode::Poll, true, |_| {})
+ .expect("add")
+ .expect("registered");
+ watcher
+ .add(
+ Path::new("/repo/child").into(),
+ WatcherMode::Poll,
+ true,
+ |_| {},
+ )
+ .expect("add");
+
+ // The child is covered by the recursive parent despite the case mismatch.
+ assert_eq!(backend.lock().watch_calls, vec![PathBuf::from("/Repo")]);
+ }
+
#[test]
fn rescan_event_broadcasts_to_all_registrations_of_the_same_mode() {
let (watcher, fired) = recording_watcher();
@@ -1141,6 +1480,7 @@ mod tests {
.add(
Arc::<Path>::from(Path::new("C:\\repo\\src")),
WatcherMode::Native,
+ false,
move |_| fired.lock().push(()),
)
.expect("add watch")
diff --git a/crates/fs/tests/integration/fs_tests.rs b/crates/fs/tests/integration/fs_tests.rs
index d86fadd46db..6f690be8967 100644
--- a/crates/fs/tests/integration/fs_tests.rs
+++ b/crates/fs/tests/integration/fs_tests.rs
@@ -5,6 +5,8 @@ use std::{
ffi::OsString,
io::Write,
path::{Path, PathBuf},
+ pin::Pin,
+ sync::Arc,
time::Duration,
};
@@ -828,6 +830,257 @@ async fn test_fake_fs_restore(executor: BackgroundExecutor) {
assert_eq!(fs.trash_entries().len(), 2);
}
+/// Create a directory symlink (`link` -> `target`) in a cross-platform way.
+///
+/// Returns `Err` when the platform cannot create symlinks (e.g. Windows without
+/// the create-symlink privilege), so callers can skip a scenario gracefully
+/// rather than failing the whole test.
+fn make_dir_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(target, link)
+ }
+ #[cfg(windows)]
+ {
+ std::os::windows::fs::symlink_dir(target, link)
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ let _ = (target, link);
+ Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "symlinks are not supported on this platform",
+ ))
+ }
+}
+
+/// Waits up to `timeout` for `events` to deliver something that covers the
+/// written file: either a path event whose path satisfies `path_matches`, or a
+/// `Rescan` (which tells the consumer to re-scan this watcher's whole tree, so
+/// it would discover the file anyway). Returns `false` if nothing relevant
+/// arrives before the timeout.
+async fn watcher_delivered_event(
+ events: &mut (impl futures::Stream<Item = Vec<PathEvent>> + Unpin),
+ executor: &BackgroundExecutor,
+ timeout: Duration,
+ path_matches: &(dyn Fn(&Path) -> bool + Send + Sync),
+) -> bool {
+ let timeout = executor.timer(timeout).fuse();
+ futures::pin_mut!(timeout);
+ loop {
+ futures::select_biased! {
+ batch = events.next().fuse() => {
+ let Some(batch) = batch else { return false };
+ let covered = batch.iter().any(|event| {
+ path_matches(&event.path) || event.kind == Some(PathEventKind::Rescan)
+ });
+ if covered {
+ return true;
+ }
+ }
+ _ = timeout => return false,
+ }
+ }
+}
+
+/// Exercises a spread of real watchers whose registered watch path is spelled
+/// differently from the path the OS reports events under. Each scenario watches
+/// some directory and then mutates the on-disk file; a correct watcher must
+/// deliver an event (or a rescan) for every scenario.
+///
+/// This asserts the residual path-aliasing bugs that real-casing the watch root
+/// at add-time does NOT fix. The headline failure is `symlink_ancestor`:
+/// watching a path that traverses a symlinked ancestor. On macOS FSEvents
+/// reports events under the resolved real path, which no longer has the
+/// symlinked prefix the watch root was registered with, so the events are
+/// filtered out and never delivered.
+///
+/// Platform notes (the test runs everywhere but scenarios self-skip when they
+/// cannot apply):
+/// - Case scenarios require a case-insensitive filesystem (macOS/Windows
+/// default; case-sensitive Linux/APFS skip them).
+/// - Symlink scenarios require symlink creation (skipped on Windows without the
+/// privilege).
+/// - `symlink_ancestor` fails on macOS (FSEvents canonicalizes) but is expected
+/// to pass on Linux (notify reconstructs paths from the watch path you pass),
+/// which is itself a useful demonstration that this is an FSEvents-specific
+/// bug.
+#[gpui::test]
+async fn test_realfs_watch_aliased_watch_paths_deliver_events(
+ executor: BackgroundExecutor,
+ cx: &mut TestAppContext,
+) {
+ cx.executor().allow_parking();
+
+ let fs = RealFs::new(None, executor.clone());
+ let temp_dir = TempDir::new().expect("create temp dir");
+ let root = temp_dir.path().to_path_buf();
+ let latency = Duration::from_millis(10);
+
+ // Probe the real filesystem for case sensitivity rather than guessing from
+ // the platform.
+ std::fs::create_dir_all(root.join("CaseProbe")).expect("create case probe dir");
+ let case_insensitive = root.join("caseprobe").exists();
+ eprintln!("filesystem is case-insensitive: {case_insensitive}");
+
+ struct Scenario {
+ name: &'static str,
+ events: Pin<Box<dyn Send + futures::Stream<Item = Vec<PathEvent>>>>,
+ _watcher: Arc<dyn Watcher>,
+ path_matches: Box<dyn Fn(&Path) -> bool + Send + Sync>,
+ action: Option<Box<dyn FnOnce() + Send>>,
+ }
+
+ let mut scenarios: Vec<Scenario> = Vec::new();
+ let mut skipped: Vec<String> = Vec::new();
+
+ // --- Headline residual bug: watch path traverses a symlinked ancestor. ---
+ {
+ let real = root.join("ancestor_real");
+ let inner = real.join("inner");
+ std::fs::create_dir_all(&inner).expect("create symlinked-ancestor target");
+ let link = root.join("ancestor_link");
+ match make_dir_symlink(&real, &link) {
+ Ok(()) => {
+ let (events, watcher) = fs.watch(&link.join("inner"), latency).await;
+ let file = inner.join("symlink_ancestor.txt");
+ scenarios.push(Scenario {
+ name: "symlink_ancestor",
+ events,
+ _watcher: watcher,
+ path_matches: Box::new(|path| {
+ path.ends_with(Path::new("inner/symlink_ancestor.txt"))
+ }),
+ action: Some(Box::new(move || {
+ std::fs::write(&file, b"x").expect("write symlink-ancestor file");
+ })),
+ });
+ }
+ Err(error) => skipped.push(format!("symlink_ancestor (cannot symlink: {error})")),
+ }
+ }
+
+ // --- Control: watching a symlinked root IS handled (RealFs::watch follows
+ // the root symlink and also watches the target). ---
+ {
+ let real = root.join("root_real");
+ std::fs::create_dir_all(&real).expect("create symlinked-root target");
+ let link = root.join("root_link");
+ match make_dir_symlink(&real, &link) {
+ Ok(()) => {
+ let (events, watcher) = fs.watch(&link, latency).await;
+ let file = real.join("symlink_root.txt");
+ scenarios.push(Scenario {
+ name: "symlink_root",
+ events,
+ _watcher: watcher,
+ path_matches: Box::new(|path| path.ends_with(Path::new("symlink_root.txt"))),
+ action: Some(Box::new(move || {
+ std::fs::write(&file, b"x").expect("write symlink-root file");
+ })),
+ });
+ }
+ Err(error) => skipped.push(format!("symlink_root (cannot symlink: {error})")),
+ }
+ }
+
+ // --- Control: wrong-case watch root (the originally-reported bug, which the
+ // real-casing fix already addresses). ---
+ if case_insensitive {
+ let real = root.join("CaseAlpha");
+ std::fs::create_dir_all(&real).expect("create wrong-case root");
+ let lower = PathBuf::from(real.to_string_lossy().to_lowercase());
+ let (events, watcher) = fs.watch(&lower, latency).await;
+ let file = real.join("alpha.txt");
+ scenarios.push(Scenario {
+ name: "wrong_case_root",
+ events,
+ _watcher: watcher,
+ path_matches: Box::new(|path| path.ends_with(Path::new("alpha.txt"))),
+ action: Some(Box::new(move || {
+ std::fs::write(&file, b"x").expect("write wrong-case-root file");
+ })),
+ });
+ } else {
+ skipped.push("wrong_case_root (case-sensitive fs)".to_owned());
+ }
+
+ // --- Control: wrong-case nested watch path. ---
+ if case_insensitive {
+ let real = root.join("CaseBravo").join("Inner");
+ std::fs::create_dir_all(&real).expect("create wrong-case nested dir");
+ let lower = PathBuf::from(real.to_string_lossy().to_lowercase());
+ let (events, watcher) = fs.watch(&lower, latency).await;
+ let file = real.join("bravo.txt");
+ scenarios.push(Scenario {
+ name: "nested_wrong_case",
+ events,
+ _watcher: watcher,
+ path_matches: Box::new(|path| path.ends_with(Path::new("bravo.txt"))),
+ action: Some(Box::new(move || {
+ std::fs::write(&file, b"x").expect("write nested-wrong-case file");
+ })),
+ });
+ } else {
+ skipped.push("nested_wrong_case (case-sensitive fs)".to_owned());
+ }
+
+ // --- Residual bug: the watched root is renamed to a different casing after
+ // the watch is established, so later events arrive under a spelling the
+ // registered (old-case) root no longer matches. ---
+ if case_insensitive {
+ let real = root.join("CaseEcho");
+ std::fs::create_dir_all(&real).expect("create case-rename dir");
+ let (events, watcher) = fs.watch(&real, latency).await;
+ let renamed = root.join("CASEECHO");
+ let file = renamed.join("echo.txt");
+ scenarios.push(Scenario {
+ name: "case_rename_root",
+ events,
+ _watcher: watcher,
+ path_matches: Box::new(|path| path.ends_with(Path::new("echo.txt"))),
+ action: Some(Box::new(move || {
+ std::fs::rename(&real, &renamed).expect("case-only rename of watched root");
+ std::fs::write(&file, b"x").expect("write case-rename file");
+ })),
+ });
+ } else {
+ skipped.push("case_rename_root (case-sensitive fs)".to_owned());
+ }
+
+ // Let every watch settle before mutating, then perform all mutations.
+ executor.timer(Duration::from_millis(250)).await;
+ for scenario in &mut scenarios {
+ if let Some(action) = scenario.action.take() {
+ action();
+ }
+ }
+
+ let mut failures = Vec::new();
+ for scenario in &mut scenarios {
+ let delivered = watcher_delivered_event(
+ &mut scenario.events,
+ &executor,
+ Duration::from_secs(3),
+ scenario.path_matches.as_ref(),
+ )
+ .await;
+ eprintln!("scenario {}: delivered={delivered}", scenario.name);
+ if !delivered {
+ failures.push(scenario.name);
+ }
+ }
+
+ for name in &skipped {
+ eprintln!("scenario skipped: {name}");
+ }
+
+ assert!(
+ failures.is_empty(),
+ "watchers failed to deliver events for {failures:?} (skipped: {skipped:?})"
+ );
+}
+
#[gpui::test]
#[ignore = "stress test; run explicitly when needed"]
async fn test_realfs_watch_stress_reports_missed_paths(
diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rs
index b4b955ca872..55d161aea6f 100644
--- a/crates/worktree/src/worktree.rs
+++ b/crates/worktree/src/worktree.rs
@@ -4594,6 +4594,11 @@ impl BackgroundScanner {
for (ix, event) in events.iter().enumerate() {
let abs_path = SanitizedPath::new(&event.path);
+ // TODO: this strips the root case-sensitively, so on a case-insensitive
+ // volume an event whose casing differs from the canonical root is
+ // dropped. Once `fs` exposes per-volume case-sensitivity (e.g. on the
+ // `Fs` trait, with a per-volume cache + `FakeFs` support), fold this
+ // comparison on case-insensitive volumes.
let relative_path = if let Ok(path) = abs_path.strip_prefix(&root_canonical_path)
&& let Ok(path) = RelPath::new(path, PathStyle::local())
{