1#[cfg(target_os = "macos")]
2mod mac_watcher;
3
4#[cfg(any(target_os = "linux", target_os = "freebsd"))]
5pub mod linux_watcher;
6
7use anyhow::{anyhow, Result};
8use git::GitHostingProviderRegistry;
9
10#[cfg(any(target_os = "linux", target_os = "freebsd"))]
11use ashpd::desktop::trash;
12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
13use std::fs::File;
14#[cfg(unix)]
15use std::os::fd::AsFd;
16#[cfg(unix)]
17use std::os::fd::AsRawFd;
18
19#[cfg(unix)]
20use std::os::unix::fs::MetadataExt;
21
22#[cfg(unix)]
23use std::os::unix::fs::FileTypeExt;
24
25use async_tar::Archive;
26use futures::{future::BoxFuture, AsyncRead, Stream, StreamExt};
27use git::repository::{GitRepository, RealGitRepository};
28use gpui::{AppContext, Global, ReadGlobal};
29use rope::Rope;
30use serde::{Deserialize, Serialize};
31use smol::io::AsyncWriteExt;
32use std::{
33 io::{self, Write},
34 path::{Component, Path, PathBuf},
35 pin::Pin,
36 sync::Arc,
37 time::{Duration, SystemTime, UNIX_EPOCH},
38};
39use tempfile::{NamedTempFile, TempDir};
40use text::LineEnding;
41use util::ResultExt;
42
43#[cfg(any(test, feature = "test-support"))]
44use collections::{btree_map, BTreeMap};
45#[cfg(any(test, feature = "test-support"))]
46use git::repository::{FakeGitRepositoryState, GitFileStatus};
47#[cfg(any(test, feature = "test-support"))]
48use parking_lot::Mutex;
49#[cfg(any(test, feature = "test-support"))]
50use smol::io::AsyncReadExt;
51#[cfg(any(test, feature = "test-support"))]
52use std::ffi::OsStr;
53
54pub trait Watcher: Send + Sync {
55 fn add(&self, path: &Path) -> Result<()>;
56 fn remove(&self, path: &Path) -> Result<()>;
57}
58
59#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
60pub enum PathEventKind {
61 Removed,
62 Created,
63 Changed,
64}
65
66#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
67pub struct PathEvent {
68 pub path: PathBuf,
69 pub kind: Option<PathEventKind>,
70}
71
72impl From<PathEvent> for PathBuf {
73 fn from(event: PathEvent) -> Self {
74 event.path
75 }
76}
77
78#[async_trait::async_trait]
79pub trait Fs: Send + Sync {
80 async fn create_dir(&self, path: &Path) -> Result<()>;
81 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
82 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
83 async fn create_file_with(
84 &self,
85 path: &Path,
86 content: Pin<&mut (dyn AsyncRead + Send)>,
87 ) -> Result<()>;
88 async fn extract_tar_file(
89 &self,
90 path: &Path,
91 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
92 ) -> Result<()>;
93 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
94 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
95 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
96 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
97 self.remove_dir(path, options).await
98 }
99 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
100 async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
101 self.remove_file(path, options).await
102 }
103 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
104 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
105 async fn load(&self, path: &Path) -> Result<String> {
106 Ok(String::from_utf8(self.load_bytes(path).await?)?)
107 }
108 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
109 async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
110 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
111 async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
112 async fn is_file(&self, path: &Path) -> bool;
113 async fn is_dir(&self, path: &Path) -> bool;
114 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
115 async fn read_link(&self, path: &Path) -> Result<PathBuf>;
116 async fn read_dir(
117 &self,
118 path: &Path,
119 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
120
121 async fn watch(
122 &self,
123 path: &Path,
124 latency: Duration,
125 ) -> (
126 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
127 Arc<dyn Watcher>,
128 );
129
130 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>>;
131 fn is_fake(&self) -> bool;
132 async fn is_case_sensitive(&self) -> Result<bool>;
133
134 #[cfg(any(test, feature = "test-support"))]
135 fn as_fake(&self) -> &FakeFs {
136 panic!("called as_fake on a real fs");
137 }
138}
139
140struct GlobalFs(Arc<dyn Fs>);
141
142impl Global for GlobalFs {}
143
144impl dyn Fs {
145 /// Returns the global [`Fs`].
146 pub fn global(cx: &AppContext) -> Arc<Self> {
147 GlobalFs::global(cx).0.clone()
148 }
149
150 /// Sets the global [`Fs`].
151 pub fn set_global(fs: Arc<Self>, cx: &mut AppContext) {
152 cx.set_global(GlobalFs(fs));
153 }
154}
155
156#[derive(Copy, Clone, Default)]
157pub struct CreateOptions {
158 pub overwrite: bool,
159 pub ignore_if_exists: bool,
160}
161
162#[derive(Copy, Clone, Default)]
163pub struct CopyOptions {
164 pub overwrite: bool,
165 pub ignore_if_exists: bool,
166}
167
168#[derive(Copy, Clone, Default)]
169pub struct RenameOptions {
170 pub overwrite: bool,
171 pub ignore_if_exists: bool,
172}
173
174#[derive(Copy, Clone, Default)]
175pub struct RemoveOptions {
176 pub recursive: bool,
177 pub ignore_if_not_exists: bool,
178}
179
180#[derive(Copy, Clone, Debug)]
181pub struct Metadata {
182 pub inode: u64,
183 pub mtime: MTime,
184 pub is_symlink: bool,
185 pub is_dir: bool,
186 pub len: u64,
187 pub is_fifo: bool,
188}
189
190/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
191/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
192/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
193/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
194///
195/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
196#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
197#[serde(transparent)]
198pub struct MTime(SystemTime);
199
200impl MTime {
201 /// Conversion intended for persistence and testing.
202 pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
203 MTime(UNIX_EPOCH + Duration::new(secs, nanos))
204 }
205
206 /// Conversion intended for persistence.
207 pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
208 self.0
209 .duration_since(UNIX_EPOCH)
210 .ok()
211 .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
212 }
213
214 /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
215 /// "_for_user" is to discourage misuse - this method should not be used when making decisions
216 /// about file dirtiness.
217 pub fn timestamp_for_user(self) -> SystemTime {
218 self.0
219 }
220
221 /// Temporary method to split out the behavior changes from introduction of this newtype.
222 pub fn bad_is_greater_than(self, other: MTime) -> bool {
223 self.0 > other.0
224 }
225}
226
227impl From<proto::Timestamp> for MTime {
228 fn from(timestamp: proto::Timestamp) -> Self {
229 MTime(timestamp.into())
230 }
231}
232
233impl From<MTime> for proto::Timestamp {
234 fn from(mtime: MTime) -> Self {
235 mtime.0.into()
236 }
237}
238
239#[derive(Default)]
240pub struct RealFs {
241 git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
242 git_binary_path: Option<PathBuf>,
243}
244
245pub trait FileHandle: Send + Sync + std::fmt::Debug {
246 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
247}
248
249impl FileHandle for std::fs::File {
250 #[cfg(target_os = "macos")]
251 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
252 use std::{
253 ffi::{CStr, OsStr},
254 os::unix::ffi::OsStrExt,
255 };
256
257 let fd = self.as_fd();
258 let mut path_buf: [libc::c_char; libc::PATH_MAX as usize] = [0; libc::PATH_MAX as usize];
259
260 let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
261 if result == -1 {
262 anyhow::bail!("fcntl returned -1".to_string());
263 }
264
265 let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr()) };
266 let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
267 Ok(path)
268 }
269
270 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
271 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
272 let fd = self.as_fd();
273 let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
274 let new_path = std::fs::read_link(fd_path)?;
275 if new_path
276 .file_name()
277 .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
278 {
279 anyhow::bail!("file was deleted")
280 };
281
282 Ok(new_path)
283 }
284
285 #[cfg(target_os = "windows")]
286 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
287 anyhow::bail!("unimplemented")
288 }
289}
290
291pub struct RealWatcher {}
292
293impl RealFs {
294 pub fn new(
295 git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
296 git_binary_path: Option<PathBuf>,
297 ) -> Self {
298 Self {
299 git_hosting_provider_registry,
300 git_binary_path,
301 }
302 }
303}
304
305#[async_trait::async_trait]
306impl Fs for RealFs {
307 async fn create_dir(&self, path: &Path) -> Result<()> {
308 Ok(smol::fs::create_dir_all(path).await?)
309 }
310
311 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
312 #[cfg(unix)]
313 smol::fs::unix::symlink(target, path).await?;
314
315 #[cfg(windows)]
316 if smol::fs::metadata(&target).await?.is_dir() {
317 smol::fs::windows::symlink_dir(target, path).await?
318 } else {
319 smol::fs::windows::symlink_file(target, path).await?
320 }
321
322 Ok(())
323 }
324
325 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
326 let mut open_options = smol::fs::OpenOptions::new();
327 open_options.write(true).create(true);
328 if options.overwrite {
329 open_options.truncate(true);
330 } else if !options.ignore_if_exists {
331 open_options.create_new(true);
332 }
333 open_options.open(path).await?;
334 Ok(())
335 }
336
337 async fn create_file_with(
338 &self,
339 path: &Path,
340 content: Pin<&mut (dyn AsyncRead + Send)>,
341 ) -> Result<()> {
342 let mut file = smol::fs::File::create(&path).await?;
343 futures::io::copy(content, &mut file).await?;
344 Ok(())
345 }
346
347 async fn extract_tar_file(
348 &self,
349 path: &Path,
350 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
351 ) -> Result<()> {
352 content.unpack(path).await?;
353 Ok(())
354 }
355
356 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
357 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
358 if options.ignore_if_exists {
359 return Ok(());
360 } else {
361 return Err(anyhow!("{target:?} already exists"));
362 }
363 }
364
365 smol::fs::copy(source, target).await?;
366 Ok(())
367 }
368
369 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
370 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
371 if options.ignore_if_exists {
372 return Ok(());
373 } else {
374 return Err(anyhow!("{target:?} already exists"));
375 }
376 }
377
378 smol::fs::rename(source, target).await?;
379 Ok(())
380 }
381
382 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
383 let result = if options.recursive {
384 smol::fs::remove_dir_all(path).await
385 } else {
386 smol::fs::remove_dir(path).await
387 };
388 match result {
389 Ok(()) => Ok(()),
390 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
391 Ok(())
392 }
393 Err(err) => Err(err)?,
394 }
395 }
396
397 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
398 #[cfg(windows)]
399 if let Ok(Some(metadata)) = self.metadata(path).await {
400 if metadata.is_symlink && metadata.is_dir {
401 self.remove_dir(
402 path,
403 RemoveOptions {
404 recursive: false,
405 ignore_if_not_exists: true,
406 },
407 )
408 .await?;
409 return Ok(());
410 }
411 }
412
413 match smol::fs::remove_file(path).await {
414 Ok(()) => Ok(()),
415 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
416 Ok(())
417 }
418 Err(err) => Err(err)?,
419 }
420 }
421
422 #[cfg(target_os = "macos")]
423 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
424 use cocoa::{
425 base::{id, nil},
426 foundation::{NSAutoreleasePool, NSString},
427 };
428 use objc::{class, msg_send, sel, sel_impl};
429
430 unsafe {
431 unsafe fn ns_string(string: &str) -> id {
432 NSString::alloc(nil).init_str(string).autorelease()
433 }
434
435 let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
436 let array: id = msg_send![class!(NSArray), arrayWithObject: url];
437 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
438
439 let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
440 }
441 Ok(())
442 }
443
444 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
445 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
446 let file = File::open(path)?;
447 match trash::trash_file(&file.as_fd()).await {
448 Ok(_) => Ok(()),
449 Err(err) => Err(anyhow::Error::new(err)),
450 }
451 }
452
453 #[cfg(target_os = "windows")]
454 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
455 use util::paths::SanitizedPath;
456 use windows::{
457 core::HSTRING,
458 Storage::{StorageDeleteOption, StorageFile},
459 };
460 // todo(windows)
461 // When new version of `windows-rs` release, make this operation `async`
462 let path = SanitizedPath::from(path.canonicalize()?);
463 let path_string = path.to_string();
464 let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
465 file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
466 Ok(())
467 }
468
469 #[cfg(target_os = "macos")]
470 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
471 self.trash_file(path, options).await
472 }
473
474 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
475 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
476 self.trash_file(path, options).await
477 }
478
479 #[cfg(target_os = "windows")]
480 async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
481 use util::paths::SanitizedPath;
482 use windows::{
483 core::HSTRING,
484 Storage::{StorageDeleteOption, StorageFolder},
485 };
486
487 // todo(windows)
488 // When new version of `windows-rs` release, make this operation `async`
489 let path = SanitizedPath::from(path.canonicalize()?);
490 let path_string = path.to_string();
491 let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
492 folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
493 Ok(())
494 }
495
496 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
497 Ok(Box::new(std::fs::File::open(path)?))
498 }
499
500 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
501 Ok(Arc::new(std::fs::File::open(path)?))
502 }
503
504 async fn load(&self, path: &Path) -> Result<String> {
505 let path = path.to_path_buf();
506 let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
507 Ok(text)
508 }
509 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
510 let path = path.to_path_buf();
511 let bytes = smol::unblock(|| std::fs::read(path)).await?;
512 Ok(bytes)
513 }
514
515 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
516 smol::unblock(move || {
517 let mut tmp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
518 // Use the directory of the destination as temp dir to avoid
519 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
520 // See https://github.com/zed-industries/zed/pull/8437 for more details.
521 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
522 } else if cfg!(target_os = "windows") {
523 // If temp dir is set to a different drive than the destination,
524 // we receive error:
525 //
526 // failed to persist temporary file:
527 // The system cannot move the file to a different disk drive. (os error 17)
528 //
529 // So we use the directory of the destination as a temp dir to avoid it.
530 // https://github.com/zed-industries/zed/issues/16571
531 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
532 } else {
533 NamedTempFile::new()
534 }?;
535 tmp_file.write_all(data.as_bytes())?;
536 tmp_file.persist(path)?;
537 Ok::<(), anyhow::Error>(())
538 })
539 .await?;
540
541 Ok(())
542 }
543
544 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
545 let buffer_size = text.summary().len.min(10 * 1024);
546 if let Some(path) = path.parent() {
547 self.create_dir(path).await?;
548 }
549 let file = smol::fs::File::create(path).await?;
550 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
551 for chunk in chunks(text, line_ending) {
552 writer.write_all(chunk.as_bytes()).await?;
553 }
554 writer.flush().await?;
555 Ok(())
556 }
557
558 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
559 Ok(smol::fs::canonicalize(path).await?)
560 }
561
562 async fn is_file(&self, path: &Path) -> bool {
563 smol::fs::metadata(path)
564 .await
565 .map_or(false, |metadata| metadata.is_file())
566 }
567
568 async fn is_dir(&self, path: &Path) -> bool {
569 smol::fs::metadata(path)
570 .await
571 .map_or(false, |metadata| metadata.is_dir())
572 }
573
574 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
575 let symlink_metadata = match smol::fs::symlink_metadata(path).await {
576 Ok(metadata) => metadata,
577 Err(err) => {
578 return match (err.kind(), err.raw_os_error()) {
579 (io::ErrorKind::NotFound, _) => Ok(None),
580 (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
581 _ => Err(anyhow::Error::new(err)),
582 }
583 }
584 };
585
586 let is_symlink = symlink_metadata.file_type().is_symlink();
587 let metadata = if is_symlink {
588 smol::fs::metadata(path).await?
589 } else {
590 symlink_metadata
591 };
592
593 #[cfg(unix)]
594 let inode = metadata.ino();
595
596 #[cfg(windows)]
597 let inode = file_id(path).await?;
598
599 #[cfg(windows)]
600 let is_fifo = false;
601
602 #[cfg(unix)]
603 let is_fifo = metadata.file_type().is_fifo();
604
605 Ok(Some(Metadata {
606 inode,
607 mtime: MTime(metadata.modified().unwrap()),
608 len: metadata.len(),
609 is_symlink,
610 is_dir: metadata.file_type().is_dir(),
611 is_fifo,
612 }))
613 }
614
615 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
616 let path = smol::fs::read_link(path).await?;
617 Ok(path)
618 }
619
620 async fn read_dir(
621 &self,
622 path: &Path,
623 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
624 let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
625 Ok(entry) => Ok(entry.path()),
626 Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
627 });
628 Ok(Box::pin(result))
629 }
630
631 #[cfg(target_os = "macos")]
632 async fn watch(
633 &self,
634 path: &Path,
635 latency: Duration,
636 ) -> (
637 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
638 Arc<dyn Watcher>,
639 ) {
640 use fsevent::StreamFlags;
641
642 let (events_tx, events_rx) = smol::channel::unbounded();
643 let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
644 let watcher = Arc::new(mac_watcher::MacWatcher::new(
645 events_tx,
646 Arc::downgrade(&handles),
647 latency,
648 ));
649 watcher.add(path).expect("handles can't be dropped");
650
651 (
652 Box::pin(
653 events_rx
654 .map(|events| {
655 events
656 .into_iter()
657 .map(|event| {
658 let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
659 Some(PathEventKind::Removed)
660 } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
661 Some(PathEventKind::Created)
662 } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
663 Some(PathEventKind::Changed)
664 } else {
665 None
666 };
667 PathEvent {
668 path: event.path,
669 kind,
670 }
671 })
672 .collect()
673 })
674 .chain(futures::stream::once(async move {
675 drop(handles);
676 vec![]
677 })),
678 ),
679 watcher,
680 )
681 }
682
683 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
684 async fn watch(
685 &self,
686 path: &Path,
687 latency: Duration,
688 ) -> (
689 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
690 Arc<dyn Watcher>,
691 ) {
692 use parking_lot::Mutex;
693
694 let (tx, rx) = smol::channel::unbounded();
695 let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
696 let watcher = Arc::new(linux_watcher::LinuxWatcher::new(tx, pending_paths.clone()));
697
698 watcher.add(&path).ok(); // Ignore "file doesn't exist error" and rely on parent watcher.
699 if let Some(parent) = path.parent() {
700 // watch the parent dir so we can tell when settings.json is created
701 watcher.add(parent).log_err();
702 }
703
704 // Check if path is a symlink and follow the target parent
705 if let Some(target) = self.read_link(&path).await.ok() {
706 watcher.add(&target).ok();
707 if let Some(parent) = target.parent() {
708 watcher.add(parent).log_err();
709 }
710 }
711
712 (
713 Box::pin(rx.filter_map({
714 let watcher = watcher.clone();
715 move |_| {
716 let _ = watcher.clone();
717 let pending_paths = pending_paths.clone();
718 async move {
719 smol::Timer::after(latency).await;
720 let paths = std::mem::take(&mut *pending_paths.lock());
721 (!paths.is_empty()).then_some(paths)
722 }
723 }
724 })),
725 watcher,
726 )
727 }
728
729 #[cfg(target_os = "windows")]
730 async fn watch(
731 &self,
732 path: &Path,
733 _latency: Duration,
734 ) -> (
735 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
736 Arc<dyn Watcher>,
737 ) {
738 use notify::{EventKind, Watcher};
739
740 let (tx, rx) = smol::channel::unbounded();
741
742 let mut file_watcher = notify::recommended_watcher({
743 let tx = tx.clone();
744 move |event: Result<notify::Event, _>| {
745 if let Some(event) = event.log_err() {
746 let kind = match event.kind {
747 EventKind::Create(_) => Some(PathEventKind::Created),
748 EventKind::Modify(_) => Some(PathEventKind::Changed),
749 EventKind::Remove(_) => Some(PathEventKind::Removed),
750 _ => None,
751 };
752
753 tx.try_send(
754 event
755 .paths
756 .into_iter()
757 .map(|path| PathEvent { path, kind })
758 .collect::<Vec<_>>(),
759 )
760 .ok();
761 }
762 }
763 })
764 .expect("Could not start file watcher");
765
766 file_watcher
767 .watch(path, notify::RecursiveMode::Recursive)
768 .log_err();
769
770 (
771 Box::pin(rx.chain(futures::stream::once(async move {
772 drop(file_watcher);
773 vec![]
774 }))),
775 Arc::new(RealWatcher {}),
776 )
777 }
778
779 fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
780 let repo = git2::Repository::open(dotgit_path).log_err()?;
781 Some(Arc::new(RealGitRepository::new(
782 repo,
783 self.git_binary_path.clone(),
784 self.git_hosting_provider_registry.clone(),
785 )))
786 }
787
788 fn is_fake(&self) -> bool {
789 false
790 }
791
792 /// Checks whether the file system is case sensitive by attempting to create two files
793 /// that have the same name except for the casing.
794 ///
795 /// It creates both files in a temporary directory it removes at the end.
796 async fn is_case_sensitive(&self) -> Result<bool> {
797 let temp_dir = TempDir::new()?;
798 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
799 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
800
801 let create_opts = CreateOptions {
802 overwrite: false,
803 ignore_if_exists: false,
804 };
805
806 // Create file1
807 self.create_file(&test_file_1, create_opts).await?;
808
809 // Now check whether it's possible to create file2
810 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
811 Ok(_) => Ok(true),
812 Err(e) => {
813 if let Some(io_error) = e.downcast_ref::<io::Error>() {
814 if io_error.kind() == io::ErrorKind::AlreadyExists {
815 Ok(false)
816 } else {
817 Err(e)
818 }
819 } else {
820 Err(e)
821 }
822 }
823 };
824
825 temp_dir.close()?;
826 case_sensitive
827 }
828}
829
830#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
831impl Watcher for RealWatcher {
832 fn add(&self, _: &Path) -> Result<()> {
833 Ok(())
834 }
835
836 fn remove(&self, _: &Path) -> Result<()> {
837 Ok(())
838 }
839}
840
841#[cfg(any(test, feature = "test-support"))]
842pub struct FakeFs {
843 // Use an unfair lock to ensure tests are deterministic.
844 state: Mutex<FakeFsState>,
845 executor: gpui::BackgroundExecutor,
846}
847
848#[cfg(any(test, feature = "test-support"))]
849struct FakeFsState {
850 root: Arc<Mutex<FakeFsEntry>>,
851 next_inode: u64,
852 next_mtime: SystemTime,
853 git_event_tx: smol::channel::Sender<PathBuf>,
854 event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
855 events_paused: bool,
856 buffered_events: Vec<PathEvent>,
857 metadata_call_count: usize,
858 read_dir_call_count: usize,
859 moves: std::collections::HashMap<u64, PathBuf>,
860}
861
862#[cfg(any(test, feature = "test-support"))]
863#[derive(Debug)]
864enum FakeFsEntry {
865 File {
866 inode: u64,
867 mtime: MTime,
868 len: u64,
869 content: Vec<u8>,
870 },
871 Dir {
872 inode: u64,
873 mtime: MTime,
874 len: u64,
875 entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
876 git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
877 },
878 Symlink {
879 target: PathBuf,
880 },
881}
882
883#[cfg(any(test, feature = "test-support"))]
884impl FakeFsState {
885 fn get_and_increment_mtime(&mut self) -> MTime {
886 let mtime = self.next_mtime;
887 self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
888 MTime(mtime)
889 }
890
891 fn get_and_increment_inode(&mut self) -> u64 {
892 let inode = self.next_inode;
893 self.next_inode += 1;
894 inode
895 }
896
897 fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
898 Ok(self
899 .try_read_path(target, true)
900 .ok_or_else(|| {
901 anyhow!(io::Error::new(
902 io::ErrorKind::NotFound,
903 format!("not found: {}", target.display())
904 ))
905 })?
906 .0)
907 }
908
909 fn try_read_path(
910 &self,
911 target: &Path,
912 follow_symlink: bool,
913 ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
914 let mut path = target.to_path_buf();
915 let mut canonical_path = PathBuf::new();
916 let mut entry_stack = Vec::new();
917 'outer: loop {
918 let mut path_components = path.components().peekable();
919 let mut prefix = None;
920 while let Some(component) = path_components.next() {
921 match component {
922 Component::Prefix(prefix_component) => prefix = Some(prefix_component),
923 Component::RootDir => {
924 entry_stack.clear();
925 entry_stack.push(self.root.clone());
926 canonical_path.clear();
927 match prefix {
928 Some(prefix_component) => {
929 canonical_path = PathBuf::from(prefix_component.as_os_str());
930 // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
931 canonical_path.push(std::path::MAIN_SEPARATOR_STR);
932 }
933 None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
934 }
935 }
936 Component::CurDir => {}
937 Component::ParentDir => {
938 entry_stack.pop()?;
939 canonical_path.pop();
940 }
941 Component::Normal(name) => {
942 let current_entry = entry_stack.last().cloned()?;
943 let current_entry = current_entry.lock();
944 if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
945 let entry = entries.get(name.to_str().unwrap()).cloned()?;
946 if path_components.peek().is_some() || follow_symlink {
947 let entry = entry.lock();
948 if let FakeFsEntry::Symlink { target, .. } = &*entry {
949 let mut target = target.clone();
950 target.extend(path_components);
951 path = target;
952 continue 'outer;
953 }
954 }
955 entry_stack.push(entry.clone());
956 canonical_path = canonical_path.join(name);
957 } else {
958 return None;
959 }
960 }
961 }
962 }
963 break;
964 }
965 Some((entry_stack.pop()?, canonical_path))
966 }
967
968 fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
969 where
970 Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
971 {
972 let path = normalize_path(path);
973 let filename = path
974 .file_name()
975 .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
976 let parent_path = path.parent().unwrap();
977
978 let parent = self.read_path(parent_path)?;
979 let mut parent = parent.lock();
980 let new_entry = parent
981 .dir_entries(parent_path)?
982 .entry(filename.to_str().unwrap().into());
983 callback(new_entry)
984 }
985
986 fn emit_event<I, T>(&mut self, paths: I)
987 where
988 I: IntoIterator<Item = (T, Option<PathEventKind>)>,
989 T: Into<PathBuf>,
990 {
991 self.buffered_events
992 .extend(paths.into_iter().map(|(path, kind)| PathEvent {
993 path: path.into(),
994 kind,
995 }));
996
997 if !self.events_paused {
998 self.flush_events(self.buffered_events.len());
999 }
1000 }
1001
1002 fn flush_events(&mut self, mut count: usize) {
1003 count = count.min(self.buffered_events.len());
1004 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1005 self.event_txs.retain(|tx| {
1006 let _ = tx.try_send(events.clone());
1007 !tx.is_closed()
1008 });
1009 }
1010}
1011
1012#[cfg(any(test, feature = "test-support"))]
1013pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1014 std::sync::LazyLock::new(|| OsStr::new(".git"));
1015
1016#[cfg(any(test, feature = "test-support"))]
1017impl FakeFs {
1018 /// We need to use something large enough for Windows and Unix to consider this a new file.
1019 /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1020 const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1021
1022 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1023 let (tx, mut rx) = smol::channel::bounded::<PathBuf>(10);
1024
1025 let this = Arc::new(Self {
1026 executor: executor.clone(),
1027 state: Mutex::new(FakeFsState {
1028 root: Arc::new(Mutex::new(FakeFsEntry::Dir {
1029 inode: 0,
1030 mtime: MTime(UNIX_EPOCH),
1031 len: 0,
1032 entries: Default::default(),
1033 git_repo_state: None,
1034 })),
1035 git_event_tx: tx,
1036 next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1037 next_inode: 1,
1038 event_txs: Default::default(),
1039 buffered_events: Vec::new(),
1040 events_paused: false,
1041 read_dir_call_count: 0,
1042 metadata_call_count: 0,
1043 moves: Default::default(),
1044 }),
1045 });
1046
1047 executor.spawn({
1048 let this = this.clone();
1049 async move {
1050 while let Some(git_event) = rx.next().await {
1051 if let Some(mut state) = this.state.try_lock() {
1052 state.emit_event([(git_event, None)]);
1053 } else {
1054 panic!("Failed to lock file system state, this execution would have caused a test hang");
1055 }
1056 }
1057 }
1058 }).detach();
1059
1060 this
1061 }
1062
1063 pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1064 let mut state = self.state.lock();
1065 state.next_mtime = next_mtime;
1066 }
1067
1068 pub fn get_and_increment_mtime(&self) -> MTime {
1069 let mut state = self.state.lock();
1070 state.get_and_increment_mtime()
1071 }
1072
1073 pub async fn touch_path(&self, path: impl AsRef<Path>) {
1074 let mut state = self.state.lock();
1075 let path = path.as_ref();
1076 let new_mtime = state.get_and_increment_mtime();
1077 let new_inode = state.get_and_increment_inode();
1078 state
1079 .write_path(path, move |entry| {
1080 match entry {
1081 btree_map::Entry::Vacant(e) => {
1082 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1083 inode: new_inode,
1084 mtime: new_mtime,
1085 content: Vec::new(),
1086 len: 0,
1087 })));
1088 }
1089 btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1090 FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1091 FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1092 FakeFsEntry::Symlink { .. } => {}
1093 },
1094 }
1095 Ok(())
1096 })
1097 .unwrap();
1098 state.emit_event([(path.to_path_buf(), None)]);
1099 }
1100
1101 pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1102 self.write_file_internal(path, content).unwrap()
1103 }
1104
1105 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1106 let mut state = self.state.lock();
1107 let path = path.as_ref();
1108 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1109 state
1110 .write_path(path.as_ref(), move |e| match e {
1111 btree_map::Entry::Vacant(e) => {
1112 e.insert(file);
1113 Ok(())
1114 }
1115 btree_map::Entry::Occupied(mut e) => {
1116 *e.get_mut() = file;
1117 Ok(())
1118 }
1119 })
1120 .unwrap();
1121 state.emit_event([(path, None)]);
1122 }
1123
1124 fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1125 let mut state = self.state.lock();
1126 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1127 inode: state.get_and_increment_inode(),
1128 mtime: state.get_and_increment_mtime(),
1129 len: content.len() as u64,
1130 content,
1131 }));
1132 let mut kind = None;
1133 state.write_path(path.as_ref(), {
1134 let kind = &mut kind;
1135 move |entry| {
1136 match entry {
1137 btree_map::Entry::Vacant(e) => {
1138 *kind = Some(PathEventKind::Created);
1139 e.insert(file);
1140 }
1141 btree_map::Entry::Occupied(mut e) => {
1142 *kind = Some(PathEventKind::Changed);
1143 *e.get_mut() = file;
1144 }
1145 }
1146 Ok(())
1147 }
1148 })?;
1149 state.emit_event([(path.as_ref(), kind)]);
1150 Ok(())
1151 }
1152
1153 pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1154 let path = path.as_ref();
1155 let path = normalize_path(path);
1156 let state = self.state.lock();
1157 let entry = state.read_path(&path)?;
1158 let entry = entry.lock();
1159 entry.file_content(&path).cloned()
1160 }
1161
1162 async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1163 let path = path.as_ref();
1164 let path = normalize_path(path);
1165 self.simulate_random_delay().await;
1166 let state = self.state.lock();
1167 let entry = state.read_path(&path)?;
1168 let entry = entry.lock();
1169 entry.file_content(&path).cloned()
1170 }
1171
1172 pub fn pause_events(&self) {
1173 self.state.lock().events_paused = true;
1174 }
1175
1176 pub fn buffered_event_count(&self) -> usize {
1177 self.state.lock().buffered_events.len()
1178 }
1179
1180 pub fn flush_events(&self, count: usize) {
1181 self.state.lock().flush_events(count);
1182 }
1183
1184 #[must_use]
1185 pub fn insert_tree<'a>(
1186 &'a self,
1187 path: impl 'a + AsRef<Path> + Send,
1188 tree: serde_json::Value,
1189 ) -> futures::future::BoxFuture<'a, ()> {
1190 use futures::FutureExt as _;
1191 use serde_json::Value::*;
1192
1193 async move {
1194 let path = path.as_ref();
1195
1196 match tree {
1197 Object(map) => {
1198 self.create_dir(path).await.unwrap();
1199 for (name, contents) in map {
1200 let mut path = PathBuf::from(path);
1201 path.push(name);
1202 self.insert_tree(&path, contents).await;
1203 }
1204 }
1205 Null => {
1206 self.create_dir(path).await.unwrap();
1207 }
1208 String(contents) => {
1209 self.insert_file(&path, contents.into_bytes()).await;
1210 }
1211 _ => {
1212 panic!("JSON object must contain only objects, strings, or null");
1213 }
1214 }
1215 }
1216 .boxed()
1217 }
1218
1219 pub fn insert_tree_from_real_fs<'a>(
1220 &'a self,
1221 path: impl 'a + AsRef<Path> + Send,
1222 src_path: impl 'a + AsRef<Path> + Send,
1223 ) -> futures::future::BoxFuture<'a, ()> {
1224 use futures::FutureExt as _;
1225
1226 async move {
1227 let path = path.as_ref();
1228 if std::fs::metadata(&src_path).unwrap().is_file() {
1229 let contents = std::fs::read(src_path).unwrap();
1230 self.insert_file(path, contents).await;
1231 } else {
1232 self.create_dir(path).await.unwrap();
1233 for entry in std::fs::read_dir(&src_path).unwrap() {
1234 let entry = entry.unwrap();
1235 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1236 .await;
1237 }
1238 }
1239 }
1240 .boxed()
1241 }
1242
1243 pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1244 where
1245 F: FnOnce(&mut FakeGitRepositoryState),
1246 {
1247 let mut state = self.state.lock();
1248 let entry = state.read_path(dot_git).unwrap();
1249 let mut entry = entry.lock();
1250
1251 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1252 let repo_state = git_repo_state.get_or_insert_with(|| {
1253 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1254 dot_git.to_path_buf(),
1255 state.git_event_tx.clone(),
1256 )))
1257 });
1258 let mut repo_state = repo_state.lock();
1259
1260 f(&mut repo_state);
1261
1262 if emit_git_event {
1263 state.emit_event([(dot_git, None)]);
1264 }
1265 } else {
1266 panic!("not a directory");
1267 }
1268 }
1269
1270 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1271 self.with_git_state(dot_git, true, |state| {
1272 let branch = branch.map(Into::into);
1273 state.branches.extend(branch.clone());
1274 state.current_branch_name = branch.map(Into::into)
1275 })
1276 }
1277
1278 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1279 self.with_git_state(dot_git, true, |state| {
1280 if let Some(first) = branches.first() {
1281 if state.current_branch_name.is_none() {
1282 state.current_branch_name = Some(first.to_string())
1283 }
1284 }
1285 state
1286 .branches
1287 .extend(branches.iter().map(ToString::to_string));
1288 })
1289 }
1290
1291 pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1292 self.with_git_state(dot_git, true, |state| {
1293 state.index_contents.clear();
1294 state.index_contents.extend(
1295 head_state
1296 .iter()
1297 .map(|(path, content)| (path.to_path_buf(), content.clone())),
1298 );
1299 });
1300 }
1301
1302 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1303 self.with_git_state(dot_git, true, |state| {
1304 state.blames.clear();
1305 state.blames.extend(
1306 blames
1307 .into_iter()
1308 .map(|(path, blame)| (path.to_path_buf(), blame)),
1309 );
1310 });
1311 }
1312
1313 pub fn set_status_for_repo_via_working_copy_change(
1314 &self,
1315 dot_git: &Path,
1316 statuses: &[(&Path, GitFileStatus)],
1317 ) {
1318 self.with_git_state(dot_git, false, |state| {
1319 state.worktree_statuses.clear();
1320 state.worktree_statuses.extend(
1321 statuses
1322 .iter()
1323 .map(|(path, content)| ((**path).into(), *content)),
1324 );
1325 });
1326 self.state.lock().emit_event(
1327 statuses
1328 .iter()
1329 .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1330 );
1331 }
1332
1333 pub fn set_status_for_repo_via_git_operation(
1334 &self,
1335 dot_git: &Path,
1336 statuses: &[(&Path, GitFileStatus)],
1337 ) {
1338 self.with_git_state(dot_git, true, |state| {
1339 state.worktree_statuses.clear();
1340 state.worktree_statuses.extend(
1341 statuses
1342 .iter()
1343 .map(|(path, content)| ((**path).into(), *content)),
1344 );
1345 });
1346 }
1347
1348 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1349 let mut result = Vec::new();
1350 let mut queue = collections::VecDeque::new();
1351 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1352 while let Some((path, entry)) = queue.pop_front() {
1353 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1354 for (name, entry) in entries {
1355 queue.push_back((path.join(name), entry.clone()));
1356 }
1357 }
1358 if include_dot_git
1359 || !path
1360 .components()
1361 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1362 {
1363 result.push(path);
1364 }
1365 }
1366 result
1367 }
1368
1369 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1370 let mut result = Vec::new();
1371 let mut queue = collections::VecDeque::new();
1372 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1373 while let Some((path, entry)) = queue.pop_front() {
1374 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1375 for (name, entry) in entries {
1376 queue.push_back((path.join(name), entry.clone()));
1377 }
1378 if include_dot_git
1379 || !path
1380 .components()
1381 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1382 {
1383 result.push(path);
1384 }
1385 }
1386 }
1387 result
1388 }
1389
1390 pub fn files(&self) -> Vec<PathBuf> {
1391 let mut result = Vec::new();
1392 let mut queue = collections::VecDeque::new();
1393 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1394 while let Some((path, entry)) = queue.pop_front() {
1395 let e = entry.lock();
1396 match &*e {
1397 FakeFsEntry::File { .. } => result.push(path),
1398 FakeFsEntry::Dir { entries, .. } => {
1399 for (name, entry) in entries {
1400 queue.push_back((path.join(name), entry.clone()));
1401 }
1402 }
1403 FakeFsEntry::Symlink { .. } => {}
1404 }
1405 }
1406 result
1407 }
1408
1409 /// How many `read_dir` calls have been issued.
1410 pub fn read_dir_call_count(&self) -> usize {
1411 self.state.lock().read_dir_call_count
1412 }
1413
1414 /// How many `metadata` calls have been issued.
1415 pub fn metadata_call_count(&self) -> usize {
1416 self.state.lock().metadata_call_count
1417 }
1418
1419 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1420 self.executor.simulate_random_delay()
1421 }
1422}
1423
1424#[cfg(any(test, feature = "test-support"))]
1425impl FakeFsEntry {
1426 fn is_file(&self) -> bool {
1427 matches!(self, Self::File { .. })
1428 }
1429
1430 fn is_symlink(&self) -> bool {
1431 matches!(self, Self::Symlink { .. })
1432 }
1433
1434 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1435 if let Self::File { content, .. } = self {
1436 Ok(content)
1437 } else {
1438 Err(anyhow!("not a file: {}", path.display()))
1439 }
1440 }
1441
1442 fn dir_entries(
1443 &mut self,
1444 path: &Path,
1445 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1446 if let Self::Dir { entries, .. } = self {
1447 Ok(entries)
1448 } else {
1449 Err(anyhow!("not a directory: {}", path.display()))
1450 }
1451 }
1452}
1453
1454#[cfg(any(test, feature = "test-support"))]
1455struct FakeWatcher {}
1456
1457#[cfg(any(test, feature = "test-support"))]
1458impl Watcher for FakeWatcher {
1459 fn add(&self, _: &Path) -> Result<()> {
1460 Ok(())
1461 }
1462
1463 fn remove(&self, _: &Path) -> Result<()> {
1464 Ok(())
1465 }
1466}
1467
1468#[cfg(any(test, feature = "test-support"))]
1469#[derive(Debug)]
1470struct FakeHandle {
1471 inode: u64,
1472}
1473
1474#[cfg(any(test, feature = "test-support"))]
1475impl FileHandle for FakeHandle {
1476 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1477 let state = fs.as_fake().state.lock();
1478 let Some(target) = state.moves.get(&self.inode) else {
1479 anyhow::bail!("fake fd not moved")
1480 };
1481
1482 if state.try_read_path(&target, false).is_some() {
1483 return Ok(target.clone());
1484 }
1485 anyhow::bail!("fake fd target not found")
1486 }
1487}
1488
1489#[cfg(any(test, feature = "test-support"))]
1490#[async_trait::async_trait]
1491impl Fs for FakeFs {
1492 async fn create_dir(&self, path: &Path) -> Result<()> {
1493 self.simulate_random_delay().await;
1494
1495 let mut created_dirs = Vec::new();
1496 let mut cur_path = PathBuf::new();
1497 for component in path.components() {
1498 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1499 cur_path.push(component);
1500 if should_skip {
1501 continue;
1502 }
1503 let mut state = self.state.lock();
1504
1505 let inode = state.get_and_increment_inode();
1506 let mtime = state.get_and_increment_mtime();
1507 state.write_path(&cur_path, |entry| {
1508 entry.or_insert_with(|| {
1509 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1510 Arc::new(Mutex::new(FakeFsEntry::Dir {
1511 inode,
1512 mtime,
1513 len: 0,
1514 entries: Default::default(),
1515 git_repo_state: None,
1516 }))
1517 });
1518 Ok(())
1519 })?
1520 }
1521
1522 self.state.lock().emit_event(created_dirs);
1523 Ok(())
1524 }
1525
1526 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1527 self.simulate_random_delay().await;
1528 let mut state = self.state.lock();
1529 let inode = state.get_and_increment_inode();
1530 let mtime = state.get_and_increment_mtime();
1531 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1532 inode,
1533 mtime,
1534 len: 0,
1535 content: Vec::new(),
1536 }));
1537 let mut kind = Some(PathEventKind::Created);
1538 state.write_path(path, |entry| {
1539 match entry {
1540 btree_map::Entry::Occupied(mut e) => {
1541 if options.overwrite {
1542 kind = Some(PathEventKind::Changed);
1543 *e.get_mut() = file;
1544 } else if !options.ignore_if_exists {
1545 return Err(anyhow!("path already exists: {}", path.display()));
1546 }
1547 }
1548 btree_map::Entry::Vacant(e) => {
1549 e.insert(file);
1550 }
1551 }
1552 Ok(())
1553 })?;
1554 state.emit_event([(path, kind)]);
1555 Ok(())
1556 }
1557
1558 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1559 let mut state = self.state.lock();
1560 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1561 state
1562 .write_path(path.as_ref(), move |e| match e {
1563 btree_map::Entry::Vacant(e) => {
1564 e.insert(file);
1565 Ok(())
1566 }
1567 btree_map::Entry::Occupied(mut e) => {
1568 *e.get_mut() = file;
1569 Ok(())
1570 }
1571 })
1572 .unwrap();
1573 state.emit_event([(path, None)]);
1574
1575 Ok(())
1576 }
1577
1578 async fn create_file_with(
1579 &self,
1580 path: &Path,
1581 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1582 ) -> Result<()> {
1583 let mut bytes = Vec::new();
1584 content.read_to_end(&mut bytes).await?;
1585 self.write_file_internal(path, bytes)?;
1586 Ok(())
1587 }
1588
1589 async fn extract_tar_file(
1590 &self,
1591 path: &Path,
1592 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1593 ) -> Result<()> {
1594 let mut entries = content.entries()?;
1595 while let Some(entry) = entries.next().await {
1596 let mut entry = entry?;
1597 if entry.header().entry_type().is_file() {
1598 let path = path.join(entry.path()?.as_ref());
1599 let mut bytes = Vec::new();
1600 entry.read_to_end(&mut bytes).await?;
1601 self.create_dir(path.parent().unwrap()).await?;
1602 self.write_file_internal(&path, bytes)?;
1603 }
1604 }
1605 Ok(())
1606 }
1607
1608 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1609 self.simulate_random_delay().await;
1610
1611 let old_path = normalize_path(old_path);
1612 let new_path = normalize_path(new_path);
1613
1614 let mut state = self.state.lock();
1615 let moved_entry = state.write_path(&old_path, |e| {
1616 if let btree_map::Entry::Occupied(e) = e {
1617 Ok(e.get().clone())
1618 } else {
1619 Err(anyhow!("path does not exist: {}", &old_path.display()))
1620 }
1621 })?;
1622
1623 let inode = match *moved_entry.lock() {
1624 FakeFsEntry::File { inode, .. } => inode,
1625 FakeFsEntry::Dir { inode, .. } => inode,
1626 _ => 0,
1627 };
1628
1629 state.moves.insert(inode, new_path.clone());
1630
1631 state.write_path(&new_path, |e| {
1632 match e {
1633 btree_map::Entry::Occupied(mut e) => {
1634 if options.overwrite {
1635 *e.get_mut() = moved_entry;
1636 } else if !options.ignore_if_exists {
1637 return Err(anyhow!("path already exists: {}", new_path.display()));
1638 }
1639 }
1640 btree_map::Entry::Vacant(e) => {
1641 e.insert(moved_entry);
1642 }
1643 }
1644 Ok(())
1645 })?;
1646
1647 state
1648 .write_path(&old_path, |e| {
1649 if let btree_map::Entry::Occupied(e) = e {
1650 Ok(e.remove())
1651 } else {
1652 unreachable!()
1653 }
1654 })
1655 .unwrap();
1656
1657 state.emit_event([
1658 (old_path, Some(PathEventKind::Removed)),
1659 (new_path, Some(PathEventKind::Created)),
1660 ]);
1661 Ok(())
1662 }
1663
1664 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1665 self.simulate_random_delay().await;
1666
1667 let source = normalize_path(source);
1668 let target = normalize_path(target);
1669 let mut state = self.state.lock();
1670 let mtime = state.get_and_increment_mtime();
1671 let inode = state.get_and_increment_inode();
1672 let source_entry = state.read_path(&source)?;
1673 let content = source_entry.lock().file_content(&source)?.clone();
1674 let mut kind = Some(PathEventKind::Created);
1675 state.write_path(&target, |e| match e {
1676 btree_map::Entry::Occupied(e) => {
1677 if options.overwrite {
1678 kind = Some(PathEventKind::Changed);
1679 Ok(Some(e.get().clone()))
1680 } else if !options.ignore_if_exists {
1681 return Err(anyhow!("{target:?} already exists"));
1682 } else {
1683 Ok(None)
1684 }
1685 }
1686 btree_map::Entry::Vacant(e) => Ok(Some(
1687 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1688 inode,
1689 mtime,
1690 len: content.len() as u64,
1691 content,
1692 })))
1693 .clone(),
1694 )),
1695 })?;
1696 state.emit_event([(target, kind)]);
1697 Ok(())
1698 }
1699
1700 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1701 self.simulate_random_delay().await;
1702
1703 let path = normalize_path(path);
1704 let parent_path = path
1705 .parent()
1706 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1707 let base_name = path.file_name().unwrap();
1708
1709 let mut state = self.state.lock();
1710 let parent_entry = state.read_path(parent_path)?;
1711 let mut parent_entry = parent_entry.lock();
1712 let entry = parent_entry
1713 .dir_entries(parent_path)?
1714 .entry(base_name.to_str().unwrap().into());
1715
1716 match entry {
1717 btree_map::Entry::Vacant(_) => {
1718 if !options.ignore_if_not_exists {
1719 return Err(anyhow!("{path:?} does not exist"));
1720 }
1721 }
1722 btree_map::Entry::Occupied(e) => {
1723 {
1724 let mut entry = e.get().lock();
1725 let children = entry.dir_entries(&path)?;
1726 if !options.recursive && !children.is_empty() {
1727 return Err(anyhow!("{path:?} is not empty"));
1728 }
1729 }
1730 e.remove();
1731 }
1732 }
1733 state.emit_event([(path, Some(PathEventKind::Removed))]);
1734 Ok(())
1735 }
1736
1737 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1738 self.simulate_random_delay().await;
1739
1740 let path = normalize_path(path);
1741 let parent_path = path
1742 .parent()
1743 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1744 let base_name = path.file_name().unwrap();
1745 let mut state = self.state.lock();
1746 let parent_entry = state.read_path(parent_path)?;
1747 let mut parent_entry = parent_entry.lock();
1748 let entry = parent_entry
1749 .dir_entries(parent_path)?
1750 .entry(base_name.to_str().unwrap().into());
1751 match entry {
1752 btree_map::Entry::Vacant(_) => {
1753 if !options.ignore_if_not_exists {
1754 return Err(anyhow!("{path:?} does not exist"));
1755 }
1756 }
1757 btree_map::Entry::Occupied(e) => {
1758 e.get().lock().file_content(&path)?;
1759 e.remove();
1760 }
1761 }
1762 state.emit_event([(path, Some(PathEventKind::Removed))]);
1763 Ok(())
1764 }
1765
1766 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1767 let bytes = self.load_internal(path).await?;
1768 Ok(Box::new(io::Cursor::new(bytes)))
1769 }
1770
1771 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1772 self.simulate_random_delay().await;
1773 let state = self.state.lock();
1774 let entry = state.read_path(&path)?;
1775 let entry = entry.lock();
1776 let inode = match *entry {
1777 FakeFsEntry::File { inode, .. } => inode,
1778 FakeFsEntry::Dir { inode, .. } => inode,
1779 _ => unreachable!(),
1780 };
1781 Ok(Arc::new(FakeHandle { inode }))
1782 }
1783
1784 async fn load(&self, path: &Path) -> Result<String> {
1785 let content = self.load_internal(path).await?;
1786 Ok(String::from_utf8(content.clone())?)
1787 }
1788
1789 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1790 self.load_internal(path).await
1791 }
1792
1793 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1794 self.simulate_random_delay().await;
1795 let path = normalize_path(path.as_path());
1796 self.write_file_internal(path, data.into_bytes())?;
1797 Ok(())
1798 }
1799
1800 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1801 self.simulate_random_delay().await;
1802 let path = normalize_path(path);
1803 let content = chunks(text, line_ending).collect::<String>();
1804 if let Some(path) = path.parent() {
1805 self.create_dir(path).await?;
1806 }
1807 self.write_file_internal(path, content.into_bytes())?;
1808 Ok(())
1809 }
1810
1811 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1812 let path = normalize_path(path);
1813 self.simulate_random_delay().await;
1814 let state = self.state.lock();
1815 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1816 Ok(canonical_path)
1817 } else {
1818 Err(anyhow!("path does not exist: {}", path.display()))
1819 }
1820 }
1821
1822 async fn is_file(&self, path: &Path) -> bool {
1823 let path = normalize_path(path);
1824 self.simulate_random_delay().await;
1825 let state = self.state.lock();
1826 if let Some((entry, _)) = state.try_read_path(&path, true) {
1827 entry.lock().is_file()
1828 } else {
1829 false
1830 }
1831 }
1832
1833 async fn is_dir(&self, path: &Path) -> bool {
1834 self.metadata(path)
1835 .await
1836 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1837 }
1838
1839 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1840 self.simulate_random_delay().await;
1841 let path = normalize_path(path);
1842 let mut state = self.state.lock();
1843 state.metadata_call_count += 1;
1844 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1845 let is_symlink = entry.lock().is_symlink();
1846 if is_symlink {
1847 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1848 entry = e;
1849 } else {
1850 return Ok(None);
1851 }
1852 }
1853
1854 let entry = entry.lock();
1855 Ok(Some(match &*entry {
1856 FakeFsEntry::File {
1857 inode, mtime, len, ..
1858 } => Metadata {
1859 inode: *inode,
1860 mtime: *mtime,
1861 len: *len,
1862 is_dir: false,
1863 is_symlink,
1864 is_fifo: false,
1865 },
1866 FakeFsEntry::Dir {
1867 inode, mtime, len, ..
1868 } => Metadata {
1869 inode: *inode,
1870 mtime: *mtime,
1871 len: *len,
1872 is_dir: true,
1873 is_symlink,
1874 is_fifo: false,
1875 },
1876 FakeFsEntry::Symlink { .. } => unreachable!(),
1877 }))
1878 } else {
1879 Ok(None)
1880 }
1881 }
1882
1883 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1884 self.simulate_random_delay().await;
1885 let path = normalize_path(path);
1886 let state = self.state.lock();
1887 if let Some((entry, _)) = state.try_read_path(&path, false) {
1888 let entry = entry.lock();
1889 if let FakeFsEntry::Symlink { target } = &*entry {
1890 Ok(target.clone())
1891 } else {
1892 Err(anyhow!("not a symlink: {}", path.display()))
1893 }
1894 } else {
1895 Err(anyhow!("path does not exist: {}", path.display()))
1896 }
1897 }
1898
1899 async fn read_dir(
1900 &self,
1901 path: &Path,
1902 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1903 self.simulate_random_delay().await;
1904 let path = normalize_path(path);
1905 let mut state = self.state.lock();
1906 state.read_dir_call_count += 1;
1907 let entry = state.read_path(&path)?;
1908 let mut entry = entry.lock();
1909 let children = entry.dir_entries(&path)?;
1910 let paths = children
1911 .keys()
1912 .map(|file_name| Ok(path.join(file_name)))
1913 .collect::<Vec<_>>();
1914 Ok(Box::pin(futures::stream::iter(paths)))
1915 }
1916
1917 async fn watch(
1918 &self,
1919 path: &Path,
1920 _: Duration,
1921 ) -> (
1922 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1923 Arc<dyn Watcher>,
1924 ) {
1925 self.simulate_random_delay().await;
1926 let (tx, rx) = smol::channel::unbounded();
1927 self.state.lock().event_txs.push(tx);
1928 let path = path.to_path_buf();
1929 let executor = self.executor.clone();
1930 (
1931 Box::pin(futures::StreamExt::filter(rx, move |events| {
1932 let result = events
1933 .iter()
1934 .any(|evt_path| evt_path.path.starts_with(&path));
1935 let executor = executor.clone();
1936 async move {
1937 executor.simulate_random_delay().await;
1938 result
1939 }
1940 })),
1941 Arc::new(FakeWatcher {}),
1942 )
1943 }
1944
1945 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1946 let state = self.state.lock();
1947 let entry = state.read_path(abs_dot_git).unwrap();
1948 let mut entry = entry.lock();
1949 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1950 let state = git_repo_state
1951 .get_or_insert_with(|| {
1952 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1953 abs_dot_git.to_path_buf(),
1954 state.git_event_tx.clone(),
1955 )))
1956 })
1957 .clone();
1958 Some(git::repository::FakeGitRepository::open(state))
1959 } else {
1960 None
1961 }
1962 }
1963
1964 fn is_fake(&self) -> bool {
1965 true
1966 }
1967
1968 async fn is_case_sensitive(&self) -> Result<bool> {
1969 Ok(true)
1970 }
1971
1972 #[cfg(any(test, feature = "test-support"))]
1973 fn as_fake(&self) -> &FakeFs {
1974 self
1975 }
1976}
1977
1978fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1979 rope.chunks().flat_map(move |chunk| {
1980 let mut newline = false;
1981 chunk.split('\n').flat_map(move |line| {
1982 let ending = if newline {
1983 Some(line_ending.as_str())
1984 } else {
1985 None
1986 };
1987 newline = true;
1988 ending.into_iter().chain([line])
1989 })
1990 })
1991}
1992
1993pub fn normalize_path(path: &Path) -> PathBuf {
1994 let mut components = path.components().peekable();
1995 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1996 components.next();
1997 PathBuf::from(c.as_os_str())
1998 } else {
1999 PathBuf::new()
2000 };
2001
2002 for component in components {
2003 match component {
2004 Component::Prefix(..) => unreachable!(),
2005 Component::RootDir => {
2006 ret.push(component.as_os_str());
2007 }
2008 Component::CurDir => {}
2009 Component::ParentDir => {
2010 ret.pop();
2011 }
2012 Component::Normal(c) => {
2013 ret.push(c);
2014 }
2015 }
2016 }
2017 ret
2018}
2019
2020pub fn copy_recursive<'a>(
2021 fs: &'a dyn Fs,
2022 source: &'a Path,
2023 target: &'a Path,
2024 options: CopyOptions,
2025) -> BoxFuture<'a, Result<()>> {
2026 use futures::future::FutureExt;
2027
2028 async move {
2029 let metadata = fs
2030 .metadata(source)
2031 .await?
2032 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2033 if metadata.is_dir {
2034 if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
2035 if options.ignore_if_exists {
2036 return Ok(());
2037 } else {
2038 return Err(anyhow!("{target:?} already exists"));
2039 }
2040 }
2041
2042 let _ = fs
2043 .remove_dir(
2044 target,
2045 RemoveOptions {
2046 recursive: true,
2047 ignore_if_not_exists: true,
2048 },
2049 )
2050 .await;
2051 fs.create_dir(target).await?;
2052 let mut children = fs.read_dir(source).await?;
2053 while let Some(child_path) = children.next().await {
2054 if let Ok(child_path) = child_path {
2055 if let Some(file_name) = child_path.file_name() {
2056 let child_target_path = target.join(file_name);
2057 copy_recursive(fs, &child_path, &child_target_path, options).await?;
2058 }
2059 }
2060 }
2061
2062 Ok(())
2063 } else {
2064 fs.copy_file(source, target, options).await
2065 }
2066 }
2067 .boxed()
2068}
2069
2070// todo(windows)
2071// can we get file id not open the file twice?
2072// https://github.com/rust-lang/rust/issues/63010
2073#[cfg(target_os = "windows")]
2074async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2075 use std::os::windows::io::AsRawHandle;
2076
2077 use smol::fs::windows::OpenOptionsExt;
2078 use windows::Win32::{
2079 Foundation::HANDLE,
2080 Storage::FileSystem::{
2081 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2082 },
2083 };
2084
2085 let file = smol::fs::OpenOptions::new()
2086 .read(true)
2087 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2088 .open(path)
2089 .await?;
2090
2091 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2092 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2093 // This function supports Windows XP+
2094 smol::unblock(move || {
2095 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2096
2097 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2098 })
2099 .await
2100}
2101
2102#[cfg(test)]
2103mod tests {
2104 use super::*;
2105 use gpui::BackgroundExecutor;
2106 use serde_json::json;
2107
2108 #[gpui::test]
2109 async fn test_fake_fs(executor: BackgroundExecutor) {
2110 let fs = FakeFs::new(executor.clone());
2111 fs.insert_tree(
2112 "/root",
2113 json!({
2114 "dir1": {
2115 "a": "A",
2116 "b": "B"
2117 },
2118 "dir2": {
2119 "c": "C",
2120 "dir3": {
2121 "d": "D"
2122 }
2123 }
2124 }),
2125 )
2126 .await;
2127
2128 assert_eq!(
2129 fs.files(),
2130 vec![
2131 PathBuf::from("/root/dir1/a"),
2132 PathBuf::from("/root/dir1/b"),
2133 PathBuf::from("/root/dir2/c"),
2134 PathBuf::from("/root/dir2/dir3/d"),
2135 ]
2136 );
2137
2138 fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2139 .await
2140 .unwrap();
2141
2142 assert_eq!(
2143 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2144 .await
2145 .unwrap(),
2146 PathBuf::from("/root/dir2/dir3"),
2147 );
2148 assert_eq!(
2149 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2150 .await
2151 .unwrap(),
2152 PathBuf::from("/root/dir2/dir3/d"),
2153 );
2154 assert_eq!(
2155 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2156 "D",
2157 );
2158 }
2159}