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