1#[cfg(target_os = "macos")]
2mod mac_watcher;
3
4#[cfg(not(target_os = "macos"))]
5pub mod fs_watcher;
6
7use anyhow::{anyhow, Context, Result};
8#[cfg(any(test, feature = "test-support"))]
9use git::status::FileStatus;
10use git::GitHostingProviderRegistry;
11
12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
13use ashpd::desktop::trash;
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;
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) -> Arc<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 if let Ok(Some(metadata)) = self.metadata(path).await {
447 if metadata.is_symlink {
448 // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
449 return self.remove_file(path, RemoveOptions::default()).await;
450 }
451 }
452 let file = smol::fs::File::open(path).await?;
453 match trash::trash_file(&file.as_fd()).await {
454 Ok(_) => Ok(()),
455 Err(err) => Err(anyhow::Error::new(err)),
456 }
457 }
458
459 #[cfg(target_os = "windows")]
460 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
461 use util::paths::SanitizedPath;
462 use windows::{
463 core::HSTRING,
464 Storage::{StorageDeleteOption, StorageFile},
465 };
466 // todo(windows)
467 // When new version of `windows-rs` release, make this operation `async`
468 let path = SanitizedPath::from(path.canonicalize()?);
469 let path_string = path.to_string();
470 let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
471 file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
472 Ok(())
473 }
474
475 #[cfg(target_os = "macos")]
476 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
477 self.trash_file(path, options).await
478 }
479
480 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
481 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
482 self.trash_file(path, options).await
483 }
484
485 #[cfg(target_os = "windows")]
486 async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
487 use util::paths::SanitizedPath;
488 use windows::{
489 core::HSTRING,
490 Storage::{StorageDeleteOption, StorageFolder},
491 };
492
493 // todo(windows)
494 // When new version of `windows-rs` release, make this operation `async`
495 let path = SanitizedPath::from(path.canonicalize()?);
496 let path_string = path.to_string();
497 let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
498 folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
499 Ok(())
500 }
501
502 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
503 Ok(Box::new(std::fs::File::open(path)?))
504 }
505
506 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
507 Ok(Arc::new(std::fs::File::open(path)?))
508 }
509
510 async fn load(&self, path: &Path) -> Result<String> {
511 let path = path.to_path_buf();
512 let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
513 Ok(text)
514 }
515 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
516 let path = path.to_path_buf();
517 let bytes = smol::unblock(|| std::fs::read(path)).await?;
518 Ok(bytes)
519 }
520
521 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
522 smol::unblock(move || {
523 let mut tmp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
524 // Use the directory of the destination as temp dir to avoid
525 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
526 // See https://github.com/zed-industries/zed/pull/8437 for more details.
527 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
528 } else if cfg!(target_os = "windows") {
529 // If temp dir is set to a different drive than the destination,
530 // we receive error:
531 //
532 // failed to persist temporary file:
533 // The system cannot move the file to a different disk drive. (os error 17)
534 //
535 // So we use the directory of the destination as a temp dir to avoid it.
536 // https://github.com/zed-industries/zed/issues/16571
537 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
538 } else {
539 NamedTempFile::new()
540 }?;
541 tmp_file.write_all(data.as_bytes())?;
542 tmp_file.persist(path)?;
543 Ok::<(), anyhow::Error>(())
544 })
545 .await?;
546
547 Ok(())
548 }
549
550 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
551 let buffer_size = text.summary().len.min(10 * 1024);
552 if let Some(path) = path.parent() {
553 self.create_dir(path).await?;
554 }
555 let file = smol::fs::File::create(path).await?;
556 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
557 for chunk in chunks(text, line_ending) {
558 writer.write_all(chunk.as_bytes()).await?;
559 }
560 writer.flush().await?;
561 Ok(())
562 }
563
564 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
565 Ok(smol::fs::canonicalize(path).await?)
566 }
567
568 async fn is_file(&self, path: &Path) -> bool {
569 smol::fs::metadata(path)
570 .await
571 .map_or(false, |metadata| metadata.is_file())
572 }
573
574 async fn is_dir(&self, path: &Path) -> bool {
575 smol::fs::metadata(path)
576 .await
577 .map_or(false, |metadata| metadata.is_dir())
578 }
579
580 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
581 let symlink_metadata = match smol::fs::symlink_metadata(path).await {
582 Ok(metadata) => metadata,
583 Err(err) => {
584 return match (err.kind(), err.raw_os_error()) {
585 (io::ErrorKind::NotFound, _) => Ok(None),
586 (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
587 _ => Err(anyhow::Error::new(err)),
588 }
589 }
590 };
591
592 let path_buf = path.to_path_buf();
593 let path_exists = smol::unblock(move || {
594 path_buf
595 .try_exists()
596 .with_context(|| format!("checking existence for path {path_buf:?}"))
597 })
598 .await?;
599 let is_symlink = symlink_metadata.file_type().is_symlink();
600 let metadata = match (is_symlink, path_exists) {
601 (true, true) => smol::fs::metadata(path)
602 .await
603 .with_context(|| "accessing symlink for path {path}")?,
604 _ => symlink_metadata,
605 };
606
607 #[cfg(unix)]
608 let inode = metadata.ino();
609
610 #[cfg(windows)]
611 let inode = file_id(path).await?;
612
613 #[cfg(windows)]
614 let is_fifo = false;
615
616 #[cfg(unix)]
617 let is_fifo = metadata.file_type().is_fifo();
618
619 Ok(Some(Metadata {
620 inode,
621 mtime: MTime(metadata.modified().unwrap()),
622 len: metadata.len(),
623 is_symlink,
624 is_dir: metadata.file_type().is_dir(),
625 is_fifo,
626 }))
627 }
628
629 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
630 let path = smol::fs::read_link(path).await?;
631 Ok(path)
632 }
633
634 async fn read_dir(
635 &self,
636 path: &Path,
637 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
638 let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
639 Ok(entry) => Ok(entry.path()),
640 Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
641 });
642 Ok(Box::pin(result))
643 }
644
645 #[cfg(target_os = "macos")]
646 async fn watch(
647 &self,
648 path: &Path,
649 latency: Duration,
650 ) -> (
651 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
652 Arc<dyn Watcher>,
653 ) {
654 use fsevent::StreamFlags;
655
656 let (events_tx, events_rx) = smol::channel::unbounded();
657 let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
658 let watcher = Arc::new(mac_watcher::MacWatcher::new(
659 events_tx,
660 Arc::downgrade(&handles),
661 latency,
662 ));
663 watcher.add(path).expect("handles can't be dropped");
664
665 (
666 Box::pin(
667 events_rx
668 .map(|events| {
669 events
670 .into_iter()
671 .map(|event| {
672 let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
673 Some(PathEventKind::Removed)
674 } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
675 Some(PathEventKind::Created)
676 } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
677 Some(PathEventKind::Changed)
678 } else {
679 None
680 };
681 PathEvent {
682 path: event.path,
683 kind,
684 }
685 })
686 .collect()
687 })
688 .chain(futures::stream::once(async move {
689 drop(handles);
690 vec![]
691 })),
692 ),
693 watcher,
694 )
695 }
696
697 #[cfg(not(target_os = "macos"))]
698 async fn watch(
699 &self,
700 path: &Path,
701 latency: Duration,
702 ) -> (
703 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
704 Arc<dyn Watcher>,
705 ) {
706 use parking_lot::Mutex;
707 use util::paths::SanitizedPath;
708
709 let (tx, rx) = smol::channel::unbounded();
710 let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
711 let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
712
713 if watcher.add(path).is_err() {
714 // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
715 if let Some(parent) = path.parent() {
716 if let Err(e) = watcher.add(parent) {
717 log::warn!("Failed to watch: {e}");
718 }
719 }
720 }
721
722 // Check if path is a symlink and follow the target parent
723 if let Some(mut target) = self.read_link(&path).await.ok() {
724 // Check if symlink target is relative path, if so make it absolute
725 if target.is_relative() {
726 if let Some(parent) = path.parent() {
727 target = parent.join(target);
728 if let Ok(canonical) = self.canonicalize(&target).await {
729 target = SanitizedPath::from(canonical).as_path().to_path_buf();
730 }
731 }
732 }
733 watcher.add(&target).ok();
734 if let Some(parent) = target.parent() {
735 watcher.add(parent).log_err();
736 }
737 }
738
739 (
740 Box::pin(rx.filter_map({
741 let watcher = watcher.clone();
742 move |_| {
743 let _ = watcher.clone();
744 let pending_paths = pending_paths.clone();
745 async move {
746 smol::Timer::after(latency).await;
747 let paths = std::mem::take(&mut *pending_paths.lock());
748 (!paths.is_empty()).then_some(paths)
749 }
750 }
751 })),
752 watcher,
753 )
754 }
755
756 fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
757 // with libgit2, we can open git repo from an existing work dir
758 // https://libgit2.org/docs/reference/main/repository/git_repository_open.html
759 let workdir_root = dotgit_path.parent()?;
760 let repo = git2::Repository::open(workdir_root).log_err()?;
761 Some(Arc::new(RealGitRepository::new(
762 repo,
763 self.git_binary_path.clone(),
764 self.git_hosting_provider_registry.clone(),
765 )))
766 }
767
768 fn is_fake(&self) -> bool {
769 false
770 }
771
772 /// Checks whether the file system is case sensitive by attempting to create two files
773 /// that have the same name except for the casing.
774 ///
775 /// It creates both files in a temporary directory it removes at the end.
776 async fn is_case_sensitive(&self) -> Result<bool> {
777 let temp_dir = TempDir::new()?;
778 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
779 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
780
781 let create_opts = CreateOptions {
782 overwrite: false,
783 ignore_if_exists: false,
784 };
785
786 // Create file1
787 self.create_file(&test_file_1, create_opts).await?;
788
789 // Now check whether it's possible to create file2
790 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
791 Ok(_) => Ok(true),
792 Err(e) => {
793 if let Some(io_error) = e.downcast_ref::<io::Error>() {
794 if io_error.kind() == io::ErrorKind::AlreadyExists {
795 Ok(false)
796 } else {
797 Err(e)
798 }
799 } else {
800 Err(e)
801 }
802 }
803 };
804
805 temp_dir.close()?;
806 case_sensitive
807 }
808}
809
810#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
811impl Watcher for RealWatcher {
812 fn add(&self, _: &Path) -> Result<()> {
813 Ok(())
814 }
815
816 fn remove(&self, _: &Path) -> Result<()> {
817 Ok(())
818 }
819}
820
821#[cfg(any(test, feature = "test-support"))]
822pub struct FakeFs {
823 this: std::sync::Weak<Self>,
824 // Use an unfair lock to ensure tests are deterministic.
825 state: Mutex<FakeFsState>,
826 executor: gpui::BackgroundExecutor,
827}
828
829#[cfg(any(test, feature = "test-support"))]
830struct FakeFsState {
831 root: Arc<Mutex<FakeFsEntry>>,
832 next_inode: u64,
833 next_mtime: SystemTime,
834 git_event_tx: smol::channel::Sender<PathBuf>,
835 event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
836 events_paused: bool,
837 buffered_events: Vec<PathEvent>,
838 metadata_call_count: usize,
839 read_dir_call_count: usize,
840 moves: std::collections::HashMap<u64, PathBuf>,
841}
842
843#[cfg(any(test, feature = "test-support"))]
844#[derive(Debug)]
845enum FakeFsEntry {
846 File {
847 inode: u64,
848 mtime: MTime,
849 len: u64,
850 content: Vec<u8>,
851 },
852 Dir {
853 inode: u64,
854 mtime: MTime,
855 len: u64,
856 entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
857 git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
858 },
859 Symlink {
860 target: PathBuf,
861 },
862}
863
864#[cfg(any(test, feature = "test-support"))]
865impl FakeFsState {
866 fn get_and_increment_mtime(&mut self) -> MTime {
867 let mtime = self.next_mtime;
868 self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
869 MTime(mtime)
870 }
871
872 fn get_and_increment_inode(&mut self) -> u64 {
873 let inode = self.next_inode;
874 self.next_inode += 1;
875 inode
876 }
877
878 fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
879 Ok(self
880 .try_read_path(target, true)
881 .ok_or_else(|| {
882 anyhow!(io::Error::new(
883 io::ErrorKind::NotFound,
884 format!("not found: {}", target.display())
885 ))
886 })?
887 .0)
888 }
889
890 fn try_read_path(
891 &self,
892 target: &Path,
893 follow_symlink: bool,
894 ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
895 let mut path = target.to_path_buf();
896 let mut canonical_path = PathBuf::new();
897 let mut entry_stack = Vec::new();
898 'outer: loop {
899 let mut path_components = path.components().peekable();
900 let mut prefix = None;
901 while let Some(component) = path_components.next() {
902 match component {
903 Component::Prefix(prefix_component) => prefix = Some(prefix_component),
904 Component::RootDir => {
905 entry_stack.clear();
906 entry_stack.push(self.root.clone());
907 canonical_path.clear();
908 match prefix {
909 Some(prefix_component) => {
910 canonical_path = PathBuf::from(prefix_component.as_os_str());
911 // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
912 canonical_path.push(std::path::MAIN_SEPARATOR_STR);
913 }
914 None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
915 }
916 }
917 Component::CurDir => {}
918 Component::ParentDir => {
919 entry_stack.pop()?;
920 canonical_path.pop();
921 }
922 Component::Normal(name) => {
923 let current_entry = entry_stack.last().cloned()?;
924 let current_entry = current_entry.lock();
925 if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
926 let entry = entries.get(name.to_str().unwrap()).cloned()?;
927 if path_components.peek().is_some() || follow_symlink {
928 let entry = entry.lock();
929 if let FakeFsEntry::Symlink { target, .. } = &*entry {
930 let mut target = target.clone();
931 target.extend(path_components);
932 path = target;
933 continue 'outer;
934 }
935 }
936 entry_stack.push(entry.clone());
937 canonical_path = canonical_path.join(name);
938 } else {
939 return None;
940 }
941 }
942 }
943 }
944 break;
945 }
946 Some((entry_stack.pop()?, canonical_path))
947 }
948
949 fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
950 where
951 Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
952 {
953 let path = normalize_path(path);
954 let filename = path
955 .file_name()
956 .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
957 let parent_path = path.parent().unwrap();
958
959 let parent = self.read_path(parent_path)?;
960 let mut parent = parent.lock();
961 let new_entry = parent
962 .dir_entries(parent_path)?
963 .entry(filename.to_str().unwrap().into());
964 callback(new_entry)
965 }
966
967 fn emit_event<I, T>(&mut self, paths: I)
968 where
969 I: IntoIterator<Item = (T, Option<PathEventKind>)>,
970 T: Into<PathBuf>,
971 {
972 self.buffered_events
973 .extend(paths.into_iter().map(|(path, kind)| PathEvent {
974 path: path.into(),
975 kind,
976 }));
977
978 if !self.events_paused {
979 self.flush_events(self.buffered_events.len());
980 }
981 }
982
983 fn flush_events(&mut self, mut count: usize) {
984 count = count.min(self.buffered_events.len());
985 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
986 self.event_txs.retain(|tx| {
987 let _ = tx.try_send(events.clone());
988 !tx.is_closed()
989 });
990 }
991}
992
993#[cfg(any(test, feature = "test-support"))]
994pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
995 std::sync::LazyLock::new(|| OsStr::new(".git"));
996
997#[cfg(any(test, feature = "test-support"))]
998impl FakeFs {
999 /// We need to use something large enough for Windows and Unix to consider this a new file.
1000 /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1001 const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1002
1003 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1004 let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1005
1006 let this = Arc::new_cyclic(|this| Self {
1007 this: this.clone(),
1008 executor: executor.clone(),
1009 state: Mutex::new(FakeFsState {
1010 root: Arc::new(Mutex::new(FakeFsEntry::Dir {
1011 inode: 0,
1012 mtime: MTime(UNIX_EPOCH),
1013 len: 0,
1014 entries: Default::default(),
1015 git_repo_state: None,
1016 })),
1017 git_event_tx: tx,
1018 next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1019 next_inode: 1,
1020 event_txs: Default::default(),
1021 buffered_events: Vec::new(),
1022 events_paused: false,
1023 read_dir_call_count: 0,
1024 metadata_call_count: 0,
1025 moves: Default::default(),
1026 }),
1027 });
1028
1029 executor.spawn({
1030 let this = this.clone();
1031 async move {
1032 while let Ok(git_event) = rx.recv().await {
1033 if let Some(mut state) = this.state.try_lock() {
1034 state.emit_event([(git_event, None)]);
1035 } else {
1036 panic!("Failed to lock file system state, this execution would have caused a test hang");
1037 }
1038 }
1039 }
1040 }).detach();
1041
1042 this
1043 }
1044
1045 pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1046 let mut state = self.state.lock();
1047 state.next_mtime = next_mtime;
1048 }
1049
1050 pub fn get_and_increment_mtime(&self) -> MTime {
1051 let mut state = self.state.lock();
1052 state.get_and_increment_mtime()
1053 }
1054
1055 pub async fn touch_path(&self, path: impl AsRef<Path>) {
1056 let mut state = self.state.lock();
1057 let path = path.as_ref();
1058 let new_mtime = state.get_and_increment_mtime();
1059 let new_inode = state.get_and_increment_inode();
1060 state
1061 .write_path(path, move |entry| {
1062 match entry {
1063 btree_map::Entry::Vacant(e) => {
1064 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1065 inode: new_inode,
1066 mtime: new_mtime,
1067 content: Vec::new(),
1068 len: 0,
1069 })));
1070 }
1071 btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1072 FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1073 FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1074 FakeFsEntry::Symlink { .. } => {}
1075 },
1076 }
1077 Ok(())
1078 })
1079 .unwrap();
1080 state.emit_event([(path.to_path_buf(), None)]);
1081 }
1082
1083 pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1084 self.write_file_internal(path, content).unwrap()
1085 }
1086
1087 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1088 let mut state = self.state.lock();
1089 let path = path.as_ref();
1090 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1091 state
1092 .write_path(path.as_ref(), move |e| match e {
1093 btree_map::Entry::Vacant(e) => {
1094 e.insert(file);
1095 Ok(())
1096 }
1097 btree_map::Entry::Occupied(mut e) => {
1098 *e.get_mut() = file;
1099 Ok(())
1100 }
1101 })
1102 .unwrap();
1103 state.emit_event([(path, None)]);
1104 }
1105
1106 fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1107 let mut state = self.state.lock();
1108 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1109 inode: state.get_and_increment_inode(),
1110 mtime: state.get_and_increment_mtime(),
1111 len: content.len() as u64,
1112 content,
1113 }));
1114 let mut kind = None;
1115 state.write_path(path.as_ref(), {
1116 let kind = &mut kind;
1117 move |entry| {
1118 match entry {
1119 btree_map::Entry::Vacant(e) => {
1120 *kind = Some(PathEventKind::Created);
1121 e.insert(file);
1122 }
1123 btree_map::Entry::Occupied(mut e) => {
1124 *kind = Some(PathEventKind::Changed);
1125 *e.get_mut() = file;
1126 }
1127 }
1128 Ok(())
1129 }
1130 })?;
1131 state.emit_event([(path.as_ref(), kind)]);
1132 Ok(())
1133 }
1134
1135 pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1136 let path = path.as_ref();
1137 let path = normalize_path(path);
1138 let state = self.state.lock();
1139 let entry = state.read_path(&path)?;
1140 let entry = entry.lock();
1141 entry.file_content(&path).cloned()
1142 }
1143
1144 async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1145 let path = path.as_ref();
1146 let path = normalize_path(path);
1147 self.simulate_random_delay().await;
1148 let state = self.state.lock();
1149 let entry = state.read_path(&path)?;
1150 let entry = entry.lock();
1151 entry.file_content(&path).cloned()
1152 }
1153
1154 pub fn pause_events(&self) {
1155 self.state.lock().events_paused = true;
1156 }
1157
1158 pub fn buffered_event_count(&self) -> usize {
1159 self.state.lock().buffered_events.len()
1160 }
1161
1162 pub fn flush_events(&self, count: usize) {
1163 self.state.lock().flush_events(count);
1164 }
1165
1166 #[must_use]
1167 pub fn insert_tree<'a>(
1168 &'a self,
1169 path: impl 'a + AsRef<Path> + Send,
1170 tree: serde_json::Value,
1171 ) -> futures::future::BoxFuture<'a, ()> {
1172 use futures::FutureExt as _;
1173 use serde_json::Value::*;
1174
1175 async move {
1176 let path = path.as_ref();
1177
1178 match tree {
1179 Object(map) => {
1180 self.create_dir(path).await.unwrap();
1181 for (name, contents) in map {
1182 let mut path = PathBuf::from(path);
1183 path.push(name);
1184 self.insert_tree(&path, contents).await;
1185 }
1186 }
1187 Null => {
1188 self.create_dir(path).await.unwrap();
1189 }
1190 String(contents) => {
1191 self.insert_file(&path, contents.into_bytes()).await;
1192 }
1193 _ => {
1194 panic!("JSON object must contain only objects, strings, or null");
1195 }
1196 }
1197 }
1198 .boxed()
1199 }
1200
1201 pub fn insert_tree_from_real_fs<'a>(
1202 &'a self,
1203 path: impl 'a + AsRef<Path> + Send,
1204 src_path: impl 'a + AsRef<Path> + Send,
1205 ) -> futures::future::BoxFuture<'a, ()> {
1206 use futures::FutureExt as _;
1207
1208 async move {
1209 let path = path.as_ref();
1210 if std::fs::metadata(&src_path).unwrap().is_file() {
1211 let contents = std::fs::read(src_path).unwrap();
1212 self.insert_file(path, contents).await;
1213 } else {
1214 self.create_dir(path).await.unwrap();
1215 for entry in std::fs::read_dir(&src_path).unwrap() {
1216 let entry = entry.unwrap();
1217 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1218 .await;
1219 }
1220 }
1221 }
1222 .boxed()
1223 }
1224
1225 pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1226 where
1227 F: FnOnce(&mut FakeGitRepositoryState),
1228 {
1229 let mut state = self.state.lock();
1230 let entry = state.read_path(dot_git).unwrap();
1231 let mut entry = entry.lock();
1232
1233 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1234 let repo_state = git_repo_state.get_or_insert_with(|| {
1235 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1236 dot_git.to_path_buf(),
1237 state.git_event_tx.clone(),
1238 )))
1239 });
1240 let mut repo_state = repo_state.lock();
1241
1242 f(&mut repo_state);
1243
1244 if emit_git_event {
1245 state.emit_event([(dot_git, None)]);
1246 }
1247 } else {
1248 panic!("not a directory");
1249 }
1250 }
1251
1252 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1253 self.with_git_state(dot_git, true, |state| {
1254 let branch = branch.map(Into::into);
1255 state.branches.extend(branch.clone());
1256 state.current_branch_name = branch.map(Into::into)
1257 })
1258 }
1259
1260 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1261 self.with_git_state(dot_git, true, |state| {
1262 if let Some(first) = branches.first() {
1263 if state.current_branch_name.is_none() {
1264 state.current_branch_name = Some(first.to_string())
1265 }
1266 }
1267 state
1268 .branches
1269 .extend(branches.iter().map(ToString::to_string));
1270 })
1271 }
1272
1273 pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1274 self.with_git_state(dot_git, true, |state| {
1275 state.index_contents.clear();
1276 state.index_contents.extend(
1277 head_state
1278 .iter()
1279 .map(|(path, content)| (path.to_path_buf(), content.clone())),
1280 );
1281 });
1282 }
1283
1284 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1285 self.with_git_state(dot_git, true, |state| {
1286 state.blames.clear();
1287 state.blames.extend(
1288 blames
1289 .into_iter()
1290 .map(|(path, blame)| (path.to_path_buf(), blame)),
1291 );
1292 });
1293 }
1294
1295 pub fn set_status_for_repo_via_working_copy_change(
1296 &self,
1297 dot_git: &Path,
1298 statuses: &[(&Path, FileStatus)],
1299 ) {
1300 self.with_git_state(dot_git, false, |state| {
1301 state.statuses.clear();
1302 state.statuses.extend(
1303 statuses
1304 .iter()
1305 .map(|(path, content)| ((**path).into(), *content)),
1306 );
1307 });
1308 self.state.lock().emit_event(
1309 statuses
1310 .iter()
1311 .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1312 );
1313 }
1314
1315 pub fn set_status_for_repo_via_git_operation(
1316 &self,
1317 dot_git: &Path,
1318 statuses: &[(&Path, FileStatus)],
1319 ) {
1320 self.with_git_state(dot_git, true, |state| {
1321 state.statuses.clear();
1322 state.statuses.extend(
1323 statuses
1324 .iter()
1325 .map(|(path, content)| ((**path).into(), *content)),
1326 );
1327 });
1328 }
1329
1330 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1331 let mut result = Vec::new();
1332 let mut queue = collections::VecDeque::new();
1333 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1334 while let Some((path, entry)) = queue.pop_front() {
1335 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1336 for (name, entry) in entries {
1337 queue.push_back((path.join(name), entry.clone()));
1338 }
1339 }
1340 if include_dot_git
1341 || !path
1342 .components()
1343 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1344 {
1345 result.push(path);
1346 }
1347 }
1348 result
1349 }
1350
1351 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1352 let mut result = Vec::new();
1353 let mut queue = collections::VecDeque::new();
1354 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1355 while let Some((path, entry)) = queue.pop_front() {
1356 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1357 for (name, entry) in entries {
1358 queue.push_back((path.join(name), entry.clone()));
1359 }
1360 if include_dot_git
1361 || !path
1362 .components()
1363 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1364 {
1365 result.push(path);
1366 }
1367 }
1368 }
1369 result
1370 }
1371
1372 pub fn files(&self) -> Vec<PathBuf> {
1373 let mut result = Vec::new();
1374 let mut queue = collections::VecDeque::new();
1375 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1376 while let Some((path, entry)) = queue.pop_front() {
1377 let e = entry.lock();
1378 match &*e {
1379 FakeFsEntry::File { .. } => result.push(path),
1380 FakeFsEntry::Dir { entries, .. } => {
1381 for (name, entry) in entries {
1382 queue.push_back((path.join(name), entry.clone()));
1383 }
1384 }
1385 FakeFsEntry::Symlink { .. } => {}
1386 }
1387 }
1388 result
1389 }
1390
1391 /// How many `read_dir` calls have been issued.
1392 pub fn read_dir_call_count(&self) -> usize {
1393 self.state.lock().read_dir_call_count
1394 }
1395
1396 /// How many `metadata` calls have been issued.
1397 pub fn metadata_call_count(&self) -> usize {
1398 self.state.lock().metadata_call_count
1399 }
1400
1401 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1402 self.executor.simulate_random_delay()
1403 }
1404}
1405
1406#[cfg(any(test, feature = "test-support"))]
1407impl FakeFsEntry {
1408 fn is_file(&self) -> bool {
1409 matches!(self, Self::File { .. })
1410 }
1411
1412 fn is_symlink(&self) -> bool {
1413 matches!(self, Self::Symlink { .. })
1414 }
1415
1416 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1417 if let Self::File { content, .. } = self {
1418 Ok(content)
1419 } else {
1420 Err(anyhow!("not a file: {}", path.display()))
1421 }
1422 }
1423
1424 fn dir_entries(
1425 &mut self,
1426 path: &Path,
1427 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1428 if let Self::Dir { entries, .. } = self {
1429 Ok(entries)
1430 } else {
1431 Err(anyhow!("not a directory: {}", path.display()))
1432 }
1433 }
1434}
1435
1436#[cfg(any(test, feature = "test-support"))]
1437struct FakeWatcher {}
1438
1439#[cfg(any(test, feature = "test-support"))]
1440impl Watcher for FakeWatcher {
1441 fn add(&self, _: &Path) -> Result<()> {
1442 Ok(())
1443 }
1444
1445 fn remove(&self, _: &Path) -> Result<()> {
1446 Ok(())
1447 }
1448}
1449
1450#[cfg(any(test, feature = "test-support"))]
1451#[derive(Debug)]
1452struct FakeHandle {
1453 inode: u64,
1454}
1455
1456#[cfg(any(test, feature = "test-support"))]
1457impl FileHandle for FakeHandle {
1458 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1459 let fs = fs.as_fake();
1460 let state = fs.state.lock();
1461 let Some(target) = state.moves.get(&self.inode) else {
1462 anyhow::bail!("fake fd not moved")
1463 };
1464
1465 if state.try_read_path(&target, false).is_some() {
1466 return Ok(target.clone());
1467 }
1468 anyhow::bail!("fake fd target not found")
1469 }
1470}
1471
1472#[cfg(any(test, feature = "test-support"))]
1473#[async_trait::async_trait]
1474impl Fs for FakeFs {
1475 async fn create_dir(&self, path: &Path) -> Result<()> {
1476 self.simulate_random_delay().await;
1477
1478 let mut created_dirs = Vec::new();
1479 let mut cur_path = PathBuf::new();
1480 for component in path.components() {
1481 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1482 cur_path.push(component);
1483 if should_skip {
1484 continue;
1485 }
1486 let mut state = self.state.lock();
1487
1488 let inode = state.get_and_increment_inode();
1489 let mtime = state.get_and_increment_mtime();
1490 state.write_path(&cur_path, |entry| {
1491 entry.or_insert_with(|| {
1492 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1493 Arc::new(Mutex::new(FakeFsEntry::Dir {
1494 inode,
1495 mtime,
1496 len: 0,
1497 entries: Default::default(),
1498 git_repo_state: None,
1499 }))
1500 });
1501 Ok(())
1502 })?
1503 }
1504
1505 self.state.lock().emit_event(created_dirs);
1506 Ok(())
1507 }
1508
1509 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1510 self.simulate_random_delay().await;
1511 let mut state = self.state.lock();
1512 let inode = state.get_and_increment_inode();
1513 let mtime = state.get_and_increment_mtime();
1514 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1515 inode,
1516 mtime,
1517 len: 0,
1518 content: Vec::new(),
1519 }));
1520 let mut kind = Some(PathEventKind::Created);
1521 state.write_path(path, |entry| {
1522 match entry {
1523 btree_map::Entry::Occupied(mut e) => {
1524 if options.overwrite {
1525 kind = Some(PathEventKind::Changed);
1526 *e.get_mut() = file;
1527 } else if !options.ignore_if_exists {
1528 return Err(anyhow!("path already exists: {}", path.display()));
1529 }
1530 }
1531 btree_map::Entry::Vacant(e) => {
1532 e.insert(file);
1533 }
1534 }
1535 Ok(())
1536 })?;
1537 state.emit_event([(path, kind)]);
1538 Ok(())
1539 }
1540
1541 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1542 let mut state = self.state.lock();
1543 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1544 state
1545 .write_path(path.as_ref(), move |e| match e {
1546 btree_map::Entry::Vacant(e) => {
1547 e.insert(file);
1548 Ok(())
1549 }
1550 btree_map::Entry::Occupied(mut e) => {
1551 *e.get_mut() = file;
1552 Ok(())
1553 }
1554 })
1555 .unwrap();
1556 state.emit_event([(path, None)]);
1557
1558 Ok(())
1559 }
1560
1561 async fn create_file_with(
1562 &self,
1563 path: &Path,
1564 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1565 ) -> Result<()> {
1566 let mut bytes = Vec::new();
1567 content.read_to_end(&mut bytes).await?;
1568 self.write_file_internal(path, bytes)?;
1569 Ok(())
1570 }
1571
1572 async fn extract_tar_file(
1573 &self,
1574 path: &Path,
1575 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1576 ) -> Result<()> {
1577 let mut entries = content.entries()?;
1578 while let Some(entry) = entries.next().await {
1579 let mut entry = entry?;
1580 if entry.header().entry_type().is_file() {
1581 let path = path.join(entry.path()?.as_ref());
1582 let mut bytes = Vec::new();
1583 entry.read_to_end(&mut bytes).await?;
1584 self.create_dir(path.parent().unwrap()).await?;
1585 self.write_file_internal(&path, bytes)?;
1586 }
1587 }
1588 Ok(())
1589 }
1590
1591 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1592 self.simulate_random_delay().await;
1593
1594 let old_path = normalize_path(old_path);
1595 let new_path = normalize_path(new_path);
1596
1597 let mut state = self.state.lock();
1598 let moved_entry = state.write_path(&old_path, |e| {
1599 if let btree_map::Entry::Occupied(e) = e {
1600 Ok(e.get().clone())
1601 } else {
1602 Err(anyhow!("path does not exist: {}", &old_path.display()))
1603 }
1604 })?;
1605
1606 let inode = match *moved_entry.lock() {
1607 FakeFsEntry::File { inode, .. } => inode,
1608 FakeFsEntry::Dir { inode, .. } => inode,
1609 _ => 0,
1610 };
1611
1612 state.moves.insert(inode, new_path.clone());
1613
1614 state.write_path(&new_path, |e| {
1615 match e {
1616 btree_map::Entry::Occupied(mut e) => {
1617 if options.overwrite {
1618 *e.get_mut() = moved_entry;
1619 } else if !options.ignore_if_exists {
1620 return Err(anyhow!("path already exists: {}", new_path.display()));
1621 }
1622 }
1623 btree_map::Entry::Vacant(e) => {
1624 e.insert(moved_entry);
1625 }
1626 }
1627 Ok(())
1628 })?;
1629
1630 state
1631 .write_path(&old_path, |e| {
1632 if let btree_map::Entry::Occupied(e) = e {
1633 Ok(e.remove())
1634 } else {
1635 unreachable!()
1636 }
1637 })
1638 .unwrap();
1639
1640 state.emit_event([
1641 (old_path, Some(PathEventKind::Removed)),
1642 (new_path, Some(PathEventKind::Created)),
1643 ]);
1644 Ok(())
1645 }
1646
1647 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1648 self.simulate_random_delay().await;
1649
1650 let source = normalize_path(source);
1651 let target = normalize_path(target);
1652 let mut state = self.state.lock();
1653 let mtime = state.get_and_increment_mtime();
1654 let inode = state.get_and_increment_inode();
1655 let source_entry = state.read_path(&source)?;
1656 let content = source_entry.lock().file_content(&source)?.clone();
1657 let mut kind = Some(PathEventKind::Created);
1658 state.write_path(&target, |e| match e {
1659 btree_map::Entry::Occupied(e) => {
1660 if options.overwrite {
1661 kind = Some(PathEventKind::Changed);
1662 Ok(Some(e.get().clone()))
1663 } else if !options.ignore_if_exists {
1664 return Err(anyhow!("{target:?} already exists"));
1665 } else {
1666 Ok(None)
1667 }
1668 }
1669 btree_map::Entry::Vacant(e) => Ok(Some(
1670 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1671 inode,
1672 mtime,
1673 len: content.len() as u64,
1674 content,
1675 })))
1676 .clone(),
1677 )),
1678 })?;
1679 state.emit_event([(target, kind)]);
1680 Ok(())
1681 }
1682
1683 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1684 self.simulate_random_delay().await;
1685
1686 let path = normalize_path(path);
1687 let parent_path = path
1688 .parent()
1689 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1690 let base_name = path.file_name().unwrap();
1691
1692 let mut state = self.state.lock();
1693 let parent_entry = state.read_path(parent_path)?;
1694 let mut parent_entry = parent_entry.lock();
1695 let entry = parent_entry
1696 .dir_entries(parent_path)?
1697 .entry(base_name.to_str().unwrap().into());
1698
1699 match entry {
1700 btree_map::Entry::Vacant(_) => {
1701 if !options.ignore_if_not_exists {
1702 return Err(anyhow!("{path:?} does not exist"));
1703 }
1704 }
1705 btree_map::Entry::Occupied(e) => {
1706 {
1707 let mut entry = e.get().lock();
1708 let children = entry.dir_entries(&path)?;
1709 if !options.recursive && !children.is_empty() {
1710 return Err(anyhow!("{path:?} is not empty"));
1711 }
1712 }
1713 e.remove();
1714 }
1715 }
1716 state.emit_event([(path, Some(PathEventKind::Removed))]);
1717 Ok(())
1718 }
1719
1720 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1721 self.simulate_random_delay().await;
1722
1723 let path = normalize_path(path);
1724 let parent_path = path
1725 .parent()
1726 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1727 let base_name = path.file_name().unwrap();
1728 let mut state = self.state.lock();
1729 let parent_entry = state.read_path(parent_path)?;
1730 let mut parent_entry = parent_entry.lock();
1731 let entry = parent_entry
1732 .dir_entries(parent_path)?
1733 .entry(base_name.to_str().unwrap().into());
1734 match entry {
1735 btree_map::Entry::Vacant(_) => {
1736 if !options.ignore_if_not_exists {
1737 return Err(anyhow!("{path:?} does not exist"));
1738 }
1739 }
1740 btree_map::Entry::Occupied(e) => {
1741 e.get().lock().file_content(&path)?;
1742 e.remove();
1743 }
1744 }
1745 state.emit_event([(path, Some(PathEventKind::Removed))]);
1746 Ok(())
1747 }
1748
1749 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1750 let bytes = self.load_internal(path).await?;
1751 Ok(Box::new(io::Cursor::new(bytes)))
1752 }
1753
1754 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1755 self.simulate_random_delay().await;
1756 let state = self.state.lock();
1757 let entry = state.read_path(&path)?;
1758 let entry = entry.lock();
1759 let inode = match *entry {
1760 FakeFsEntry::File { inode, .. } => inode,
1761 FakeFsEntry::Dir { inode, .. } => inode,
1762 _ => unreachable!(),
1763 };
1764 Ok(Arc::new(FakeHandle { inode }))
1765 }
1766
1767 async fn load(&self, path: &Path) -> Result<String> {
1768 let content = self.load_internal(path).await?;
1769 Ok(String::from_utf8(content.clone())?)
1770 }
1771
1772 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1773 self.load_internal(path).await
1774 }
1775
1776 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1777 self.simulate_random_delay().await;
1778 let path = normalize_path(path.as_path());
1779 self.write_file_internal(path, data.into_bytes())?;
1780 Ok(())
1781 }
1782
1783 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1784 self.simulate_random_delay().await;
1785 let path = normalize_path(path);
1786 let content = chunks(text, line_ending).collect::<String>();
1787 if let Some(path) = path.parent() {
1788 self.create_dir(path).await?;
1789 }
1790 self.write_file_internal(path, content.into_bytes())?;
1791 Ok(())
1792 }
1793
1794 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1795 let path = normalize_path(path);
1796 self.simulate_random_delay().await;
1797 let state = self.state.lock();
1798 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1799 Ok(canonical_path)
1800 } else {
1801 Err(anyhow!("path does not exist: {}", path.display()))
1802 }
1803 }
1804
1805 async fn is_file(&self, path: &Path) -> bool {
1806 let path = normalize_path(path);
1807 self.simulate_random_delay().await;
1808 let state = self.state.lock();
1809 if let Some((entry, _)) = state.try_read_path(&path, true) {
1810 entry.lock().is_file()
1811 } else {
1812 false
1813 }
1814 }
1815
1816 async fn is_dir(&self, path: &Path) -> bool {
1817 self.metadata(path)
1818 .await
1819 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1820 }
1821
1822 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1823 self.simulate_random_delay().await;
1824 let path = normalize_path(path);
1825 let mut state = self.state.lock();
1826 state.metadata_call_count += 1;
1827 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1828 let is_symlink = entry.lock().is_symlink();
1829 if is_symlink {
1830 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1831 entry = e;
1832 } else {
1833 return Ok(None);
1834 }
1835 }
1836
1837 let entry = entry.lock();
1838 Ok(Some(match &*entry {
1839 FakeFsEntry::File {
1840 inode, mtime, len, ..
1841 } => Metadata {
1842 inode: *inode,
1843 mtime: *mtime,
1844 len: *len,
1845 is_dir: false,
1846 is_symlink,
1847 is_fifo: false,
1848 },
1849 FakeFsEntry::Dir {
1850 inode, mtime, len, ..
1851 } => Metadata {
1852 inode: *inode,
1853 mtime: *mtime,
1854 len: *len,
1855 is_dir: true,
1856 is_symlink,
1857 is_fifo: false,
1858 },
1859 FakeFsEntry::Symlink { .. } => unreachable!(),
1860 }))
1861 } else {
1862 Ok(None)
1863 }
1864 }
1865
1866 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1867 self.simulate_random_delay().await;
1868 let path = normalize_path(path);
1869 let state = self.state.lock();
1870 if let Some((entry, _)) = state.try_read_path(&path, false) {
1871 let entry = entry.lock();
1872 if let FakeFsEntry::Symlink { target } = &*entry {
1873 Ok(target.clone())
1874 } else {
1875 Err(anyhow!("not a symlink: {}", path.display()))
1876 }
1877 } else {
1878 Err(anyhow!("path does not exist: {}", path.display()))
1879 }
1880 }
1881
1882 async fn read_dir(
1883 &self,
1884 path: &Path,
1885 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1886 self.simulate_random_delay().await;
1887 let path = normalize_path(path);
1888 let mut state = self.state.lock();
1889 state.read_dir_call_count += 1;
1890 let entry = state.read_path(&path)?;
1891 let mut entry = entry.lock();
1892 let children = entry.dir_entries(&path)?;
1893 let paths = children
1894 .keys()
1895 .map(|file_name| Ok(path.join(file_name)))
1896 .collect::<Vec<_>>();
1897 Ok(Box::pin(futures::stream::iter(paths)))
1898 }
1899
1900 async fn watch(
1901 &self,
1902 path: &Path,
1903 _: Duration,
1904 ) -> (
1905 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1906 Arc<dyn Watcher>,
1907 ) {
1908 self.simulate_random_delay().await;
1909 let (tx, rx) = smol::channel::unbounded();
1910 self.state.lock().event_txs.push(tx);
1911 let path = path.to_path_buf();
1912 let executor = self.executor.clone();
1913 (
1914 Box::pin(futures::StreamExt::filter(rx, move |events| {
1915 let result = events
1916 .iter()
1917 .any(|evt_path| evt_path.path.starts_with(&path));
1918 let executor = executor.clone();
1919 async move {
1920 executor.simulate_random_delay().await;
1921 result
1922 }
1923 })),
1924 Arc::new(FakeWatcher {}),
1925 )
1926 }
1927
1928 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1929 let state = self.state.lock();
1930 let entry = state.read_path(abs_dot_git).unwrap();
1931 let mut entry = entry.lock();
1932 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1933 let state = git_repo_state
1934 .get_or_insert_with(|| {
1935 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1936 abs_dot_git.to_path_buf(),
1937 state.git_event_tx.clone(),
1938 )))
1939 })
1940 .clone();
1941 Some(git::repository::FakeGitRepository::open(state))
1942 } else {
1943 None
1944 }
1945 }
1946
1947 fn is_fake(&self) -> bool {
1948 true
1949 }
1950
1951 async fn is_case_sensitive(&self) -> Result<bool> {
1952 Ok(true)
1953 }
1954
1955 #[cfg(any(test, feature = "test-support"))]
1956 fn as_fake(&self) -> Arc<FakeFs> {
1957 self.this.upgrade().unwrap()
1958 }
1959}
1960
1961fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1962 rope.chunks().flat_map(move |chunk| {
1963 let mut newline = false;
1964 chunk.split('\n').flat_map(move |line| {
1965 let ending = if newline {
1966 Some(line_ending.as_str())
1967 } else {
1968 None
1969 };
1970 newline = true;
1971 ending.into_iter().chain([line])
1972 })
1973 })
1974}
1975
1976pub fn normalize_path(path: &Path) -> PathBuf {
1977 let mut components = path.components().peekable();
1978 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1979 components.next();
1980 PathBuf::from(c.as_os_str())
1981 } else {
1982 PathBuf::new()
1983 };
1984
1985 for component in components {
1986 match component {
1987 Component::Prefix(..) => unreachable!(),
1988 Component::RootDir => {
1989 ret.push(component.as_os_str());
1990 }
1991 Component::CurDir => {}
1992 Component::ParentDir => {
1993 ret.pop();
1994 }
1995 Component::Normal(c) => {
1996 ret.push(c);
1997 }
1998 }
1999 }
2000 ret
2001}
2002
2003pub fn copy_recursive<'a>(
2004 fs: &'a dyn Fs,
2005 source: &'a Path,
2006 target: &'a Path,
2007 options: CopyOptions,
2008) -> BoxFuture<'a, Result<()>> {
2009 use futures::future::FutureExt;
2010
2011 async move {
2012 let metadata = fs
2013 .metadata(source)
2014 .await?
2015 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2016 if metadata.is_dir {
2017 if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
2018 if options.ignore_if_exists {
2019 return Ok(());
2020 } else {
2021 return Err(anyhow!("{target:?} already exists"));
2022 }
2023 }
2024
2025 let _ = fs
2026 .remove_dir(
2027 target,
2028 RemoveOptions {
2029 recursive: true,
2030 ignore_if_not_exists: true,
2031 },
2032 )
2033 .await;
2034 fs.create_dir(target).await?;
2035 let mut children = fs.read_dir(source).await?;
2036 while let Some(child_path) = children.next().await {
2037 if let Ok(child_path) = child_path {
2038 if let Some(file_name) = child_path.file_name() {
2039 let child_target_path = target.join(file_name);
2040 copy_recursive(fs, &child_path, &child_target_path, options).await?;
2041 }
2042 }
2043 }
2044
2045 Ok(())
2046 } else {
2047 fs.copy_file(source, target, options).await
2048 }
2049 }
2050 .boxed()
2051}
2052
2053// todo(windows)
2054// can we get file id not open the file twice?
2055// https://github.com/rust-lang/rust/issues/63010
2056#[cfg(target_os = "windows")]
2057async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2058 use std::os::windows::io::AsRawHandle;
2059
2060 use smol::fs::windows::OpenOptionsExt;
2061 use windows::Win32::{
2062 Foundation::HANDLE,
2063 Storage::FileSystem::{
2064 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2065 },
2066 };
2067
2068 let file = smol::fs::OpenOptions::new()
2069 .read(true)
2070 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2071 .open(path)
2072 .await?;
2073
2074 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2075 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2076 // This function supports Windows XP+
2077 smol::unblock(move || {
2078 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2079
2080 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2081 })
2082 .await
2083}
2084
2085#[cfg(test)]
2086mod tests {
2087 use super::*;
2088 use gpui::BackgroundExecutor;
2089 use serde_json::json;
2090
2091 #[gpui::test]
2092 async fn test_fake_fs(executor: BackgroundExecutor) {
2093 let fs = FakeFs::new(executor.clone());
2094 fs.insert_tree(
2095 "/root",
2096 json!({
2097 "dir1": {
2098 "a": "A",
2099 "b": "B"
2100 },
2101 "dir2": {
2102 "c": "C",
2103 "dir3": {
2104 "d": "D"
2105 }
2106 }
2107 }),
2108 )
2109 .await;
2110
2111 assert_eq!(
2112 fs.files(),
2113 vec![
2114 PathBuf::from("/root/dir1/a"),
2115 PathBuf::from("/root/dir1/b"),
2116 PathBuf::from("/root/dir2/c"),
2117 PathBuf::from("/root/dir2/dir3/d"),
2118 ]
2119 );
2120
2121 fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2122 .await
2123 .unwrap();
2124
2125 assert_eq!(
2126 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2127 .await
2128 .unwrap(),
2129 PathBuf::from("/root/dir2/dir3"),
2130 );
2131 assert_eq!(
2132 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2133 .await
2134 .unwrap(),
2135 PathBuf::from("/root/dir2/dir3/d"),
2136 );
2137 assert_eq!(
2138 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2139 "D",
2140 );
2141 }
2142}