1#[cfg(target_os = "macos")]
2mod mac_watcher;
3
4#[cfg(not(target_os = "macos"))]
5pub mod fs_watcher;
6
7use anyhow::{anyhow, Context as _, Result};
8use git::GitHostingProviderRegistry;
9#[cfg(any(test, feature = "test-support"))]
10use git::{repository::RepoPath, status::FileStatus};
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::{App, 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 + Send + Sync>>;
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: &App) -> 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 App) {
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 + Send + Sync>> {
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, index_state: &[(RepoPath, String)]) {
1274 self.with_git_state(dot_git, true, |state| {
1275 state.index_contents.clear();
1276 state.index_contents.extend(
1277 index_state
1278 .iter()
1279 .map(|(path, content)| (path.clone(), content.clone())),
1280 );
1281 });
1282 }
1283
1284 pub fn set_head_for_repo(&self, dot_git: &Path, head_state: &[(RepoPath, String)]) {
1285 self.with_git_state(dot_git, true, |state| {
1286 state.head_contents.clear();
1287 state.head_contents.extend(
1288 head_state
1289 .iter()
1290 .map(|(path, content)| (path.clone(), content.clone())),
1291 );
1292 });
1293 }
1294
1295 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1296 self.with_git_state(dot_git, true, |state| {
1297 state.blames.clear();
1298 state.blames.extend(blames);
1299 });
1300 }
1301
1302 pub fn set_status_for_repo_via_working_copy_change(
1303 &self,
1304 dot_git: &Path,
1305 statuses: &[(&Path, FileStatus)],
1306 ) {
1307 self.with_git_state(dot_git, false, |state| {
1308 state.statuses.clear();
1309 state.statuses.extend(
1310 statuses
1311 .iter()
1312 .map(|(path, content)| ((**path).into(), *content)),
1313 );
1314 });
1315 self.state.lock().emit_event(
1316 statuses
1317 .iter()
1318 .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1319 );
1320 }
1321
1322 pub fn set_status_for_repo_via_git_operation(
1323 &self,
1324 dot_git: &Path,
1325 statuses: &[(&Path, FileStatus)],
1326 ) {
1327 self.with_git_state(dot_git, true, |state| {
1328 state.statuses.clear();
1329 state.statuses.extend(
1330 statuses
1331 .iter()
1332 .map(|(path, content)| ((**path).into(), *content)),
1333 );
1334 });
1335 }
1336
1337 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1338 let mut result = Vec::new();
1339 let mut queue = collections::VecDeque::new();
1340 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1341 while let Some((path, entry)) = queue.pop_front() {
1342 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1343 for (name, entry) in entries {
1344 queue.push_back((path.join(name), entry.clone()));
1345 }
1346 }
1347 if include_dot_git
1348 || !path
1349 .components()
1350 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1351 {
1352 result.push(path);
1353 }
1354 }
1355 result
1356 }
1357
1358 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1359 let mut result = Vec::new();
1360 let mut queue = collections::VecDeque::new();
1361 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1362 while let Some((path, entry)) = queue.pop_front() {
1363 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1364 for (name, entry) in entries {
1365 queue.push_back((path.join(name), entry.clone()));
1366 }
1367 if include_dot_git
1368 || !path
1369 .components()
1370 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1371 {
1372 result.push(path);
1373 }
1374 }
1375 }
1376 result
1377 }
1378
1379 pub fn files(&self) -> Vec<PathBuf> {
1380 let mut result = Vec::new();
1381 let mut queue = collections::VecDeque::new();
1382 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1383 while let Some((path, entry)) = queue.pop_front() {
1384 let e = entry.lock();
1385 match &*e {
1386 FakeFsEntry::File { .. } => result.push(path),
1387 FakeFsEntry::Dir { entries, .. } => {
1388 for (name, entry) in entries {
1389 queue.push_back((path.join(name), entry.clone()));
1390 }
1391 }
1392 FakeFsEntry::Symlink { .. } => {}
1393 }
1394 }
1395 result
1396 }
1397
1398 /// How many `read_dir` calls have been issued.
1399 pub fn read_dir_call_count(&self) -> usize {
1400 self.state.lock().read_dir_call_count
1401 }
1402
1403 /// How many `metadata` calls have been issued.
1404 pub fn metadata_call_count(&self) -> usize {
1405 self.state.lock().metadata_call_count
1406 }
1407
1408 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1409 self.executor.simulate_random_delay()
1410 }
1411}
1412
1413#[cfg(any(test, feature = "test-support"))]
1414impl FakeFsEntry {
1415 fn is_file(&self) -> bool {
1416 matches!(self, Self::File { .. })
1417 }
1418
1419 fn is_symlink(&self) -> bool {
1420 matches!(self, Self::Symlink { .. })
1421 }
1422
1423 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1424 if let Self::File { content, .. } = self {
1425 Ok(content)
1426 } else {
1427 Err(anyhow!("not a file: {}", path.display()))
1428 }
1429 }
1430
1431 fn dir_entries(
1432 &mut self,
1433 path: &Path,
1434 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1435 if let Self::Dir { entries, .. } = self {
1436 Ok(entries)
1437 } else {
1438 Err(anyhow!("not a directory: {}", path.display()))
1439 }
1440 }
1441}
1442
1443#[cfg(any(test, feature = "test-support"))]
1444struct FakeWatcher {}
1445
1446#[cfg(any(test, feature = "test-support"))]
1447impl Watcher for FakeWatcher {
1448 fn add(&self, _: &Path) -> Result<()> {
1449 Ok(())
1450 }
1451
1452 fn remove(&self, _: &Path) -> Result<()> {
1453 Ok(())
1454 }
1455}
1456
1457#[cfg(any(test, feature = "test-support"))]
1458#[derive(Debug)]
1459struct FakeHandle {
1460 inode: u64,
1461}
1462
1463#[cfg(any(test, feature = "test-support"))]
1464impl FileHandle for FakeHandle {
1465 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1466 let fs = fs.as_fake();
1467 let state = fs.state.lock();
1468 let Some(target) = state.moves.get(&self.inode) else {
1469 anyhow::bail!("fake fd not moved")
1470 };
1471
1472 if state.try_read_path(&target, false).is_some() {
1473 return Ok(target.clone());
1474 }
1475 anyhow::bail!("fake fd target not found")
1476 }
1477}
1478
1479#[cfg(any(test, feature = "test-support"))]
1480#[async_trait::async_trait]
1481impl Fs for FakeFs {
1482 async fn create_dir(&self, path: &Path) -> Result<()> {
1483 self.simulate_random_delay().await;
1484
1485 let mut created_dirs = Vec::new();
1486 let mut cur_path = PathBuf::new();
1487 for component in path.components() {
1488 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1489 cur_path.push(component);
1490 if should_skip {
1491 continue;
1492 }
1493 let mut state = self.state.lock();
1494
1495 let inode = state.get_and_increment_inode();
1496 let mtime = state.get_and_increment_mtime();
1497 state.write_path(&cur_path, |entry| {
1498 entry.or_insert_with(|| {
1499 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1500 Arc::new(Mutex::new(FakeFsEntry::Dir {
1501 inode,
1502 mtime,
1503 len: 0,
1504 entries: Default::default(),
1505 git_repo_state: None,
1506 }))
1507 });
1508 Ok(())
1509 })?
1510 }
1511
1512 self.state.lock().emit_event(created_dirs);
1513 Ok(())
1514 }
1515
1516 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1517 self.simulate_random_delay().await;
1518 let mut state = self.state.lock();
1519 let inode = state.get_and_increment_inode();
1520 let mtime = state.get_and_increment_mtime();
1521 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1522 inode,
1523 mtime,
1524 len: 0,
1525 content: Vec::new(),
1526 }));
1527 let mut kind = Some(PathEventKind::Created);
1528 state.write_path(path, |entry| {
1529 match entry {
1530 btree_map::Entry::Occupied(mut e) => {
1531 if options.overwrite {
1532 kind = Some(PathEventKind::Changed);
1533 *e.get_mut() = file;
1534 } else if !options.ignore_if_exists {
1535 return Err(anyhow!("path already exists: {}", path.display()));
1536 }
1537 }
1538 btree_map::Entry::Vacant(e) => {
1539 e.insert(file);
1540 }
1541 }
1542 Ok(())
1543 })?;
1544 state.emit_event([(path, kind)]);
1545 Ok(())
1546 }
1547
1548 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1549 let mut state = self.state.lock();
1550 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1551 state
1552 .write_path(path.as_ref(), move |e| match e {
1553 btree_map::Entry::Vacant(e) => {
1554 e.insert(file);
1555 Ok(())
1556 }
1557 btree_map::Entry::Occupied(mut e) => {
1558 *e.get_mut() = file;
1559 Ok(())
1560 }
1561 })
1562 .unwrap();
1563 state.emit_event([(path, None)]);
1564
1565 Ok(())
1566 }
1567
1568 async fn create_file_with(
1569 &self,
1570 path: &Path,
1571 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1572 ) -> Result<()> {
1573 let mut bytes = Vec::new();
1574 content.read_to_end(&mut bytes).await?;
1575 self.write_file_internal(path, bytes)?;
1576 Ok(())
1577 }
1578
1579 async fn extract_tar_file(
1580 &self,
1581 path: &Path,
1582 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1583 ) -> Result<()> {
1584 let mut entries = content.entries()?;
1585 while let Some(entry) = entries.next().await {
1586 let mut entry = entry?;
1587 if entry.header().entry_type().is_file() {
1588 let path = path.join(entry.path()?.as_ref());
1589 let mut bytes = Vec::new();
1590 entry.read_to_end(&mut bytes).await?;
1591 self.create_dir(path.parent().unwrap()).await?;
1592 self.write_file_internal(&path, bytes)?;
1593 }
1594 }
1595 Ok(())
1596 }
1597
1598 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1599 self.simulate_random_delay().await;
1600
1601 let old_path = normalize_path(old_path);
1602 let new_path = normalize_path(new_path);
1603
1604 let mut state = self.state.lock();
1605 let moved_entry = state.write_path(&old_path, |e| {
1606 if let btree_map::Entry::Occupied(e) = e {
1607 Ok(e.get().clone())
1608 } else {
1609 Err(anyhow!("path does not exist: {}", &old_path.display()))
1610 }
1611 })?;
1612
1613 let inode = match *moved_entry.lock() {
1614 FakeFsEntry::File { inode, .. } => inode,
1615 FakeFsEntry::Dir { inode, .. } => inode,
1616 _ => 0,
1617 };
1618
1619 state.moves.insert(inode, new_path.clone());
1620
1621 state.write_path(&new_path, |e| {
1622 match e {
1623 btree_map::Entry::Occupied(mut e) => {
1624 if options.overwrite {
1625 *e.get_mut() = moved_entry;
1626 } else if !options.ignore_if_exists {
1627 return Err(anyhow!("path already exists: {}", new_path.display()));
1628 }
1629 }
1630 btree_map::Entry::Vacant(e) => {
1631 e.insert(moved_entry);
1632 }
1633 }
1634 Ok(())
1635 })?;
1636
1637 state
1638 .write_path(&old_path, |e| {
1639 if let btree_map::Entry::Occupied(e) = e {
1640 Ok(e.remove())
1641 } else {
1642 unreachable!()
1643 }
1644 })
1645 .unwrap();
1646
1647 state.emit_event([
1648 (old_path, Some(PathEventKind::Removed)),
1649 (new_path, Some(PathEventKind::Created)),
1650 ]);
1651 Ok(())
1652 }
1653
1654 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1655 self.simulate_random_delay().await;
1656
1657 let source = normalize_path(source);
1658 let target = normalize_path(target);
1659 let mut state = self.state.lock();
1660 let mtime = state.get_and_increment_mtime();
1661 let inode = state.get_and_increment_inode();
1662 let source_entry = state.read_path(&source)?;
1663 let content = source_entry.lock().file_content(&source)?.clone();
1664 let mut kind = Some(PathEventKind::Created);
1665 state.write_path(&target, |e| match e {
1666 btree_map::Entry::Occupied(e) => {
1667 if options.overwrite {
1668 kind = Some(PathEventKind::Changed);
1669 Ok(Some(e.get().clone()))
1670 } else if !options.ignore_if_exists {
1671 return Err(anyhow!("{target:?} already exists"));
1672 } else {
1673 Ok(None)
1674 }
1675 }
1676 btree_map::Entry::Vacant(e) => Ok(Some(
1677 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1678 inode,
1679 mtime,
1680 len: content.len() as u64,
1681 content,
1682 })))
1683 .clone(),
1684 )),
1685 })?;
1686 state.emit_event([(target, kind)]);
1687 Ok(())
1688 }
1689
1690 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1691 self.simulate_random_delay().await;
1692
1693 let path = normalize_path(path);
1694 let parent_path = path
1695 .parent()
1696 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1697 let base_name = path.file_name().unwrap();
1698
1699 let mut state = self.state.lock();
1700 let parent_entry = state.read_path(parent_path)?;
1701 let mut parent_entry = parent_entry.lock();
1702 let entry = parent_entry
1703 .dir_entries(parent_path)?
1704 .entry(base_name.to_str().unwrap().into());
1705
1706 match entry {
1707 btree_map::Entry::Vacant(_) => {
1708 if !options.ignore_if_not_exists {
1709 return Err(anyhow!("{path:?} does not exist"));
1710 }
1711 }
1712 btree_map::Entry::Occupied(e) => {
1713 {
1714 let mut entry = e.get().lock();
1715 let children = entry.dir_entries(&path)?;
1716 if !options.recursive && !children.is_empty() {
1717 return Err(anyhow!("{path:?} is not empty"));
1718 }
1719 }
1720 e.remove();
1721 }
1722 }
1723 state.emit_event([(path, Some(PathEventKind::Removed))]);
1724 Ok(())
1725 }
1726
1727 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1728 self.simulate_random_delay().await;
1729
1730 let path = normalize_path(path);
1731 let parent_path = path
1732 .parent()
1733 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1734 let base_name = path.file_name().unwrap();
1735 let mut state = self.state.lock();
1736 let parent_entry = state.read_path(parent_path)?;
1737 let mut parent_entry = parent_entry.lock();
1738 let entry = parent_entry
1739 .dir_entries(parent_path)?
1740 .entry(base_name.to_str().unwrap().into());
1741 match entry {
1742 btree_map::Entry::Vacant(_) => {
1743 if !options.ignore_if_not_exists {
1744 return Err(anyhow!("{path:?} does not exist"));
1745 }
1746 }
1747 btree_map::Entry::Occupied(e) => {
1748 e.get().lock().file_content(&path)?;
1749 e.remove();
1750 }
1751 }
1752 state.emit_event([(path, Some(PathEventKind::Removed))]);
1753 Ok(())
1754 }
1755
1756 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
1757 let bytes = self.load_internal(path).await?;
1758 Ok(Box::new(io::Cursor::new(bytes)))
1759 }
1760
1761 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1762 self.simulate_random_delay().await;
1763 let state = self.state.lock();
1764 let entry = state.read_path(&path)?;
1765 let entry = entry.lock();
1766 let inode = match *entry {
1767 FakeFsEntry::File { inode, .. } => inode,
1768 FakeFsEntry::Dir { inode, .. } => inode,
1769 _ => unreachable!(),
1770 };
1771 Ok(Arc::new(FakeHandle { inode }))
1772 }
1773
1774 async fn load(&self, path: &Path) -> Result<String> {
1775 let content = self.load_internal(path).await?;
1776 Ok(String::from_utf8(content.clone())?)
1777 }
1778
1779 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1780 self.load_internal(path).await
1781 }
1782
1783 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1784 self.simulate_random_delay().await;
1785 let path = normalize_path(path.as_path());
1786 self.write_file_internal(path, data.into_bytes())?;
1787 Ok(())
1788 }
1789
1790 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1791 self.simulate_random_delay().await;
1792 let path = normalize_path(path);
1793 let content = chunks(text, line_ending).collect::<String>();
1794 if let Some(path) = path.parent() {
1795 self.create_dir(path).await?;
1796 }
1797 self.write_file_internal(path, content.into_bytes())?;
1798 Ok(())
1799 }
1800
1801 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1802 let path = normalize_path(path);
1803 self.simulate_random_delay().await;
1804 let state = self.state.lock();
1805 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1806 Ok(canonical_path)
1807 } else {
1808 Err(anyhow!("path does not exist: {}", path.display()))
1809 }
1810 }
1811
1812 async fn is_file(&self, path: &Path) -> bool {
1813 let path = normalize_path(path);
1814 self.simulate_random_delay().await;
1815 let state = self.state.lock();
1816 if let Some((entry, _)) = state.try_read_path(&path, true) {
1817 entry.lock().is_file()
1818 } else {
1819 false
1820 }
1821 }
1822
1823 async fn is_dir(&self, path: &Path) -> bool {
1824 self.metadata(path)
1825 .await
1826 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1827 }
1828
1829 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1830 self.simulate_random_delay().await;
1831 let path = normalize_path(path);
1832 let mut state = self.state.lock();
1833 state.metadata_call_count += 1;
1834 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1835 let is_symlink = entry.lock().is_symlink();
1836 if is_symlink {
1837 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1838 entry = e;
1839 } else {
1840 return Ok(None);
1841 }
1842 }
1843
1844 let entry = entry.lock();
1845 Ok(Some(match &*entry {
1846 FakeFsEntry::File {
1847 inode, mtime, len, ..
1848 } => Metadata {
1849 inode: *inode,
1850 mtime: *mtime,
1851 len: *len,
1852 is_dir: false,
1853 is_symlink,
1854 is_fifo: false,
1855 },
1856 FakeFsEntry::Dir {
1857 inode, mtime, len, ..
1858 } => Metadata {
1859 inode: *inode,
1860 mtime: *mtime,
1861 len: *len,
1862 is_dir: true,
1863 is_symlink,
1864 is_fifo: false,
1865 },
1866 FakeFsEntry::Symlink { .. } => unreachable!(),
1867 }))
1868 } else {
1869 Ok(None)
1870 }
1871 }
1872
1873 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1874 self.simulate_random_delay().await;
1875 let path = normalize_path(path);
1876 let state = self.state.lock();
1877 if let Some((entry, _)) = state.try_read_path(&path, false) {
1878 let entry = entry.lock();
1879 if let FakeFsEntry::Symlink { target } = &*entry {
1880 Ok(target.clone())
1881 } else {
1882 Err(anyhow!("not a symlink: {}", path.display()))
1883 }
1884 } else {
1885 Err(anyhow!("path does not exist: {}", path.display()))
1886 }
1887 }
1888
1889 async fn read_dir(
1890 &self,
1891 path: &Path,
1892 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1893 self.simulate_random_delay().await;
1894 let path = normalize_path(path);
1895 let mut state = self.state.lock();
1896 state.read_dir_call_count += 1;
1897 let entry = state.read_path(&path)?;
1898 let mut entry = entry.lock();
1899 let children = entry.dir_entries(&path)?;
1900 let paths = children
1901 .keys()
1902 .map(|file_name| Ok(path.join(file_name)))
1903 .collect::<Vec<_>>();
1904 Ok(Box::pin(futures::stream::iter(paths)))
1905 }
1906
1907 async fn watch(
1908 &self,
1909 path: &Path,
1910 _: Duration,
1911 ) -> (
1912 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1913 Arc<dyn Watcher>,
1914 ) {
1915 self.simulate_random_delay().await;
1916 let (tx, rx) = smol::channel::unbounded();
1917 self.state.lock().event_txs.push(tx);
1918 let path = path.to_path_buf();
1919 let executor = self.executor.clone();
1920 (
1921 Box::pin(futures::StreamExt::filter(rx, move |events| {
1922 let result = events
1923 .iter()
1924 .any(|evt_path| evt_path.path.starts_with(&path));
1925 let executor = executor.clone();
1926 async move {
1927 executor.simulate_random_delay().await;
1928 result
1929 }
1930 })),
1931 Arc::new(FakeWatcher {}),
1932 )
1933 }
1934
1935 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1936 let state = self.state.lock();
1937 let entry = state.read_path(abs_dot_git).unwrap();
1938 let mut entry = entry.lock();
1939 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1940 let state = git_repo_state
1941 .get_or_insert_with(|| {
1942 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1943 abs_dot_git.to_path_buf(),
1944 state.git_event_tx.clone(),
1945 )))
1946 })
1947 .clone();
1948 Some(git::repository::FakeGitRepository::open(state))
1949 } else {
1950 None
1951 }
1952 }
1953
1954 fn is_fake(&self) -> bool {
1955 true
1956 }
1957
1958 async fn is_case_sensitive(&self) -> Result<bool> {
1959 Ok(true)
1960 }
1961
1962 #[cfg(any(test, feature = "test-support"))]
1963 fn as_fake(&self) -> Arc<FakeFs> {
1964 self.this.upgrade().unwrap()
1965 }
1966}
1967
1968fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1969 rope.chunks().flat_map(move |chunk| {
1970 let mut newline = false;
1971 chunk.split('\n').flat_map(move |line| {
1972 let ending = if newline {
1973 Some(line_ending.as_str())
1974 } else {
1975 None
1976 };
1977 newline = true;
1978 ending.into_iter().chain([line])
1979 })
1980 })
1981}
1982
1983pub fn normalize_path(path: &Path) -> PathBuf {
1984 let mut components = path.components().peekable();
1985 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1986 components.next();
1987 PathBuf::from(c.as_os_str())
1988 } else {
1989 PathBuf::new()
1990 };
1991
1992 for component in components {
1993 match component {
1994 Component::Prefix(..) => unreachable!(),
1995 Component::RootDir => {
1996 ret.push(component.as_os_str());
1997 }
1998 Component::CurDir => {}
1999 Component::ParentDir => {
2000 ret.pop();
2001 }
2002 Component::Normal(c) => {
2003 ret.push(c);
2004 }
2005 }
2006 }
2007 ret
2008}
2009
2010pub fn copy_recursive<'a>(
2011 fs: &'a dyn Fs,
2012 source: &'a Path,
2013 target: &'a Path,
2014 options: CopyOptions,
2015) -> BoxFuture<'a, Result<()>> {
2016 use futures::future::FutureExt;
2017
2018 async move {
2019 let metadata = fs
2020 .metadata(source)
2021 .await?
2022 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2023 if metadata.is_dir {
2024 if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
2025 if options.ignore_if_exists {
2026 return Ok(());
2027 } else {
2028 return Err(anyhow!("{target:?} already exists"));
2029 }
2030 }
2031
2032 let _ = fs
2033 .remove_dir(
2034 target,
2035 RemoveOptions {
2036 recursive: true,
2037 ignore_if_not_exists: true,
2038 },
2039 )
2040 .await;
2041 fs.create_dir(target).await?;
2042 let mut children = fs.read_dir(source).await?;
2043 while let Some(child_path) = children.next().await {
2044 if let Ok(child_path) = child_path {
2045 if let Some(file_name) = child_path.file_name() {
2046 let child_target_path = target.join(file_name);
2047 copy_recursive(fs, &child_path, &child_target_path, options).await?;
2048 }
2049 }
2050 }
2051
2052 Ok(())
2053 } else {
2054 fs.copy_file(source, target, options).await
2055 }
2056 }
2057 .boxed()
2058}
2059
2060// todo(windows)
2061// can we get file id not open the file twice?
2062// https://github.com/rust-lang/rust/issues/63010
2063#[cfg(target_os = "windows")]
2064async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2065 use std::os::windows::io::AsRawHandle;
2066
2067 use smol::fs::windows::OpenOptionsExt;
2068 use windows::Win32::{
2069 Foundation::HANDLE,
2070 Storage::FileSystem::{
2071 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2072 },
2073 };
2074
2075 let file = smol::fs::OpenOptions::new()
2076 .read(true)
2077 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2078 .open(path)
2079 .await?;
2080
2081 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2082 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2083 // This function supports Windows XP+
2084 smol::unblock(move || {
2085 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2086
2087 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2088 })
2089 .await
2090}
2091
2092#[cfg(test)]
2093mod tests {
2094 use super::*;
2095 use gpui::BackgroundExecutor;
2096 use serde_json::json;
2097
2098 #[gpui::test]
2099 async fn test_fake_fs(executor: BackgroundExecutor) {
2100 let fs = FakeFs::new(executor.clone());
2101 fs.insert_tree(
2102 "/root",
2103 json!({
2104 "dir1": {
2105 "a": "A",
2106 "b": "B"
2107 },
2108 "dir2": {
2109 "c": "C",
2110 "dir3": {
2111 "d": "D"
2112 }
2113 }
2114 }),
2115 )
2116 .await;
2117
2118 assert_eq!(
2119 fs.files(),
2120 vec![
2121 PathBuf::from("/root/dir1/a"),
2122 PathBuf::from("/root/dir1/b"),
2123 PathBuf::from("/root/dir2/c"),
2124 PathBuf::from("/root/dir2/dir3/d"),
2125 ]
2126 );
2127
2128 fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2129 .await
2130 .unwrap();
2131
2132 assert_eq!(
2133 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2134 .await
2135 .unwrap(),
2136 PathBuf::from("/root/dir2/dir3"),
2137 );
2138 assert_eq!(
2139 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2140 .await
2141 .unwrap(),
2142 PathBuf::from("/root/dir2/dir3/d"),
2143 );
2144 assert_eq!(
2145 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2146 "D",
2147 );
2148 }
2149}