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((
1383 PathBuf::from(util::path!("/")),
1384 self.state.lock().root.clone(),
1385 ));
1386 while let Some((path, entry)) = queue.pop_front() {
1387 let e = entry.lock();
1388 match &*e {
1389 FakeFsEntry::File { .. } => result.push(path),
1390 FakeFsEntry::Dir { entries, .. } => {
1391 for (name, entry) in entries {
1392 queue.push_back((path.join(name), entry.clone()));
1393 }
1394 }
1395 FakeFsEntry::Symlink { .. } => {}
1396 }
1397 }
1398 result
1399 }
1400
1401 /// How many `read_dir` calls have been issued.
1402 pub fn read_dir_call_count(&self) -> usize {
1403 self.state.lock().read_dir_call_count
1404 }
1405
1406 /// How many `metadata` calls have been issued.
1407 pub fn metadata_call_count(&self) -> usize {
1408 self.state.lock().metadata_call_count
1409 }
1410
1411 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1412 self.executor.simulate_random_delay()
1413 }
1414}
1415
1416#[cfg(any(test, feature = "test-support"))]
1417impl FakeFsEntry {
1418 fn is_file(&self) -> bool {
1419 matches!(self, Self::File { .. })
1420 }
1421
1422 fn is_symlink(&self) -> bool {
1423 matches!(self, Self::Symlink { .. })
1424 }
1425
1426 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1427 if let Self::File { content, .. } = self {
1428 Ok(content)
1429 } else {
1430 Err(anyhow!("not a file: {}", path.display()))
1431 }
1432 }
1433
1434 fn dir_entries(
1435 &mut self,
1436 path: &Path,
1437 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1438 if let Self::Dir { entries, .. } = self {
1439 Ok(entries)
1440 } else {
1441 Err(anyhow!("not a directory: {}", path.display()))
1442 }
1443 }
1444}
1445
1446#[cfg(any(test, feature = "test-support"))]
1447struct FakeWatcher {}
1448
1449#[cfg(any(test, feature = "test-support"))]
1450impl Watcher for FakeWatcher {
1451 fn add(&self, _: &Path) -> Result<()> {
1452 Ok(())
1453 }
1454
1455 fn remove(&self, _: &Path) -> Result<()> {
1456 Ok(())
1457 }
1458}
1459
1460#[cfg(any(test, feature = "test-support"))]
1461#[derive(Debug)]
1462struct FakeHandle {
1463 inode: u64,
1464}
1465
1466#[cfg(any(test, feature = "test-support"))]
1467impl FileHandle for FakeHandle {
1468 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1469 let fs = fs.as_fake();
1470 let state = fs.state.lock();
1471 let Some(target) = state.moves.get(&self.inode) else {
1472 anyhow::bail!("fake fd not moved")
1473 };
1474
1475 if state.try_read_path(&target, false).is_some() {
1476 return Ok(target.clone());
1477 }
1478 anyhow::bail!("fake fd target not found")
1479 }
1480}
1481
1482#[cfg(any(test, feature = "test-support"))]
1483#[async_trait::async_trait]
1484impl Fs for FakeFs {
1485 async fn create_dir(&self, path: &Path) -> Result<()> {
1486 self.simulate_random_delay().await;
1487
1488 let mut created_dirs = Vec::new();
1489 let mut cur_path = PathBuf::new();
1490 for component in path.components() {
1491 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1492 cur_path.push(component);
1493 if should_skip {
1494 continue;
1495 }
1496 let mut state = self.state.lock();
1497
1498 let inode = state.get_and_increment_inode();
1499 let mtime = state.get_and_increment_mtime();
1500 state.write_path(&cur_path, |entry| {
1501 entry.or_insert_with(|| {
1502 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1503 Arc::new(Mutex::new(FakeFsEntry::Dir {
1504 inode,
1505 mtime,
1506 len: 0,
1507 entries: Default::default(),
1508 git_repo_state: None,
1509 }))
1510 });
1511 Ok(())
1512 })?
1513 }
1514
1515 self.state.lock().emit_event(created_dirs);
1516 Ok(())
1517 }
1518
1519 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1520 self.simulate_random_delay().await;
1521 let mut state = self.state.lock();
1522 let inode = state.get_and_increment_inode();
1523 let mtime = state.get_and_increment_mtime();
1524 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1525 inode,
1526 mtime,
1527 len: 0,
1528 content: Vec::new(),
1529 }));
1530 let mut kind = Some(PathEventKind::Created);
1531 state.write_path(path, |entry| {
1532 match entry {
1533 btree_map::Entry::Occupied(mut e) => {
1534 if options.overwrite {
1535 kind = Some(PathEventKind::Changed);
1536 *e.get_mut() = file;
1537 } else if !options.ignore_if_exists {
1538 return Err(anyhow!("path already exists: {}", path.display()));
1539 }
1540 }
1541 btree_map::Entry::Vacant(e) => {
1542 e.insert(file);
1543 }
1544 }
1545 Ok(())
1546 })?;
1547 state.emit_event([(path, kind)]);
1548 Ok(())
1549 }
1550
1551 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1552 let mut state = self.state.lock();
1553 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1554 state
1555 .write_path(path.as_ref(), move |e| match e {
1556 btree_map::Entry::Vacant(e) => {
1557 e.insert(file);
1558 Ok(())
1559 }
1560 btree_map::Entry::Occupied(mut e) => {
1561 *e.get_mut() = file;
1562 Ok(())
1563 }
1564 })
1565 .unwrap();
1566 state.emit_event([(path, None)]);
1567
1568 Ok(())
1569 }
1570
1571 async fn create_file_with(
1572 &self,
1573 path: &Path,
1574 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1575 ) -> Result<()> {
1576 let mut bytes = Vec::new();
1577 content.read_to_end(&mut bytes).await?;
1578 self.write_file_internal(path, bytes)?;
1579 Ok(())
1580 }
1581
1582 async fn extract_tar_file(
1583 &self,
1584 path: &Path,
1585 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1586 ) -> Result<()> {
1587 let mut entries = content.entries()?;
1588 while let Some(entry) = entries.next().await {
1589 let mut entry = entry?;
1590 if entry.header().entry_type().is_file() {
1591 let path = path.join(entry.path()?.as_ref());
1592 let mut bytes = Vec::new();
1593 entry.read_to_end(&mut bytes).await?;
1594 self.create_dir(path.parent().unwrap()).await?;
1595 self.write_file_internal(&path, bytes)?;
1596 }
1597 }
1598 Ok(())
1599 }
1600
1601 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1602 self.simulate_random_delay().await;
1603
1604 let old_path = normalize_path(old_path);
1605 let new_path = normalize_path(new_path);
1606
1607 let mut state = self.state.lock();
1608 let moved_entry = state.write_path(&old_path, |e| {
1609 if let btree_map::Entry::Occupied(e) = e {
1610 Ok(e.get().clone())
1611 } else {
1612 Err(anyhow!("path does not exist: {}", &old_path.display()))
1613 }
1614 })?;
1615
1616 let inode = match *moved_entry.lock() {
1617 FakeFsEntry::File { inode, .. } => inode,
1618 FakeFsEntry::Dir { inode, .. } => inode,
1619 _ => 0,
1620 };
1621
1622 state.moves.insert(inode, new_path.clone());
1623
1624 state.write_path(&new_path, |e| {
1625 match e {
1626 btree_map::Entry::Occupied(mut e) => {
1627 if options.overwrite {
1628 *e.get_mut() = moved_entry;
1629 } else if !options.ignore_if_exists {
1630 return Err(anyhow!("path already exists: {}", new_path.display()));
1631 }
1632 }
1633 btree_map::Entry::Vacant(e) => {
1634 e.insert(moved_entry);
1635 }
1636 }
1637 Ok(())
1638 })?;
1639
1640 state
1641 .write_path(&old_path, |e| {
1642 if let btree_map::Entry::Occupied(e) = e {
1643 Ok(e.remove())
1644 } else {
1645 unreachable!()
1646 }
1647 })
1648 .unwrap();
1649
1650 state.emit_event([
1651 (old_path, Some(PathEventKind::Removed)),
1652 (new_path, Some(PathEventKind::Created)),
1653 ]);
1654 Ok(())
1655 }
1656
1657 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1658 self.simulate_random_delay().await;
1659
1660 let source = normalize_path(source);
1661 let target = normalize_path(target);
1662 let mut state = self.state.lock();
1663 let mtime = state.get_and_increment_mtime();
1664 let inode = state.get_and_increment_inode();
1665 let source_entry = state.read_path(&source)?;
1666 let content = source_entry.lock().file_content(&source)?.clone();
1667 let mut kind = Some(PathEventKind::Created);
1668 state.write_path(&target, |e| match e {
1669 btree_map::Entry::Occupied(e) => {
1670 if options.overwrite {
1671 kind = Some(PathEventKind::Changed);
1672 Ok(Some(e.get().clone()))
1673 } else if !options.ignore_if_exists {
1674 return Err(anyhow!("{target:?} already exists"));
1675 } else {
1676 Ok(None)
1677 }
1678 }
1679 btree_map::Entry::Vacant(e) => Ok(Some(
1680 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1681 inode,
1682 mtime,
1683 len: content.len() as u64,
1684 content,
1685 })))
1686 .clone(),
1687 )),
1688 })?;
1689 state.emit_event([(target, kind)]);
1690 Ok(())
1691 }
1692
1693 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1694 self.simulate_random_delay().await;
1695
1696 let path = normalize_path(path);
1697 let parent_path = path
1698 .parent()
1699 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1700 let base_name = path.file_name().unwrap();
1701
1702 let mut state = self.state.lock();
1703 let parent_entry = state.read_path(parent_path)?;
1704 let mut parent_entry = parent_entry.lock();
1705 let entry = parent_entry
1706 .dir_entries(parent_path)?
1707 .entry(base_name.to_str().unwrap().into());
1708
1709 match entry {
1710 btree_map::Entry::Vacant(_) => {
1711 if !options.ignore_if_not_exists {
1712 return Err(anyhow!("{path:?} does not exist"));
1713 }
1714 }
1715 btree_map::Entry::Occupied(e) => {
1716 {
1717 let mut entry = e.get().lock();
1718 let children = entry.dir_entries(&path)?;
1719 if !options.recursive && !children.is_empty() {
1720 return Err(anyhow!("{path:?} is not empty"));
1721 }
1722 }
1723 e.remove();
1724 }
1725 }
1726 state.emit_event([(path, Some(PathEventKind::Removed))]);
1727 Ok(())
1728 }
1729
1730 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1731 self.simulate_random_delay().await;
1732
1733 let path = normalize_path(path);
1734 let parent_path = path
1735 .parent()
1736 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1737 let base_name = path.file_name().unwrap();
1738 let mut state = self.state.lock();
1739 let parent_entry = state.read_path(parent_path)?;
1740 let mut parent_entry = parent_entry.lock();
1741 let entry = parent_entry
1742 .dir_entries(parent_path)?
1743 .entry(base_name.to_str().unwrap().into());
1744 match entry {
1745 btree_map::Entry::Vacant(_) => {
1746 if !options.ignore_if_not_exists {
1747 return Err(anyhow!("{path:?} does not exist"));
1748 }
1749 }
1750 btree_map::Entry::Occupied(e) => {
1751 e.get().lock().file_content(&path)?;
1752 e.remove();
1753 }
1754 }
1755 state.emit_event([(path, Some(PathEventKind::Removed))]);
1756 Ok(())
1757 }
1758
1759 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
1760 let bytes = self.load_internal(path).await?;
1761 Ok(Box::new(io::Cursor::new(bytes)))
1762 }
1763
1764 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1765 self.simulate_random_delay().await;
1766 let state = self.state.lock();
1767 let entry = state.read_path(&path)?;
1768 let entry = entry.lock();
1769 let inode = match *entry {
1770 FakeFsEntry::File { inode, .. } => inode,
1771 FakeFsEntry::Dir { inode, .. } => inode,
1772 _ => unreachable!(),
1773 };
1774 Ok(Arc::new(FakeHandle { inode }))
1775 }
1776
1777 async fn load(&self, path: &Path) -> Result<String> {
1778 let content = self.load_internal(path).await?;
1779 Ok(String::from_utf8(content.clone())?)
1780 }
1781
1782 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1783 self.load_internal(path).await
1784 }
1785
1786 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1787 self.simulate_random_delay().await;
1788 let path = normalize_path(path.as_path());
1789 self.write_file_internal(path, data.into_bytes())?;
1790 Ok(())
1791 }
1792
1793 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1794 self.simulate_random_delay().await;
1795 let path = normalize_path(path);
1796 let content = chunks(text, line_ending).collect::<String>();
1797 if let Some(path) = path.parent() {
1798 self.create_dir(path).await?;
1799 }
1800 self.write_file_internal(path, content.into_bytes())?;
1801 Ok(())
1802 }
1803
1804 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1805 let path = normalize_path(path);
1806 self.simulate_random_delay().await;
1807 let state = self.state.lock();
1808 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1809 Ok(canonical_path)
1810 } else {
1811 Err(anyhow!("path does not exist: {}", path.display()))
1812 }
1813 }
1814
1815 async fn is_file(&self, path: &Path) -> bool {
1816 let path = normalize_path(path);
1817 self.simulate_random_delay().await;
1818 let state = self.state.lock();
1819 if let Some((entry, _)) = state.try_read_path(&path, true) {
1820 entry.lock().is_file()
1821 } else {
1822 false
1823 }
1824 }
1825
1826 async fn is_dir(&self, path: &Path) -> bool {
1827 self.metadata(path)
1828 .await
1829 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1830 }
1831
1832 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1833 self.simulate_random_delay().await;
1834 let path = normalize_path(path);
1835 let mut state = self.state.lock();
1836 state.metadata_call_count += 1;
1837 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1838 let is_symlink = entry.lock().is_symlink();
1839 if is_symlink {
1840 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1841 entry = e;
1842 } else {
1843 return Ok(None);
1844 }
1845 }
1846
1847 let entry = entry.lock();
1848 Ok(Some(match &*entry {
1849 FakeFsEntry::File {
1850 inode, mtime, len, ..
1851 } => Metadata {
1852 inode: *inode,
1853 mtime: *mtime,
1854 len: *len,
1855 is_dir: false,
1856 is_symlink,
1857 is_fifo: false,
1858 },
1859 FakeFsEntry::Dir {
1860 inode, mtime, len, ..
1861 } => Metadata {
1862 inode: *inode,
1863 mtime: *mtime,
1864 len: *len,
1865 is_dir: true,
1866 is_symlink,
1867 is_fifo: false,
1868 },
1869 FakeFsEntry::Symlink { .. } => unreachable!(),
1870 }))
1871 } else {
1872 Ok(None)
1873 }
1874 }
1875
1876 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1877 self.simulate_random_delay().await;
1878 let path = normalize_path(path);
1879 let state = self.state.lock();
1880 if let Some((entry, _)) = state.try_read_path(&path, false) {
1881 let entry = entry.lock();
1882 if let FakeFsEntry::Symlink { target } = &*entry {
1883 Ok(target.clone())
1884 } else {
1885 Err(anyhow!("not a symlink: {}", path.display()))
1886 }
1887 } else {
1888 Err(anyhow!("path does not exist: {}", path.display()))
1889 }
1890 }
1891
1892 async fn read_dir(
1893 &self,
1894 path: &Path,
1895 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1896 self.simulate_random_delay().await;
1897 let path = normalize_path(path);
1898 let mut state = self.state.lock();
1899 state.read_dir_call_count += 1;
1900 let entry = state.read_path(&path)?;
1901 let mut entry = entry.lock();
1902 let children = entry.dir_entries(&path)?;
1903 let paths = children
1904 .keys()
1905 .map(|file_name| Ok(path.join(file_name)))
1906 .collect::<Vec<_>>();
1907 Ok(Box::pin(futures::stream::iter(paths)))
1908 }
1909
1910 async fn watch(
1911 &self,
1912 path: &Path,
1913 _: Duration,
1914 ) -> (
1915 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1916 Arc<dyn Watcher>,
1917 ) {
1918 self.simulate_random_delay().await;
1919 let (tx, rx) = smol::channel::unbounded();
1920 self.state.lock().event_txs.push(tx);
1921 let path = path.to_path_buf();
1922 let executor = self.executor.clone();
1923 (
1924 Box::pin(futures::StreamExt::filter(rx, move |events| {
1925 let result = events
1926 .iter()
1927 .any(|evt_path| evt_path.path.starts_with(&path));
1928 let executor = executor.clone();
1929 async move {
1930 executor.simulate_random_delay().await;
1931 result
1932 }
1933 })),
1934 Arc::new(FakeWatcher {}),
1935 )
1936 }
1937
1938 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1939 let state = self.state.lock();
1940 let entry = state.read_path(abs_dot_git).unwrap();
1941 let mut entry = entry.lock();
1942 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1943 let state = git_repo_state
1944 .get_or_insert_with(|| {
1945 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1946 abs_dot_git.to_path_buf(),
1947 state.git_event_tx.clone(),
1948 )))
1949 })
1950 .clone();
1951 Some(git::repository::FakeGitRepository::open(state))
1952 } else {
1953 None
1954 }
1955 }
1956
1957 fn is_fake(&self) -> bool {
1958 true
1959 }
1960
1961 async fn is_case_sensitive(&self) -> Result<bool> {
1962 Ok(true)
1963 }
1964
1965 #[cfg(any(test, feature = "test-support"))]
1966 fn as_fake(&self) -> Arc<FakeFs> {
1967 self.this.upgrade().unwrap()
1968 }
1969}
1970
1971fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1972 rope.chunks().flat_map(move |chunk| {
1973 let mut newline = false;
1974 chunk.split('\n').flat_map(move |line| {
1975 let ending = if newline {
1976 Some(line_ending.as_str())
1977 } else {
1978 None
1979 };
1980 newline = true;
1981 ending.into_iter().chain([line])
1982 })
1983 })
1984}
1985
1986pub fn normalize_path(path: &Path) -> PathBuf {
1987 let mut components = path.components().peekable();
1988 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1989 components.next();
1990 PathBuf::from(c.as_os_str())
1991 } else {
1992 PathBuf::new()
1993 };
1994
1995 for component in components {
1996 match component {
1997 Component::Prefix(..) => unreachable!(),
1998 Component::RootDir => {
1999 ret.push(component.as_os_str());
2000 }
2001 Component::CurDir => {}
2002 Component::ParentDir => {
2003 ret.pop();
2004 }
2005 Component::Normal(c) => {
2006 ret.push(c);
2007 }
2008 }
2009 }
2010 ret
2011}
2012
2013pub async fn copy_recursive<'a>(
2014 fs: &'a dyn Fs,
2015 source: &'a Path,
2016 target: &'a Path,
2017 options: CopyOptions,
2018) -> Result<()> {
2019 for (is_dir, item) in read_dir_items(fs, source).await? {
2020 let Ok(item_relative_path) = item.strip_prefix(source) else {
2021 continue;
2022 };
2023 let target_item = target.join(item_relative_path);
2024 if is_dir {
2025 if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2026 if options.ignore_if_exists {
2027 continue;
2028 } else {
2029 return Err(anyhow!("{target_item:?} already exists"));
2030 }
2031 }
2032 let _ = fs
2033 .remove_dir(
2034 &target_item,
2035 RemoveOptions {
2036 recursive: true,
2037 ignore_if_not_exists: true,
2038 },
2039 )
2040 .await;
2041 fs.create_dir(&target_item).await?;
2042 } else {
2043 fs.copy_file(&item, &target_item, options).await?;
2044 }
2045 }
2046 Ok(())
2047}
2048
2049async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(bool, PathBuf)>> {
2050 let mut items = Vec::new();
2051 read_recursive(fs, source, &mut items).await?;
2052 Ok(items)
2053}
2054
2055fn read_recursive<'a>(
2056 fs: &'a dyn Fs,
2057 source: &'a Path,
2058 output: &'a mut Vec<(bool, PathBuf)>,
2059) -> BoxFuture<'a, Result<()>> {
2060 use futures::future::FutureExt;
2061
2062 async move {
2063 let metadata = fs
2064 .metadata(source)
2065 .await?
2066 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2067
2068 if metadata.is_dir {
2069 output.push((true, source.to_path_buf()));
2070 let mut children = fs.read_dir(source).await?;
2071 while let Some(child_path) = children.next().await {
2072 if let Ok(child_path) = child_path {
2073 read_recursive(fs, &child_path, output).await?;
2074 }
2075 }
2076 } else {
2077 output.push((false, source.to_path_buf()));
2078 }
2079 Ok(())
2080 }
2081 .boxed()
2082}
2083
2084// todo(windows)
2085// can we get file id not open the file twice?
2086// https://github.com/rust-lang/rust/issues/63010
2087#[cfg(target_os = "windows")]
2088async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2089 use std::os::windows::io::AsRawHandle;
2090
2091 use smol::fs::windows::OpenOptionsExt;
2092 use windows::Win32::{
2093 Foundation::HANDLE,
2094 Storage::FileSystem::{
2095 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2096 },
2097 };
2098
2099 let file = smol::fs::OpenOptions::new()
2100 .read(true)
2101 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2102 .open(path)
2103 .await?;
2104
2105 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2106 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2107 // This function supports Windows XP+
2108 smol::unblock(move || {
2109 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2110
2111 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2112 })
2113 .await
2114}
2115
2116#[cfg(test)]
2117mod tests {
2118 use super::*;
2119 use gpui::BackgroundExecutor;
2120 use serde_json::json;
2121 use util::path;
2122
2123 #[gpui::test]
2124 async fn test_fake_fs(executor: BackgroundExecutor) {
2125 let fs = FakeFs::new(executor.clone());
2126 fs.insert_tree(
2127 path!("/root"),
2128 json!({
2129 "dir1": {
2130 "a": "A",
2131 "b": "B"
2132 },
2133 "dir2": {
2134 "c": "C",
2135 "dir3": {
2136 "d": "D"
2137 }
2138 }
2139 }),
2140 )
2141 .await;
2142
2143 assert_eq!(
2144 fs.files(),
2145 vec![
2146 PathBuf::from(path!("/root/dir1/a")),
2147 PathBuf::from(path!("/root/dir1/b")),
2148 PathBuf::from(path!("/root/dir2/c")),
2149 PathBuf::from(path!("/root/dir2/dir3/d")),
2150 ]
2151 );
2152
2153 fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2154 .await
2155 .unwrap();
2156
2157 assert_eq!(
2158 fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2159 .await
2160 .unwrap(),
2161 PathBuf::from(path!("/root/dir2/dir3")),
2162 );
2163 assert_eq!(
2164 fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2165 .await
2166 .unwrap(),
2167 PathBuf::from(path!("/root/dir2/dir3/d")),
2168 );
2169 assert_eq!(
2170 fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2171 .await
2172 .unwrap(),
2173 "D",
2174 );
2175 }
2176
2177 #[gpui::test]
2178 async fn test_copy_recursive(executor: BackgroundExecutor) {
2179 let fs = FakeFs::new(executor.clone());
2180 fs.insert_tree(
2181 path!("/outer"),
2182 json!({
2183 "inner1": {
2184 "a": "A",
2185 "b": "B",
2186 "inner3": {
2187 "d": "D",
2188 }
2189 },
2190 "inner2": {
2191 "c": "C",
2192 }
2193 }),
2194 )
2195 .await;
2196
2197 assert_eq!(
2198 fs.files(),
2199 vec![
2200 PathBuf::from(path!("/outer/inner1/a")),
2201 PathBuf::from(path!("/outer/inner1/b")),
2202 PathBuf::from(path!("/outer/inner2/c")),
2203 PathBuf::from(path!("/outer/inner1/inner3/d")),
2204 ]
2205 );
2206
2207 let source = Path::new(path!("/outer"));
2208 let target = Path::new(path!("/outer/inner1/outer"));
2209 copy_recursive(fs.as_ref(), source, target, Default::default())
2210 .await
2211 .unwrap();
2212
2213 assert_eq!(
2214 fs.files(),
2215 vec![
2216 PathBuf::from(path!("/outer/inner1/a")),
2217 PathBuf::from(path!("/outer/inner1/b")),
2218 PathBuf::from(path!("/outer/inner2/c")),
2219 PathBuf::from(path!("/outer/inner1/inner3/d")),
2220 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2221 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2222 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2223 PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2224 ]
2225 );
2226 }
2227
2228 #[gpui::test]
2229 async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2230 let fs = FakeFs::new(executor.clone());
2231 fs.insert_tree(
2232 path!("/outer"),
2233 json!({
2234 "inner1": {
2235 "a": "A",
2236 "b": "B",
2237 "outer": {
2238 "inner1": {
2239 "a": "B"
2240 }
2241 }
2242 },
2243 "inner2": {
2244 "c": "C",
2245 }
2246 }),
2247 )
2248 .await;
2249
2250 assert_eq!(
2251 fs.files(),
2252 vec![
2253 PathBuf::from(path!("/outer/inner1/a")),
2254 PathBuf::from(path!("/outer/inner1/b")),
2255 PathBuf::from(path!("/outer/inner2/c")),
2256 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2257 ]
2258 );
2259 assert_eq!(
2260 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2261 .await
2262 .unwrap(),
2263 "B",
2264 );
2265
2266 let source = Path::new(path!("/outer"));
2267 let target = Path::new(path!("/outer/inner1/outer"));
2268 copy_recursive(
2269 fs.as_ref(),
2270 source,
2271 target,
2272 CopyOptions {
2273 overwrite: true,
2274 ..Default::default()
2275 },
2276 )
2277 .await
2278 .unwrap();
2279
2280 assert_eq!(
2281 fs.files(),
2282 vec![
2283 PathBuf::from(path!("/outer/inner1/a")),
2284 PathBuf::from(path!("/outer/inner1/b")),
2285 PathBuf::from(path!("/outer/inner2/c")),
2286 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2287 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2288 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2289 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2290 ]
2291 );
2292 assert_eq!(
2293 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2294 .await
2295 .unwrap(),
2296 "A"
2297 );
2298 }
2299
2300 #[gpui::test]
2301 async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
2302 let fs = FakeFs::new(executor.clone());
2303 fs.insert_tree(
2304 path!("/outer"),
2305 json!({
2306 "inner1": {
2307 "a": "A",
2308 "b": "B",
2309 "outer": {
2310 "inner1": {
2311 "a": "B"
2312 }
2313 }
2314 },
2315 "inner2": {
2316 "c": "C",
2317 }
2318 }),
2319 )
2320 .await;
2321
2322 assert_eq!(
2323 fs.files(),
2324 vec![
2325 PathBuf::from(path!("/outer/inner1/a")),
2326 PathBuf::from(path!("/outer/inner1/b")),
2327 PathBuf::from(path!("/outer/inner2/c")),
2328 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2329 ]
2330 );
2331 assert_eq!(
2332 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2333 .await
2334 .unwrap(),
2335 "B",
2336 );
2337
2338 let source = Path::new(path!("/outer"));
2339 let target = Path::new(path!("/outer/inner1/outer"));
2340 copy_recursive(
2341 fs.as_ref(),
2342 source,
2343 target,
2344 CopyOptions {
2345 ignore_if_exists: true,
2346 ..Default::default()
2347 },
2348 )
2349 .await
2350 .unwrap();
2351
2352 assert_eq!(
2353 fs.files(),
2354 vec![
2355 PathBuf::from(path!("/outer/inner1/a")),
2356 PathBuf::from(path!("/outer/inner1/b")),
2357 PathBuf::from(path!("/outer/inner2/c")),
2358 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2359 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2360 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2361 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2362 ]
2363 );
2364 assert_eq!(
2365 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2366 .await
2367 .unwrap(),
2368 "B"
2369 );
2370 }
2371}