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