1#[cfg(target_os = "macos")]
2mod mac_watcher;
3
4#[cfg(not(target_os = "macos"))]
5pub mod fs_watcher;
6
7use anyhow::{Context as _, Result, anyhow};
8#[cfg(any(target_os = "linux", target_os = "freebsd"))]
9use ashpd::desktop::trash;
10use gpui::App;
11use gpui::BackgroundExecutor;
12use gpui::Global;
13use gpui::ReadGlobal as _;
14use std::borrow::Cow;
15use util::command::{new_smol_command, new_std_command};
16
17#[cfg(unix)]
18use std::os::fd::{AsFd, AsRawFd};
19
20#[cfg(unix)]
21use std::os::unix::fs::{FileTypeExt, MetadataExt};
22
23#[cfg(any(target_os = "macos", target_os = "freebsd"))]
24use std::mem::MaybeUninit;
25
26use async_tar::Archive;
27use futures::{AsyncRead, Stream, StreamExt, future::BoxFuture};
28use git::repository::{GitRepository, RealGitRepository};
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::TempDir;
40use text::LineEnding;
41
42#[cfg(any(test, feature = "test-support"))]
43mod fake_git_repo;
44#[cfg(any(test, feature = "test-support"))]
45use collections::{BTreeMap, btree_map};
46#[cfg(any(test, feature = "test-support"))]
47use fake_git_repo::FakeGitRepositoryState;
48#[cfg(any(test, feature = "test-support"))]
49use git::{
50 repository::RepoPath,
51 status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus},
52};
53#[cfg(any(test, feature = "test-support"))]
54use parking_lot::Mutex;
55#[cfg(any(test, feature = "test-support"))]
56use smol::io::AsyncReadExt;
57#[cfg(any(test, feature = "test-support"))]
58use std::ffi::OsStr;
59
60pub trait Watcher: Send + Sync {
61 fn add(&self, path: &Path) -> Result<()>;
62 fn remove(&self, path: &Path) -> Result<()>;
63}
64
65#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
66pub enum PathEventKind {
67 Removed,
68 Created,
69 Changed,
70}
71
72#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
73pub struct PathEvent {
74 pub path: PathBuf,
75 pub kind: Option<PathEventKind>,
76}
77
78impl From<PathEvent> for PathBuf {
79 fn from(event: PathEvent) -> Self {
80 event.path
81 }
82}
83
84#[async_trait::async_trait]
85pub trait Fs: Send + Sync {
86 async fn create_dir(&self, path: &Path) -> Result<()>;
87 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
88 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
89 async fn create_file_with(
90 &self,
91 path: &Path,
92 content: Pin<&mut (dyn AsyncRead + Send)>,
93 ) -> Result<()>;
94 async fn extract_tar_file(
95 &self,
96 path: &Path,
97 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
98 ) -> Result<()>;
99 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
100 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
101 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
102 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
103 self.remove_dir(path, options).await
104 }
105 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
106 async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
107 self.remove_file(path, options).await
108 }
109 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
110 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>>;
111 async fn load(&self, path: &Path) -> Result<String> {
112 Ok(String::from_utf8(self.load_bytes(path).await?)?)
113 }
114 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
115 async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
116 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
117 async fn write(&self, path: &Path, content: &[u8]) -> Result<()>;
118 async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
119 async fn is_file(&self, path: &Path) -> bool;
120 async fn is_dir(&self, path: &Path) -> bool;
121 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
122 async fn read_link(&self, path: &Path) -> Result<PathBuf>;
123 async fn read_dir(
124 &self,
125 path: &Path,
126 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
127
128 async fn watch(
129 &self,
130 path: &Path,
131 latency: Duration,
132 ) -> (
133 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
134 Arc<dyn Watcher>,
135 );
136
137 fn home_dir(&self) -> Option<PathBuf>;
138 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>>;
139 fn git_init(&self, abs_work_directory: &Path, fallback_branch_name: String) -> Result<()>;
140 async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()>;
141 fn is_fake(&self) -> bool;
142 async fn is_case_sensitive(&self) -> Result<bool>;
143
144 #[cfg(any(test, feature = "test-support"))]
145 fn as_fake(&self) -> Arc<FakeFs> {
146 panic!("called as_fake on a real fs");
147 }
148}
149
150struct GlobalFs(Arc<dyn Fs>);
151
152impl Global for GlobalFs {}
153
154impl dyn Fs {
155 /// Returns the global [`Fs`].
156 pub fn global(cx: &App) -> Arc<Self> {
157 GlobalFs::global(cx).0.clone()
158 }
159
160 /// Sets the global [`Fs`].
161 pub fn set_global(fs: Arc<Self>, cx: &mut App) {
162 cx.set_global(GlobalFs(fs));
163 }
164}
165
166#[derive(Copy, Clone, Default)]
167pub struct CreateOptions {
168 pub overwrite: bool,
169 pub ignore_if_exists: bool,
170}
171
172#[derive(Copy, Clone, Default)]
173pub struct CopyOptions {
174 pub overwrite: bool,
175 pub ignore_if_exists: bool,
176}
177
178#[derive(Copy, Clone, Default)]
179pub struct RenameOptions {
180 pub overwrite: bool,
181 pub ignore_if_exists: bool,
182}
183
184#[derive(Copy, Clone, Default)]
185pub struct RemoveOptions {
186 pub recursive: bool,
187 pub ignore_if_not_exists: bool,
188}
189
190#[derive(Copy, Clone, Debug)]
191pub struct Metadata {
192 pub inode: u64,
193 pub mtime: MTime,
194 pub is_symlink: bool,
195 pub is_dir: bool,
196 pub len: u64,
197 pub is_fifo: bool,
198}
199
200/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
201/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
202/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
203/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
204///
205/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
206#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
207#[serde(transparent)]
208pub struct MTime(SystemTime);
209
210impl MTime {
211 /// Conversion intended for persistence and testing.
212 pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
213 MTime(UNIX_EPOCH + Duration::new(secs, nanos))
214 }
215
216 /// Conversion intended for persistence.
217 pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
218 self.0
219 .duration_since(UNIX_EPOCH)
220 .ok()
221 .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
222 }
223
224 /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
225 /// "_for_user" is to discourage misuse - this method should not be used when making decisions
226 /// about file dirtiness.
227 pub fn timestamp_for_user(self) -> SystemTime {
228 self.0
229 }
230
231 /// Temporary method to split out the behavior changes from introduction of this newtype.
232 pub fn bad_is_greater_than(self, other: MTime) -> bool {
233 self.0 > other.0
234 }
235}
236
237impl From<proto::Timestamp> for MTime {
238 fn from(timestamp: proto::Timestamp) -> Self {
239 MTime(timestamp.into())
240 }
241}
242
243impl From<MTime> for proto::Timestamp {
244 fn from(mtime: MTime) -> Self {
245 mtime.0.into()
246 }
247}
248
249pub struct RealFs {
250 git_binary_path: Option<PathBuf>,
251 executor: BackgroundExecutor,
252}
253
254pub trait FileHandle: Send + Sync + std::fmt::Debug {
255 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
256}
257
258impl FileHandle for std::fs::File {
259 #[cfg(target_os = "macos")]
260 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
261 use std::{
262 ffi::{CStr, OsStr},
263 os::unix::ffi::OsStrExt,
264 };
265
266 let fd = self.as_fd();
267 let mut path_buf = MaybeUninit::<[u8; libc::PATH_MAX as usize]>::uninit();
268
269 let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
270 if result == -1 {
271 anyhow::bail!("fcntl returned -1".to_string());
272 }
273
274 // SAFETY: `fcntl` will initialize the path buffer.
275 let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr().cast()) };
276 let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
277 Ok(path)
278 }
279
280 #[cfg(target_os = "linux")]
281 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
282 let fd = self.as_fd();
283 let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
284 let new_path = std::fs::read_link(fd_path)?;
285 if new_path
286 .file_name()
287 .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
288 {
289 anyhow::bail!("file was deleted")
290 };
291
292 Ok(new_path)
293 }
294
295 #[cfg(target_os = "freebsd")]
296 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
297 use std::{
298 ffi::{CStr, OsStr},
299 os::unix::ffi::OsStrExt,
300 };
301
302 let fd = self.as_fd();
303 let mut kif = MaybeUninit::<libc::kinfo_file>::uninit();
304 kif.kf_structsize = libc::KINFO_FILE_SIZE;
305
306 let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_KINFO, kif.as_mut_ptr()) };
307 if result == -1 {
308 anyhow::bail!("fcntl returned -1".to_string());
309 }
310
311 // SAFETY: `fcntl` will initialize the kif.
312 let c_str = unsafe { CStr::from_ptr(kif.assume_init().kf_path.as_ptr()) };
313 let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
314 Ok(path)
315 }
316
317 #[cfg(target_os = "windows")]
318 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
319 anyhow::bail!("unimplemented")
320 }
321}
322
323pub struct RealWatcher {}
324
325impl RealFs {
326 pub fn new(git_binary_path: Option<PathBuf>, executor: BackgroundExecutor) -> Self {
327 Self {
328 git_binary_path,
329 executor,
330 }
331 }
332}
333
334#[async_trait::async_trait]
335impl Fs for RealFs {
336 async fn create_dir(&self, path: &Path) -> Result<()> {
337 Ok(smol::fs::create_dir_all(path).await?)
338 }
339
340 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
341 #[cfg(unix)]
342 smol::fs::unix::symlink(target, path).await?;
343
344 #[cfg(windows)]
345 if smol::fs::metadata(&target).await?.is_dir() {
346 smol::fs::windows::symlink_dir(target, path).await?
347 } else {
348 smol::fs::windows::symlink_file(target, path).await?
349 }
350
351 Ok(())
352 }
353
354 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
355 let mut open_options = smol::fs::OpenOptions::new();
356 open_options.write(true).create(true);
357 if options.overwrite {
358 open_options.truncate(true);
359 } else if !options.ignore_if_exists {
360 open_options.create_new(true);
361 }
362 open_options.open(path).await?;
363 Ok(())
364 }
365
366 async fn create_file_with(
367 &self,
368 path: &Path,
369 content: Pin<&mut (dyn AsyncRead + Send)>,
370 ) -> Result<()> {
371 let mut file = smol::fs::File::create(&path).await?;
372 futures::io::copy(content, &mut file).await?;
373 Ok(())
374 }
375
376 async fn extract_tar_file(
377 &self,
378 path: &Path,
379 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
380 ) -> Result<()> {
381 content.unpack(path).await?;
382 Ok(())
383 }
384
385 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
386 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
387 if options.ignore_if_exists {
388 return Ok(());
389 } else {
390 anyhow::bail!("{target:?} already exists");
391 }
392 }
393
394 smol::fs::copy(source, target).await?;
395 Ok(())
396 }
397
398 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
399 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
400 if options.ignore_if_exists {
401 return Ok(());
402 } else {
403 anyhow::bail!("{target:?} already exists");
404 }
405 }
406
407 smol::fs::rename(source, target).await?;
408 Ok(())
409 }
410
411 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
412 let result = if options.recursive {
413 smol::fs::remove_dir_all(path).await
414 } else {
415 smol::fs::remove_dir(path).await
416 };
417 match result {
418 Ok(()) => Ok(()),
419 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
420 Ok(())
421 }
422 Err(err) => Err(err)?,
423 }
424 }
425
426 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
427 #[cfg(windows)]
428 if let Ok(Some(metadata)) = self.metadata(path).await
429 && metadata.is_symlink
430 && metadata.is_dir
431 {
432 self.remove_dir(
433 path,
434 RemoveOptions {
435 recursive: false,
436 ignore_if_not_exists: true,
437 },
438 )
439 .await?;
440 return Ok(());
441 }
442
443 match smol::fs::remove_file(path).await {
444 Ok(()) => Ok(()),
445 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
446 Ok(())
447 }
448 Err(err) => Err(err)?,
449 }
450 }
451
452 #[cfg(target_os = "macos")]
453 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
454 use cocoa::{
455 base::{id, nil},
456 foundation::{NSAutoreleasePool, NSString},
457 };
458 use objc::{class, msg_send, sel, sel_impl};
459
460 unsafe {
461 unsafe fn ns_string(string: &str) -> id {
462 unsafe { NSString::alloc(nil).init_str(string).autorelease() }
463 }
464
465 let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
466 let array: id = msg_send![class!(NSArray), arrayWithObject: url];
467 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
468
469 let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
470 }
471 Ok(())
472 }
473
474 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
475 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
476 if let Ok(Some(metadata)) = self.metadata(path).await
477 && metadata.is_symlink
478 {
479 // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
480 return self.remove_file(path, RemoveOptions::default()).await;
481 }
482 let file = smol::fs::File::open(path).await?;
483 match trash::trash_file(&file.as_fd()).await {
484 Ok(_) => Ok(()),
485 Err(err) => {
486 log::error!("Failed to trash file: {}", err);
487 // Trashing files can fail if you don't have a trashing dbus service configured.
488 // In that case, delete the file directly instead.
489 return self.remove_file(path, RemoveOptions::default()).await;
490 }
491 }
492 }
493
494 #[cfg(target_os = "windows")]
495 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
496 use util::paths::SanitizedPath;
497 use windows::{
498 Storage::{StorageDeleteOption, StorageFile},
499 core::HSTRING,
500 };
501 // todo(windows)
502 // When new version of `windows-rs` release, make this operation `async`
503 let path = path.canonicalize()?;
504 let path = SanitizedPath::new(&path);
505 let path_string = path.to_string();
506 let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
507 file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
508 Ok(())
509 }
510
511 #[cfg(target_os = "macos")]
512 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
513 self.trash_file(path, options).await
514 }
515
516 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
517 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
518 self.trash_file(path, options).await
519 }
520
521 #[cfg(target_os = "windows")]
522 async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
523 use util::paths::SanitizedPath;
524 use windows::{
525 Storage::{StorageDeleteOption, StorageFolder},
526 core::HSTRING,
527 };
528
529 // todo(windows)
530 // When new version of `windows-rs` release, make this operation `async`
531 let path = path.canonicalize()?;
532 let path = SanitizedPath::new(&path);
533 let path_string = path.to_string();
534 let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
535 folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
536 Ok(())
537 }
538
539 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
540 Ok(Box::new(std::fs::File::open(path)?))
541 }
542
543 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
544 Ok(Arc::new(std::fs::File::open(path)?))
545 }
546
547 async fn load(&self, path: &Path) -> Result<String> {
548 let path = path.to_path_buf();
549 let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
550 Ok(text)
551 }
552 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
553 let path = path.to_path_buf();
554 let bytes = smol::unblock(|| std::fs::read(path)).await?;
555 Ok(bytes)
556 }
557
558 #[cfg(not(target_os = "windows"))]
559 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
560 smol::unblock(move || {
561 // Use the directory of the destination as temp dir to avoid
562 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
563 // See https://github.com/zed-industries/zed/pull/8437 for more details.
564 let mut tmp_file =
565 tempfile::NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
566 tmp_file.write_all(data.as_bytes())?;
567 tmp_file.persist(path)?;
568 anyhow::Ok(())
569 })
570 .await?;
571
572 Ok(())
573 }
574
575 #[cfg(target_os = "windows")]
576 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
577 smol::unblock(move || {
578 // If temp dir is set to a different drive than the destination,
579 // we receive error:
580 //
581 // failed to persist temporary file:
582 // The system cannot move the file to a different disk drive. (os error 17)
583 //
584 // This is because `ReplaceFileW` does not support cross volume moves.
585 // See the remark section: "The backup file, replaced file, and replacement file must all reside on the same volume."
586 // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew#remarks
587 //
588 // So we use the directory of the destination as a temp dir to avoid it.
589 // https://github.com/zed-industries/zed/issues/16571
590 let temp_dir = TempDir::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
591 let temp_file = {
592 let temp_file_path = temp_dir.path().join("temp_file");
593 let mut file = std::fs::File::create_new(&temp_file_path)?;
594 file.write_all(data.as_bytes())?;
595 temp_file_path
596 };
597 atomic_replace(path.as_path(), temp_file.as_path())?;
598 anyhow::Ok(())
599 })
600 .await?;
601 Ok(())
602 }
603
604 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
605 let buffer_size = text.summary().len.min(10 * 1024);
606 if let Some(path) = path.parent() {
607 self.create_dir(path).await?;
608 }
609 let file = smol::fs::File::create(path).await?;
610 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
611 for chunk in chunks(text, line_ending) {
612 writer.write_all(chunk.as_bytes()).await?;
613 }
614 writer.flush().await?;
615 Ok(())
616 }
617
618 async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
619 if let Some(path) = path.parent() {
620 self.create_dir(path).await?;
621 }
622 smol::fs::write(path, content).await?;
623 Ok(())
624 }
625
626 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
627 Ok(smol::fs::canonicalize(path)
628 .await
629 .with_context(|| format!("canonicalizing {path:?}"))?)
630 }
631
632 async fn is_file(&self, path: &Path) -> bool {
633 smol::fs::metadata(path)
634 .await
635 .is_ok_and(|metadata| metadata.is_file())
636 }
637
638 async fn is_dir(&self, path: &Path) -> bool {
639 smol::fs::metadata(path)
640 .await
641 .is_ok_and(|metadata| metadata.is_dir())
642 }
643
644 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
645 let symlink_metadata = match smol::fs::symlink_metadata(path).await {
646 Ok(metadata) => metadata,
647 Err(err) => {
648 return match (err.kind(), err.raw_os_error()) {
649 (io::ErrorKind::NotFound, _) => Ok(None),
650 (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
651 _ => Err(anyhow::Error::new(err)),
652 };
653 }
654 };
655
656 let path_buf = path.to_path_buf();
657 let path_exists = smol::unblock(move || {
658 path_buf
659 .try_exists()
660 .with_context(|| format!("checking existence for path {path_buf:?}"))
661 })
662 .await?;
663 let is_symlink = symlink_metadata.file_type().is_symlink();
664 let metadata = match (is_symlink, path_exists) {
665 (true, true) => smol::fs::metadata(path)
666 .await
667 .with_context(|| "accessing symlink for path {path}")?,
668 _ => symlink_metadata,
669 };
670
671 #[cfg(unix)]
672 let inode = metadata.ino();
673
674 #[cfg(windows)]
675 let inode = file_id(path).await?;
676
677 #[cfg(windows)]
678 let is_fifo = false;
679
680 #[cfg(unix)]
681 let is_fifo = metadata.file_type().is_fifo();
682
683 Ok(Some(Metadata {
684 inode,
685 mtime: MTime(metadata.modified().unwrap()),
686 len: metadata.len(),
687 is_symlink,
688 is_dir: metadata.file_type().is_dir(),
689 is_fifo,
690 }))
691 }
692
693 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
694 let path = smol::fs::read_link(path).await?;
695 Ok(path)
696 }
697
698 async fn read_dir(
699 &self,
700 path: &Path,
701 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
702 let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
703 Ok(entry) => Ok(entry.path()),
704 Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
705 });
706 Ok(Box::pin(result))
707 }
708
709 #[cfg(target_os = "macos")]
710 async fn watch(
711 &self,
712 path: &Path,
713 latency: Duration,
714 ) -> (
715 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
716 Arc<dyn Watcher>,
717 ) {
718 use fsevent::StreamFlags;
719
720 let (events_tx, events_rx) = smol::channel::unbounded();
721 let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
722 let watcher = Arc::new(mac_watcher::MacWatcher::new(
723 events_tx,
724 Arc::downgrade(&handles),
725 latency,
726 ));
727 watcher.add(path).expect("handles can't be dropped");
728
729 (
730 Box::pin(
731 events_rx
732 .map(|events| {
733 events
734 .into_iter()
735 .map(|event| {
736 let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
737 Some(PathEventKind::Removed)
738 } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
739 Some(PathEventKind::Created)
740 } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
741 Some(PathEventKind::Changed)
742 } else {
743 None
744 };
745 PathEvent {
746 path: event.path,
747 kind,
748 }
749 })
750 .collect()
751 })
752 .chain(futures::stream::once(async move {
753 drop(handles);
754 vec![]
755 })),
756 ),
757 watcher,
758 )
759 }
760
761 #[cfg(not(target_os = "macos"))]
762 async fn watch(
763 &self,
764 path: &Path,
765 latency: Duration,
766 ) -> (
767 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
768 Arc<dyn Watcher>,
769 ) {
770 use parking_lot::Mutex;
771 use util::{ResultExt as _, paths::SanitizedPath};
772
773 let (tx, rx) = smol::channel::unbounded();
774 let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
775 let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
776
777 // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
778 if watcher.add(path).is_err()
779 && let Some(parent) = path.parent()
780 && let Err(e) = watcher.add(parent)
781 {
782 log::warn!("Failed to watch: {e}");
783 }
784
785 // Check if path is a symlink and follow the target parent
786 if let Some(mut target) = self.read_link(path).await.ok() {
787 // Check if symlink target is relative path, if so make it absolute
788 if target.is_relative()
789 && let Some(parent) = path.parent()
790 {
791 target = parent.join(target);
792 if let Ok(canonical) = self.canonicalize(&target).await {
793 target = SanitizedPath::new(&canonical).as_path().to_path_buf();
794 }
795 }
796 watcher.add(&target).ok();
797 if let Some(parent) = target.parent() {
798 watcher.add(parent).log_err();
799 }
800 }
801
802 (
803 Box::pin(rx.filter_map({
804 let watcher = watcher.clone();
805 move |_| {
806 let _ = watcher.clone();
807 let pending_paths = pending_paths.clone();
808 async move {
809 smol::Timer::after(latency).await;
810 let paths = std::mem::take(&mut *pending_paths.lock());
811 (!paths.is_empty()).then_some(paths)
812 }
813 }
814 })),
815 watcher,
816 )
817 }
818
819 fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
820 Some(Arc::new(RealGitRepository::new(
821 dotgit_path,
822 self.git_binary_path.clone(),
823 self.executor.clone(),
824 )?))
825 }
826
827 fn git_init(&self, abs_work_directory_path: &Path, fallback_branch_name: String) -> Result<()> {
828 let config = new_std_command("git")
829 .current_dir(abs_work_directory_path)
830 .args(&["config", "--global", "--get", "init.defaultBranch"])
831 .output()?;
832
833 let branch_name;
834
835 if config.status.success() && !config.stdout.is_empty() {
836 branch_name = String::from_utf8_lossy(&config.stdout);
837 } else {
838 branch_name = Cow::Borrowed(fallback_branch_name.as_str());
839 }
840
841 new_std_command("git")
842 .current_dir(abs_work_directory_path)
843 .args(&["init", "-b"])
844 .arg(branch_name.trim())
845 .output()?;
846
847 Ok(())
848 }
849
850 async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
851 let output = new_smol_command("git")
852 .current_dir(abs_work_directory)
853 .args(&["clone", repo_url])
854 .output()
855 .await?;
856
857 if !output.status.success() {
858 anyhow::bail!(
859 "git clone failed: {}",
860 String::from_utf8_lossy(&output.stderr)
861 );
862 }
863
864 Ok(())
865 }
866
867 fn is_fake(&self) -> bool {
868 false
869 }
870
871 /// Checks whether the file system is case sensitive by attempting to create two files
872 /// that have the same name except for the casing.
873 ///
874 /// It creates both files in a temporary directory it removes at the end.
875 async fn is_case_sensitive(&self) -> Result<bool> {
876 let temp_dir = TempDir::new()?;
877 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
878 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
879
880 let create_opts = CreateOptions {
881 overwrite: false,
882 ignore_if_exists: false,
883 };
884
885 // Create file1
886 self.create_file(&test_file_1, create_opts).await?;
887
888 // Now check whether it's possible to create file2
889 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
890 Ok(_) => Ok(true),
891 Err(e) => {
892 if let Some(io_error) = e.downcast_ref::<io::Error>() {
893 if io_error.kind() == io::ErrorKind::AlreadyExists {
894 Ok(false)
895 } else {
896 Err(e)
897 }
898 } else {
899 Err(e)
900 }
901 }
902 };
903
904 temp_dir.close()?;
905 case_sensitive
906 }
907
908 fn home_dir(&self) -> Option<PathBuf> {
909 Some(paths::home_dir().clone())
910 }
911}
912
913#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
914impl Watcher for RealWatcher {
915 fn add(&self, _: &Path) -> Result<()> {
916 Ok(())
917 }
918
919 fn remove(&self, _: &Path) -> Result<()> {
920 Ok(())
921 }
922}
923
924#[cfg(any(test, feature = "test-support"))]
925pub struct FakeFs {
926 this: std::sync::Weak<Self>,
927 // Use an unfair lock to ensure tests are deterministic.
928 state: Arc<Mutex<FakeFsState>>,
929 executor: gpui::BackgroundExecutor,
930}
931
932#[cfg(any(test, feature = "test-support"))]
933struct FakeFsState {
934 root: FakeFsEntry,
935 next_inode: u64,
936 next_mtime: SystemTime,
937 git_event_tx: smol::channel::Sender<PathBuf>,
938 event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
939 events_paused: bool,
940 buffered_events: Vec<PathEvent>,
941 metadata_call_count: usize,
942 read_dir_call_count: usize,
943 path_write_counts: std::collections::HashMap<PathBuf, usize>,
944 moves: std::collections::HashMap<u64, PathBuf>,
945 home_dir: Option<PathBuf>,
946}
947
948#[cfg(any(test, feature = "test-support"))]
949#[derive(Clone, Debug)]
950enum FakeFsEntry {
951 File {
952 inode: u64,
953 mtime: MTime,
954 len: u64,
955 content: Vec<u8>,
956 // The path to the repository state directory, if this is a gitfile.
957 git_dir_path: Option<PathBuf>,
958 },
959 Dir {
960 inode: u64,
961 mtime: MTime,
962 len: u64,
963 entries: BTreeMap<String, FakeFsEntry>,
964 git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
965 },
966 Symlink {
967 target: PathBuf,
968 },
969}
970
971#[cfg(any(test, feature = "test-support"))]
972impl PartialEq for FakeFsEntry {
973 fn eq(&self, other: &Self) -> bool {
974 match (self, other) {
975 (
976 Self::File {
977 inode: l_inode,
978 mtime: l_mtime,
979 len: l_len,
980 content: l_content,
981 git_dir_path: l_git_dir_path,
982 },
983 Self::File {
984 inode: r_inode,
985 mtime: r_mtime,
986 len: r_len,
987 content: r_content,
988 git_dir_path: r_git_dir_path,
989 },
990 ) => {
991 l_inode == r_inode
992 && l_mtime == r_mtime
993 && l_len == r_len
994 && l_content == r_content
995 && l_git_dir_path == r_git_dir_path
996 }
997 (
998 Self::Dir {
999 inode: l_inode,
1000 mtime: l_mtime,
1001 len: l_len,
1002 entries: l_entries,
1003 git_repo_state: l_git_repo_state,
1004 },
1005 Self::Dir {
1006 inode: r_inode,
1007 mtime: r_mtime,
1008 len: r_len,
1009 entries: r_entries,
1010 git_repo_state: r_git_repo_state,
1011 },
1012 ) => {
1013 let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1014 (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1015 (None, None) => true,
1016 _ => false,
1017 };
1018 l_inode == r_inode
1019 && l_mtime == r_mtime
1020 && l_len == r_len
1021 && l_entries == r_entries
1022 && same_repo_state
1023 }
1024 (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1025 l_target == r_target
1026 }
1027 _ => false,
1028 }
1029 }
1030}
1031
1032#[cfg(any(test, feature = "test-support"))]
1033impl FakeFsState {
1034 fn get_and_increment_mtime(&mut self) -> MTime {
1035 let mtime = self.next_mtime;
1036 self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1037 MTime(mtime)
1038 }
1039
1040 fn get_and_increment_inode(&mut self) -> u64 {
1041 let inode = self.next_inode;
1042 self.next_inode += 1;
1043 inode
1044 }
1045
1046 fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1047 let mut canonical_path = PathBuf::new();
1048 let mut path = target.to_path_buf();
1049 let mut entry_stack = Vec::new();
1050 'outer: loop {
1051 let mut path_components = path.components().peekable();
1052 let mut prefix = None;
1053 while let Some(component) = path_components.next() {
1054 match component {
1055 Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1056 Component::RootDir => {
1057 entry_stack.clear();
1058 entry_stack.push(&self.root);
1059 canonical_path.clear();
1060 match prefix {
1061 Some(prefix_component) => {
1062 canonical_path = PathBuf::from(prefix_component.as_os_str());
1063 // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1064 canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1065 }
1066 None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1067 }
1068 }
1069 Component::CurDir => {}
1070 Component::ParentDir => {
1071 entry_stack.pop()?;
1072 canonical_path.pop();
1073 }
1074 Component::Normal(name) => {
1075 let current_entry = *entry_stack.last()?;
1076 if let FakeFsEntry::Dir { entries, .. } = current_entry {
1077 let entry = entries.get(name.to_str().unwrap())?;
1078 if (path_components.peek().is_some() || follow_symlink)
1079 && let FakeFsEntry::Symlink { target, .. } = entry
1080 {
1081 let mut target = target.clone();
1082 target.extend(path_components);
1083 path = target;
1084 continue 'outer;
1085 }
1086 entry_stack.push(entry);
1087 canonical_path = canonical_path.join(name);
1088 } else {
1089 return None;
1090 }
1091 }
1092 }
1093 }
1094 break;
1095 }
1096
1097 if entry_stack.is_empty() {
1098 None
1099 } else {
1100 Some(canonical_path)
1101 }
1102 }
1103
1104 fn try_entry(
1105 &mut self,
1106 target: &Path,
1107 follow_symlink: bool,
1108 ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1109 let canonical_path = self.canonicalize(target, follow_symlink)?;
1110
1111 let mut components = canonical_path
1112 .components()
1113 .skip_while(|component| matches!(component, Component::Prefix(_)));
1114 let Some(Component::RootDir) = components.next() else {
1115 panic!(
1116 "the path {:?} was not canonicalized properly {:?}",
1117 target, canonical_path
1118 )
1119 };
1120
1121 let mut entry = &mut self.root;
1122 for component in components {
1123 match component {
1124 Component::Normal(name) => {
1125 if let FakeFsEntry::Dir { entries, .. } = entry {
1126 entry = entries.get_mut(name.to_str().unwrap())?;
1127 } else {
1128 return None;
1129 }
1130 }
1131 _ => {
1132 panic!(
1133 "the path {:?} was not canonicalized properly {:?}",
1134 target, canonical_path
1135 )
1136 }
1137 }
1138 }
1139
1140 Some((entry, canonical_path))
1141 }
1142
1143 fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1144 Ok(self
1145 .try_entry(target, true)
1146 .ok_or_else(|| {
1147 anyhow!(io::Error::new(
1148 io::ErrorKind::NotFound,
1149 format!("not found: {target:?}")
1150 ))
1151 })?
1152 .0)
1153 }
1154
1155 fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1156 where
1157 Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1158 {
1159 let path = normalize_path(path);
1160 let filename = path.file_name().context("cannot overwrite the root")?;
1161 let parent_path = path.parent().unwrap();
1162
1163 let parent = self.entry(parent_path)?;
1164 let new_entry = parent
1165 .dir_entries(parent_path)?
1166 .entry(filename.to_str().unwrap().into());
1167 callback(new_entry)
1168 }
1169
1170 fn emit_event<I, T>(&mut self, paths: I)
1171 where
1172 I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1173 T: Into<PathBuf>,
1174 {
1175 self.buffered_events
1176 .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1177 path: path.into(),
1178 kind,
1179 }));
1180
1181 if !self.events_paused {
1182 self.flush_events(self.buffered_events.len());
1183 }
1184 }
1185
1186 fn flush_events(&mut self, mut count: usize) {
1187 count = count.min(self.buffered_events.len());
1188 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1189 self.event_txs.retain(|(_, tx)| {
1190 let _ = tx.try_send(events.clone());
1191 !tx.is_closed()
1192 });
1193 }
1194}
1195
1196#[cfg(any(test, feature = "test-support"))]
1197pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1198 std::sync::LazyLock::new(|| OsStr::new(".git"));
1199
1200#[cfg(any(test, feature = "test-support"))]
1201impl FakeFs {
1202 /// We need to use something large enough for Windows and Unix to consider this a new file.
1203 /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1204 const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1205
1206 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1207 let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1208
1209 let this = Arc::new_cyclic(|this| Self {
1210 this: this.clone(),
1211 executor: executor.clone(),
1212 state: Arc::new(Mutex::new(FakeFsState {
1213 root: FakeFsEntry::Dir {
1214 inode: 0,
1215 mtime: MTime(UNIX_EPOCH),
1216 len: 0,
1217 entries: Default::default(),
1218 git_repo_state: None,
1219 },
1220 git_event_tx: tx,
1221 next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1222 next_inode: 1,
1223 event_txs: Default::default(),
1224 buffered_events: Vec::new(),
1225 events_paused: false,
1226 read_dir_call_count: 0,
1227 metadata_call_count: 0,
1228 path_write_counts: Default::default(),
1229 moves: Default::default(),
1230 home_dir: None,
1231 })),
1232 });
1233
1234 executor.spawn({
1235 let this = this.clone();
1236 async move {
1237 while let Ok(git_event) = rx.recv().await {
1238 if let Some(mut state) = this.state.try_lock() {
1239 state.emit_event([(git_event, None)]);
1240 } else {
1241 panic!("Failed to lock file system state, this execution would have caused a test hang");
1242 }
1243 }
1244 }
1245 }).detach();
1246
1247 this
1248 }
1249
1250 pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1251 let mut state = self.state.lock();
1252 state.next_mtime = next_mtime;
1253 }
1254
1255 pub fn get_and_increment_mtime(&self) -> MTime {
1256 let mut state = self.state.lock();
1257 state.get_and_increment_mtime()
1258 }
1259
1260 pub async fn touch_path(&self, path: impl AsRef<Path>) {
1261 let mut state = self.state.lock();
1262 let path = path.as_ref();
1263 let new_mtime = state.get_and_increment_mtime();
1264 let new_inode = state.get_and_increment_inode();
1265 state
1266 .write_path(path, move |entry| {
1267 match entry {
1268 btree_map::Entry::Vacant(e) => {
1269 e.insert(FakeFsEntry::File {
1270 inode: new_inode,
1271 mtime: new_mtime,
1272 content: Vec::new(),
1273 len: 0,
1274 git_dir_path: None,
1275 });
1276 }
1277 btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1278 FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1279 FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1280 FakeFsEntry::Symlink { .. } => {}
1281 },
1282 }
1283 Ok(())
1284 })
1285 .unwrap();
1286 state.emit_event([(path.to_path_buf(), None)]);
1287 }
1288
1289 pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1290 self.write_file_internal(path, content, true).unwrap()
1291 }
1292
1293 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1294 let mut state = self.state.lock();
1295 let path = path.as_ref();
1296 let file = FakeFsEntry::Symlink { target };
1297 state
1298 .write_path(path.as_ref(), move |e| match e {
1299 btree_map::Entry::Vacant(e) => {
1300 e.insert(file);
1301 Ok(())
1302 }
1303 btree_map::Entry::Occupied(mut e) => {
1304 *e.get_mut() = file;
1305 Ok(())
1306 }
1307 })
1308 .unwrap();
1309 state.emit_event([(path, None)]);
1310 }
1311
1312 fn write_file_internal(
1313 &self,
1314 path: impl AsRef<Path>,
1315 new_content: Vec<u8>,
1316 recreate_inode: bool,
1317 ) -> Result<()> {
1318 let mut state = self.state.lock();
1319 let path_buf = path.as_ref().to_path_buf();
1320 *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1321 let new_inode = state.get_and_increment_inode();
1322 let new_mtime = state.get_and_increment_mtime();
1323 let new_len = new_content.len() as u64;
1324 let mut kind = None;
1325 state.write_path(path.as_ref(), |entry| {
1326 match entry {
1327 btree_map::Entry::Vacant(e) => {
1328 kind = Some(PathEventKind::Created);
1329 e.insert(FakeFsEntry::File {
1330 inode: new_inode,
1331 mtime: new_mtime,
1332 len: new_len,
1333 content: new_content,
1334 git_dir_path: None,
1335 });
1336 }
1337 btree_map::Entry::Occupied(mut e) => {
1338 kind = Some(PathEventKind::Changed);
1339 if let FakeFsEntry::File {
1340 inode,
1341 mtime,
1342 len,
1343 content,
1344 ..
1345 } = e.get_mut()
1346 {
1347 *mtime = new_mtime;
1348 *content = new_content;
1349 *len = new_len;
1350 if recreate_inode {
1351 *inode = new_inode;
1352 }
1353 } else {
1354 anyhow::bail!("not a file")
1355 }
1356 }
1357 }
1358 Ok(())
1359 })?;
1360 state.emit_event([(path.as_ref(), kind)]);
1361 Ok(())
1362 }
1363
1364 pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1365 let path = path.as_ref();
1366 let path = normalize_path(path);
1367 let mut state = self.state.lock();
1368 let entry = state.entry(&path)?;
1369 entry.file_content(&path).cloned()
1370 }
1371
1372 async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1373 let path = path.as_ref();
1374 let path = normalize_path(path);
1375 self.simulate_random_delay().await;
1376 let mut state = self.state.lock();
1377 let entry = state.entry(&path)?;
1378 entry.file_content(&path).cloned()
1379 }
1380
1381 pub fn pause_events(&self) {
1382 self.state.lock().events_paused = true;
1383 }
1384
1385 pub fn unpause_events_and_flush(&self) {
1386 self.state.lock().events_paused = false;
1387 self.flush_events(usize::MAX);
1388 }
1389
1390 pub fn buffered_event_count(&self) -> usize {
1391 self.state.lock().buffered_events.len()
1392 }
1393
1394 pub fn flush_events(&self, count: usize) {
1395 self.state.lock().flush_events(count);
1396 }
1397
1398 pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1399 self.state.lock().entry(target).cloned()
1400 }
1401
1402 pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1403 let mut state = self.state.lock();
1404 state.write_path(target, |entry| {
1405 match entry {
1406 btree_map::Entry::Vacant(vacant_entry) => {
1407 vacant_entry.insert(new_entry);
1408 }
1409 btree_map::Entry::Occupied(mut occupied_entry) => {
1410 occupied_entry.insert(new_entry);
1411 }
1412 }
1413 Ok(())
1414 })
1415 }
1416
1417 #[must_use]
1418 pub fn insert_tree<'a>(
1419 &'a self,
1420 path: impl 'a + AsRef<Path> + Send,
1421 tree: serde_json::Value,
1422 ) -> futures::future::BoxFuture<'a, ()> {
1423 use futures::FutureExt as _;
1424 use serde_json::Value::*;
1425
1426 async move {
1427 let path = path.as_ref();
1428
1429 match tree {
1430 Object(map) => {
1431 self.create_dir(path).await.unwrap();
1432 for (name, contents) in map {
1433 let mut path = PathBuf::from(path);
1434 path.push(name);
1435 self.insert_tree(&path, contents).await;
1436 }
1437 }
1438 Null => {
1439 self.create_dir(path).await.unwrap();
1440 }
1441 String(contents) => {
1442 self.insert_file(&path, contents.into_bytes()).await;
1443 }
1444 _ => {
1445 panic!("JSON object must contain only objects, strings, or null");
1446 }
1447 }
1448 }
1449 .boxed()
1450 }
1451
1452 pub fn insert_tree_from_real_fs<'a>(
1453 &'a self,
1454 path: impl 'a + AsRef<Path> + Send,
1455 src_path: impl 'a + AsRef<Path> + Send,
1456 ) -> futures::future::BoxFuture<'a, ()> {
1457 use futures::FutureExt as _;
1458
1459 async move {
1460 let path = path.as_ref();
1461 if std::fs::metadata(&src_path).unwrap().is_file() {
1462 let contents = std::fs::read(src_path).unwrap();
1463 self.insert_file(path, contents).await;
1464 } else {
1465 self.create_dir(path).await.unwrap();
1466 for entry in std::fs::read_dir(&src_path).unwrap() {
1467 let entry = entry.unwrap();
1468 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1469 .await;
1470 }
1471 }
1472 }
1473 .boxed()
1474 }
1475
1476 pub fn with_git_state_and_paths<T, F>(
1477 &self,
1478 dot_git: &Path,
1479 emit_git_event: bool,
1480 f: F,
1481 ) -> Result<T>
1482 where
1483 F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1484 {
1485 let mut state = self.state.lock();
1486 let git_event_tx = state.git_event_tx.clone();
1487 let entry = state.entry(dot_git).context("open .git")?;
1488
1489 if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1490 let repo_state = git_repo_state.get_or_insert_with(|| {
1491 log::debug!("insert git state for {dot_git:?}");
1492 Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1493 });
1494 let mut repo_state = repo_state.lock();
1495
1496 let result = f(&mut repo_state, dot_git, dot_git);
1497
1498 drop(repo_state);
1499 if emit_git_event {
1500 state.emit_event([(dot_git, None)]);
1501 }
1502
1503 Ok(result)
1504 } else if let FakeFsEntry::File {
1505 content,
1506 git_dir_path,
1507 ..
1508 } = &mut *entry
1509 {
1510 let path = match git_dir_path {
1511 Some(path) => path,
1512 None => {
1513 let path = std::str::from_utf8(content)
1514 .ok()
1515 .and_then(|content| content.strip_prefix("gitdir:"))
1516 .context("not a valid gitfile")?
1517 .trim();
1518 git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1519 }
1520 }
1521 .clone();
1522 let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1523 anyhow::bail!("pointed-to git dir {path:?} not found")
1524 };
1525 let FakeFsEntry::Dir {
1526 git_repo_state,
1527 entries,
1528 ..
1529 } = git_dir_entry
1530 else {
1531 anyhow::bail!("gitfile points to a non-directory")
1532 };
1533 let common_dir = if let Some(child) = entries.get("commondir") {
1534 Path::new(
1535 std::str::from_utf8(child.file_content("commondir".as_ref())?)
1536 .context("commondir content")?,
1537 )
1538 .to_owned()
1539 } else {
1540 canonical_path.clone()
1541 };
1542 let repo_state = git_repo_state.get_or_insert_with(|| {
1543 Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1544 });
1545 let mut repo_state = repo_state.lock();
1546
1547 let result = f(&mut repo_state, &canonical_path, &common_dir);
1548
1549 if emit_git_event {
1550 drop(repo_state);
1551 state.emit_event([(canonical_path, None)]);
1552 }
1553
1554 Ok(result)
1555 } else {
1556 anyhow::bail!("not a valid git repository");
1557 }
1558 }
1559
1560 pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1561 where
1562 F: FnOnce(&mut FakeGitRepositoryState) -> T,
1563 {
1564 self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1565 }
1566
1567 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1568 self.with_git_state(dot_git, true, |state| {
1569 let branch = branch.map(Into::into);
1570 state.branches.extend(branch.clone());
1571 state.current_branch_name = branch
1572 })
1573 .unwrap();
1574 }
1575
1576 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1577 self.with_git_state(dot_git, true, |state| {
1578 if let Some(first) = branches.first()
1579 && state.current_branch_name.is_none()
1580 {
1581 state.current_branch_name = Some(first.to_string())
1582 }
1583 state
1584 .branches
1585 .extend(branches.iter().map(ToString::to_string));
1586 })
1587 .unwrap();
1588 }
1589
1590 pub fn set_unmerged_paths_for_repo(
1591 &self,
1592 dot_git: &Path,
1593 unmerged_state: &[(RepoPath, UnmergedStatus)],
1594 ) {
1595 self.with_git_state(dot_git, true, |state| {
1596 state.unmerged_paths.clear();
1597 state.unmerged_paths.extend(
1598 unmerged_state
1599 .iter()
1600 .map(|(path, content)| (path.clone(), *content)),
1601 );
1602 })
1603 .unwrap();
1604 }
1605
1606 pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(RepoPath, String)]) {
1607 self.with_git_state(dot_git, true, |state| {
1608 state.index_contents.clear();
1609 state.index_contents.extend(
1610 index_state
1611 .iter()
1612 .map(|(path, content)| (path.clone(), content.clone())),
1613 );
1614 })
1615 .unwrap();
1616 }
1617
1618 pub fn set_head_for_repo(
1619 &self,
1620 dot_git: &Path,
1621 head_state: &[(RepoPath, String)],
1622 sha: impl Into<String>,
1623 ) {
1624 self.with_git_state(dot_git, true, |state| {
1625 state.head_contents.clear();
1626 state.head_contents.extend(
1627 head_state
1628 .iter()
1629 .map(|(path, content)| (path.clone(), content.clone())),
1630 );
1631 state.refs.insert("HEAD".into(), sha.into());
1632 })
1633 .unwrap();
1634 }
1635
1636 pub fn set_git_content_for_repo(
1637 &self,
1638 dot_git: &Path,
1639 head_state: &[(RepoPath, String, Option<String>)],
1640 ) {
1641 self.with_git_state(dot_git, true, |state| {
1642 state.head_contents.clear();
1643 state.head_contents.extend(
1644 head_state
1645 .iter()
1646 .map(|(path, head_content, _)| (path.clone(), head_content.clone())),
1647 );
1648 state.index_contents.clear();
1649 state.index_contents.extend(head_state.iter().map(
1650 |(path, head_content, index_content)| {
1651 (
1652 path.clone(),
1653 index_content.as_ref().unwrap_or(head_content).clone(),
1654 )
1655 },
1656 ));
1657 })
1658 .unwrap();
1659 }
1660
1661 pub fn set_head_and_index_for_repo(
1662 &self,
1663 dot_git: &Path,
1664 contents_by_path: &[(RepoPath, String)],
1665 ) {
1666 self.with_git_state(dot_git, true, |state| {
1667 state.head_contents.clear();
1668 state.index_contents.clear();
1669 state.head_contents.extend(contents_by_path.iter().cloned());
1670 state
1671 .index_contents
1672 .extend(contents_by_path.iter().cloned());
1673 })
1674 .unwrap();
1675 }
1676
1677 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1678 self.with_git_state(dot_git, true, |state| {
1679 state.blames.clear();
1680 state.blames.extend(blames);
1681 })
1682 .unwrap();
1683 }
1684
1685 /// Put the given git repository into a state with the given status,
1686 /// by mutating the head, index, and unmerged state.
1687 pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&Path, FileStatus)]) {
1688 let workdir_path = dot_git.parent().unwrap();
1689 let workdir_contents = self.files_with_contents(workdir_path);
1690 self.with_git_state(dot_git, true, |state| {
1691 state.index_contents.clear();
1692 state.head_contents.clear();
1693 state.unmerged_paths.clear();
1694 for (path, content) in workdir_contents {
1695 let repo_path: RepoPath = path.strip_prefix(&workdir_path).unwrap().into();
1696 let status = statuses
1697 .iter()
1698 .find_map(|(p, status)| (**p == *repo_path.0).then_some(status));
1699 let mut content = String::from_utf8_lossy(&content).to_string();
1700
1701 let mut index_content = None;
1702 let mut head_content = None;
1703 match status {
1704 None => {
1705 index_content = Some(content.clone());
1706 head_content = Some(content);
1707 }
1708 Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1709 Some(FileStatus::Unmerged(unmerged_status)) => {
1710 state
1711 .unmerged_paths
1712 .insert(repo_path.clone(), *unmerged_status);
1713 content.push_str(" (unmerged)");
1714 index_content = Some(content.clone());
1715 head_content = Some(content);
1716 }
1717 Some(FileStatus::Tracked(TrackedStatus {
1718 index_status,
1719 worktree_status,
1720 })) => {
1721 match worktree_status {
1722 StatusCode::Modified => {
1723 let mut content = content.clone();
1724 content.push_str(" (modified in working copy)");
1725 index_content = Some(content);
1726 }
1727 StatusCode::TypeChanged | StatusCode::Unmodified => {
1728 index_content = Some(content.clone());
1729 }
1730 StatusCode::Added => {}
1731 StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1732 panic!("cannot create these statuses for an existing file");
1733 }
1734 };
1735 match index_status {
1736 StatusCode::Modified => {
1737 let mut content = index_content.clone().expect(
1738 "file cannot be both modified in index and created in working copy",
1739 );
1740 content.push_str(" (modified in index)");
1741 head_content = Some(content);
1742 }
1743 StatusCode::TypeChanged | StatusCode::Unmodified => {
1744 head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1745 }
1746 StatusCode::Added => {}
1747 StatusCode::Deleted => {
1748 head_content = Some("".into());
1749 }
1750 StatusCode::Renamed | StatusCode::Copied => {
1751 panic!("cannot create these statuses for an existing file");
1752 }
1753 };
1754 }
1755 };
1756
1757 if let Some(content) = index_content {
1758 state.index_contents.insert(repo_path.clone(), content);
1759 }
1760 if let Some(content) = head_content {
1761 state.head_contents.insert(repo_path.clone(), content);
1762 }
1763 }
1764 }).unwrap();
1765 }
1766
1767 pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1768 self.with_git_state(dot_git, true, |state| {
1769 state.simulated_index_write_error_message = message;
1770 })
1771 .unwrap();
1772 }
1773
1774 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1775 let mut result = Vec::new();
1776 let mut queue = collections::VecDeque::new();
1777 let state = &*self.state.lock();
1778 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1779 while let Some((path, entry)) = queue.pop_front() {
1780 if let FakeFsEntry::Dir { entries, .. } = entry {
1781 for (name, entry) in entries {
1782 queue.push_back((path.join(name), entry));
1783 }
1784 }
1785 if include_dot_git
1786 || !path
1787 .components()
1788 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1789 {
1790 result.push(path);
1791 }
1792 }
1793 result
1794 }
1795
1796 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1797 let mut result = Vec::new();
1798 let mut queue = collections::VecDeque::new();
1799 let state = &*self.state.lock();
1800 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1801 while let Some((path, entry)) = queue.pop_front() {
1802 if let FakeFsEntry::Dir { entries, .. } = entry {
1803 for (name, entry) in entries {
1804 queue.push_back((path.join(name), entry));
1805 }
1806 if include_dot_git
1807 || !path
1808 .components()
1809 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1810 {
1811 result.push(path);
1812 }
1813 }
1814 }
1815 result
1816 }
1817
1818 pub fn files(&self) -> Vec<PathBuf> {
1819 let mut result = Vec::new();
1820 let mut queue = collections::VecDeque::new();
1821 let state = &*self.state.lock();
1822 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1823 while let Some((path, entry)) = queue.pop_front() {
1824 match entry {
1825 FakeFsEntry::File { .. } => result.push(path),
1826 FakeFsEntry::Dir { entries, .. } => {
1827 for (name, entry) in entries {
1828 queue.push_back((path.join(name), entry));
1829 }
1830 }
1831 FakeFsEntry::Symlink { .. } => {}
1832 }
1833 }
1834 result
1835 }
1836
1837 pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1838 let mut result = Vec::new();
1839 let mut queue = collections::VecDeque::new();
1840 let state = &*self.state.lock();
1841 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1842 while let Some((path, entry)) = queue.pop_front() {
1843 match entry {
1844 FakeFsEntry::File { content, .. } => {
1845 if path.starts_with(prefix) {
1846 result.push((path, content.clone()));
1847 }
1848 }
1849 FakeFsEntry::Dir { entries, .. } => {
1850 for (name, entry) in entries {
1851 queue.push_back((path.join(name), entry));
1852 }
1853 }
1854 FakeFsEntry::Symlink { .. } => {}
1855 }
1856 }
1857 result
1858 }
1859
1860 /// How many `read_dir` calls have been issued.
1861 pub fn read_dir_call_count(&self) -> usize {
1862 self.state.lock().read_dir_call_count
1863 }
1864
1865 pub fn watched_paths(&self) -> Vec<PathBuf> {
1866 let state = self.state.lock();
1867 state
1868 .event_txs
1869 .iter()
1870 .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
1871 .collect()
1872 }
1873
1874 /// How many `metadata` calls have been issued.
1875 pub fn metadata_call_count(&self) -> usize {
1876 self.state.lock().metadata_call_count
1877 }
1878
1879 /// How many write operations have been issued for a specific path.
1880 pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
1881 let path = path.as_ref().to_path_buf();
1882 self.state
1883 .lock()
1884 .path_write_counts
1885 .get(&path)
1886 .copied()
1887 .unwrap_or(0)
1888 }
1889
1890 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1891 self.executor.simulate_random_delay()
1892 }
1893
1894 pub fn set_home_dir(&self, home_dir: PathBuf) {
1895 self.state.lock().home_dir = Some(home_dir);
1896 }
1897}
1898
1899#[cfg(any(test, feature = "test-support"))]
1900impl FakeFsEntry {
1901 fn is_file(&self) -> bool {
1902 matches!(self, Self::File { .. })
1903 }
1904
1905 fn is_symlink(&self) -> bool {
1906 matches!(self, Self::Symlink { .. })
1907 }
1908
1909 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1910 if let Self::File { content, .. } = self {
1911 Ok(content)
1912 } else {
1913 anyhow::bail!("not a file: {path:?}");
1914 }
1915 }
1916
1917 fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
1918 if let Self::Dir { entries, .. } = self {
1919 Ok(entries)
1920 } else {
1921 anyhow::bail!("not a directory: {path:?}");
1922 }
1923 }
1924}
1925
1926#[cfg(any(test, feature = "test-support"))]
1927struct FakeWatcher {
1928 tx: smol::channel::Sender<Vec<PathEvent>>,
1929 original_path: PathBuf,
1930 fs_state: Arc<Mutex<FakeFsState>>,
1931 prefixes: Mutex<Vec<PathBuf>>,
1932}
1933
1934#[cfg(any(test, feature = "test-support"))]
1935impl Watcher for FakeWatcher {
1936 fn add(&self, path: &Path) -> Result<()> {
1937 if path.starts_with(&self.original_path) {
1938 return Ok(());
1939 }
1940 self.fs_state
1941 .try_lock()
1942 .unwrap()
1943 .event_txs
1944 .push((path.to_owned(), self.tx.clone()));
1945 self.prefixes.lock().push(path.to_owned());
1946 Ok(())
1947 }
1948
1949 fn remove(&self, _: &Path) -> Result<()> {
1950 Ok(())
1951 }
1952}
1953
1954#[cfg(any(test, feature = "test-support"))]
1955#[derive(Debug)]
1956struct FakeHandle {
1957 inode: u64,
1958}
1959
1960#[cfg(any(test, feature = "test-support"))]
1961impl FileHandle for FakeHandle {
1962 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1963 let fs = fs.as_fake();
1964 let mut state = fs.state.lock();
1965 let Some(target) = state.moves.get(&self.inode).cloned() else {
1966 anyhow::bail!("fake fd not moved")
1967 };
1968
1969 if state.try_entry(&target, false).is_some() {
1970 return Ok(target);
1971 }
1972 anyhow::bail!("fake fd target not found")
1973 }
1974}
1975
1976#[cfg(any(test, feature = "test-support"))]
1977#[async_trait::async_trait]
1978impl Fs for FakeFs {
1979 async fn create_dir(&self, path: &Path) -> Result<()> {
1980 self.simulate_random_delay().await;
1981
1982 let mut created_dirs = Vec::new();
1983 let mut cur_path = PathBuf::new();
1984 for component in path.components() {
1985 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1986 cur_path.push(component);
1987 if should_skip {
1988 continue;
1989 }
1990 let mut state = self.state.lock();
1991
1992 let inode = state.get_and_increment_inode();
1993 let mtime = state.get_and_increment_mtime();
1994 state.write_path(&cur_path, |entry| {
1995 entry.or_insert_with(|| {
1996 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1997 FakeFsEntry::Dir {
1998 inode,
1999 mtime,
2000 len: 0,
2001 entries: Default::default(),
2002 git_repo_state: None,
2003 }
2004 });
2005 Ok(())
2006 })?
2007 }
2008
2009 self.state.lock().emit_event(created_dirs);
2010 Ok(())
2011 }
2012
2013 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2014 self.simulate_random_delay().await;
2015 let mut state = self.state.lock();
2016 let inode = state.get_and_increment_inode();
2017 let mtime = state.get_and_increment_mtime();
2018 let file = FakeFsEntry::File {
2019 inode,
2020 mtime,
2021 len: 0,
2022 content: Vec::new(),
2023 git_dir_path: None,
2024 };
2025 let mut kind = Some(PathEventKind::Created);
2026 state.write_path(path, |entry| {
2027 match entry {
2028 btree_map::Entry::Occupied(mut e) => {
2029 if options.overwrite {
2030 kind = Some(PathEventKind::Changed);
2031 *e.get_mut() = file;
2032 } else if !options.ignore_if_exists {
2033 anyhow::bail!("path already exists: {path:?}");
2034 }
2035 }
2036 btree_map::Entry::Vacant(e) => {
2037 e.insert(file);
2038 }
2039 }
2040 Ok(())
2041 })?;
2042 state.emit_event([(path, kind)]);
2043 Ok(())
2044 }
2045
2046 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2047 let mut state = self.state.lock();
2048 let file = FakeFsEntry::Symlink { target };
2049 state
2050 .write_path(path.as_ref(), move |e| match e {
2051 btree_map::Entry::Vacant(e) => {
2052 e.insert(file);
2053 Ok(())
2054 }
2055 btree_map::Entry::Occupied(mut e) => {
2056 *e.get_mut() = file;
2057 Ok(())
2058 }
2059 })
2060 .unwrap();
2061 state.emit_event([(path, None)]);
2062
2063 Ok(())
2064 }
2065
2066 async fn create_file_with(
2067 &self,
2068 path: &Path,
2069 mut content: Pin<&mut (dyn AsyncRead + Send)>,
2070 ) -> Result<()> {
2071 let mut bytes = Vec::new();
2072 content.read_to_end(&mut bytes).await?;
2073 self.write_file_internal(path, bytes, true)?;
2074 Ok(())
2075 }
2076
2077 async fn extract_tar_file(
2078 &self,
2079 path: &Path,
2080 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2081 ) -> Result<()> {
2082 let mut entries = content.entries()?;
2083 while let Some(entry) = entries.next().await {
2084 let mut entry = entry?;
2085 if entry.header().entry_type().is_file() {
2086 let path = path.join(entry.path()?.as_ref());
2087 let mut bytes = Vec::new();
2088 entry.read_to_end(&mut bytes).await?;
2089 self.create_dir(path.parent().unwrap()).await?;
2090 self.write_file_internal(&path, bytes, true)?;
2091 }
2092 }
2093 Ok(())
2094 }
2095
2096 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2097 self.simulate_random_delay().await;
2098
2099 let old_path = normalize_path(old_path);
2100 let new_path = normalize_path(new_path);
2101
2102 let mut state = self.state.lock();
2103 let moved_entry = state.write_path(&old_path, |e| {
2104 if let btree_map::Entry::Occupied(e) = e {
2105 Ok(e.get().clone())
2106 } else {
2107 anyhow::bail!("path does not exist: {old_path:?}")
2108 }
2109 })?;
2110
2111 let inode = match moved_entry {
2112 FakeFsEntry::File { inode, .. } => inode,
2113 FakeFsEntry::Dir { inode, .. } => inode,
2114 _ => 0,
2115 };
2116
2117 state.moves.insert(inode, new_path.clone());
2118
2119 state.write_path(&new_path, |e| {
2120 match e {
2121 btree_map::Entry::Occupied(mut e) => {
2122 if options.overwrite {
2123 *e.get_mut() = moved_entry;
2124 } else if !options.ignore_if_exists {
2125 anyhow::bail!("path already exists: {new_path:?}");
2126 }
2127 }
2128 btree_map::Entry::Vacant(e) => {
2129 e.insert(moved_entry);
2130 }
2131 }
2132 Ok(())
2133 })?;
2134
2135 state
2136 .write_path(&old_path, |e| {
2137 if let btree_map::Entry::Occupied(e) = e {
2138 Ok(e.remove())
2139 } else {
2140 unreachable!()
2141 }
2142 })
2143 .unwrap();
2144
2145 state.emit_event([
2146 (old_path, Some(PathEventKind::Removed)),
2147 (new_path, Some(PathEventKind::Created)),
2148 ]);
2149 Ok(())
2150 }
2151
2152 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2153 self.simulate_random_delay().await;
2154
2155 let source = normalize_path(source);
2156 let target = normalize_path(target);
2157 let mut state = self.state.lock();
2158 let mtime = state.get_and_increment_mtime();
2159 let inode = state.get_and_increment_inode();
2160 let source_entry = state.entry(&source)?;
2161 let content = source_entry.file_content(&source)?.clone();
2162 let mut kind = Some(PathEventKind::Created);
2163 state.write_path(&target, |e| match e {
2164 btree_map::Entry::Occupied(e) => {
2165 if options.overwrite {
2166 kind = Some(PathEventKind::Changed);
2167 Ok(Some(e.get().clone()))
2168 } else if !options.ignore_if_exists {
2169 anyhow::bail!("{target:?} already exists");
2170 } else {
2171 Ok(None)
2172 }
2173 }
2174 btree_map::Entry::Vacant(e) => Ok(Some(
2175 e.insert(FakeFsEntry::File {
2176 inode,
2177 mtime,
2178 len: content.len() as u64,
2179 content,
2180 git_dir_path: None,
2181 })
2182 .clone(),
2183 )),
2184 })?;
2185 state.emit_event([(target, kind)]);
2186 Ok(())
2187 }
2188
2189 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2190 self.simulate_random_delay().await;
2191
2192 let path = normalize_path(path);
2193 let parent_path = path.parent().context("cannot remove the root")?;
2194 let base_name = path.file_name().context("cannot remove the root")?;
2195
2196 let mut state = self.state.lock();
2197 let parent_entry = state.entry(parent_path)?;
2198 let entry = parent_entry
2199 .dir_entries(parent_path)?
2200 .entry(base_name.to_str().unwrap().into());
2201
2202 match entry {
2203 btree_map::Entry::Vacant(_) => {
2204 if !options.ignore_if_not_exists {
2205 anyhow::bail!("{path:?} does not exist");
2206 }
2207 }
2208 btree_map::Entry::Occupied(mut entry) => {
2209 {
2210 let children = entry.get_mut().dir_entries(&path)?;
2211 if !options.recursive && !children.is_empty() {
2212 anyhow::bail!("{path:?} is not empty");
2213 }
2214 }
2215 entry.remove();
2216 }
2217 }
2218 state.emit_event([(path, Some(PathEventKind::Removed))]);
2219 Ok(())
2220 }
2221
2222 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2223 self.simulate_random_delay().await;
2224
2225 let path = normalize_path(path);
2226 let parent_path = path.parent().context("cannot remove the root")?;
2227 let base_name = path.file_name().unwrap();
2228 let mut state = self.state.lock();
2229 let parent_entry = state.entry(parent_path)?;
2230 let entry = parent_entry
2231 .dir_entries(parent_path)?
2232 .entry(base_name.to_str().unwrap().into());
2233 match entry {
2234 btree_map::Entry::Vacant(_) => {
2235 if !options.ignore_if_not_exists {
2236 anyhow::bail!("{path:?} does not exist");
2237 }
2238 }
2239 btree_map::Entry::Occupied(mut entry) => {
2240 entry.get_mut().file_content(&path)?;
2241 entry.remove();
2242 }
2243 }
2244 state.emit_event([(path, Some(PathEventKind::Removed))]);
2245 Ok(())
2246 }
2247
2248 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2249 let bytes = self.load_internal(path).await?;
2250 Ok(Box::new(io::Cursor::new(bytes)))
2251 }
2252
2253 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2254 self.simulate_random_delay().await;
2255 let mut state = self.state.lock();
2256 let inode = match state.entry(path)? {
2257 FakeFsEntry::File { inode, .. } => *inode,
2258 FakeFsEntry::Dir { inode, .. } => *inode,
2259 _ => unreachable!(),
2260 };
2261 Ok(Arc::new(FakeHandle { inode }))
2262 }
2263
2264 async fn load(&self, path: &Path) -> Result<String> {
2265 let content = self.load_internal(path).await?;
2266 Ok(String::from_utf8(content)?)
2267 }
2268
2269 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2270 self.load_internal(path).await
2271 }
2272
2273 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2274 self.simulate_random_delay().await;
2275 let path = normalize_path(path.as_path());
2276 if let Some(path) = path.parent() {
2277 self.create_dir(path).await?;
2278 }
2279 self.write_file_internal(path, data.into_bytes(), true)?;
2280 Ok(())
2281 }
2282
2283 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2284 self.simulate_random_delay().await;
2285 let path = normalize_path(path);
2286 let content = chunks(text, line_ending).collect::<String>();
2287 if let Some(path) = path.parent() {
2288 self.create_dir(path).await?;
2289 }
2290 self.write_file_internal(path, content.into_bytes(), false)?;
2291 Ok(())
2292 }
2293
2294 async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2295 self.simulate_random_delay().await;
2296 let path = normalize_path(path);
2297 if let Some(path) = path.parent() {
2298 self.create_dir(path).await?;
2299 }
2300 self.write_file_internal(path, content.to_vec(), false)?;
2301 Ok(())
2302 }
2303
2304 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2305 let path = normalize_path(path);
2306 self.simulate_random_delay().await;
2307 let state = self.state.lock();
2308 let canonical_path = state
2309 .canonicalize(&path, true)
2310 .with_context(|| format!("path does not exist: {path:?}"))?;
2311 Ok(canonical_path)
2312 }
2313
2314 async fn is_file(&self, path: &Path) -> bool {
2315 let path = normalize_path(path);
2316 self.simulate_random_delay().await;
2317 let mut state = self.state.lock();
2318 if let Some((entry, _)) = state.try_entry(&path, true) {
2319 entry.is_file()
2320 } else {
2321 false
2322 }
2323 }
2324
2325 async fn is_dir(&self, path: &Path) -> bool {
2326 self.metadata(path)
2327 .await
2328 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2329 }
2330
2331 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2332 self.simulate_random_delay().await;
2333 let path = normalize_path(path);
2334 let mut state = self.state.lock();
2335 state.metadata_call_count += 1;
2336 if let Some((mut entry, _)) = state.try_entry(&path, false) {
2337 let is_symlink = entry.is_symlink();
2338 if is_symlink {
2339 if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2340 entry = e;
2341 } else {
2342 return Ok(None);
2343 }
2344 }
2345
2346 Ok(Some(match &*entry {
2347 FakeFsEntry::File {
2348 inode, mtime, len, ..
2349 } => Metadata {
2350 inode: *inode,
2351 mtime: *mtime,
2352 len: *len,
2353 is_dir: false,
2354 is_symlink,
2355 is_fifo: false,
2356 },
2357 FakeFsEntry::Dir {
2358 inode, mtime, len, ..
2359 } => Metadata {
2360 inode: *inode,
2361 mtime: *mtime,
2362 len: *len,
2363 is_dir: true,
2364 is_symlink,
2365 is_fifo: false,
2366 },
2367 FakeFsEntry::Symlink { .. } => unreachable!(),
2368 }))
2369 } else {
2370 Ok(None)
2371 }
2372 }
2373
2374 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2375 self.simulate_random_delay().await;
2376 let path = normalize_path(path);
2377 let mut state = self.state.lock();
2378 let (entry, _) = state
2379 .try_entry(&path, false)
2380 .with_context(|| format!("path does not exist: {path:?}"))?;
2381 if let FakeFsEntry::Symlink { target } = entry {
2382 Ok(target.clone())
2383 } else {
2384 anyhow::bail!("not a symlink: {path:?}")
2385 }
2386 }
2387
2388 async fn read_dir(
2389 &self,
2390 path: &Path,
2391 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2392 self.simulate_random_delay().await;
2393 let path = normalize_path(path);
2394 let mut state = self.state.lock();
2395 state.read_dir_call_count += 1;
2396 let entry = state.entry(&path)?;
2397 let children = entry.dir_entries(&path)?;
2398 let paths = children
2399 .keys()
2400 .map(|file_name| Ok(path.join(file_name)))
2401 .collect::<Vec<_>>();
2402 Ok(Box::pin(futures::stream::iter(paths)))
2403 }
2404
2405 async fn watch(
2406 &self,
2407 path: &Path,
2408 _: Duration,
2409 ) -> (
2410 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2411 Arc<dyn Watcher>,
2412 ) {
2413 self.simulate_random_delay().await;
2414 let (tx, rx) = smol::channel::unbounded();
2415 let path = path.to_path_buf();
2416 self.state.lock().event_txs.push((path.clone(), tx.clone()));
2417 let executor = self.executor.clone();
2418 let watcher = Arc::new(FakeWatcher {
2419 tx,
2420 original_path: path.to_owned(),
2421 fs_state: self.state.clone(),
2422 prefixes: Mutex::new(vec![path]),
2423 });
2424 (
2425 Box::pin(futures::StreamExt::filter(rx, {
2426 let watcher = watcher.clone();
2427 move |events| {
2428 let result = events.iter().any(|evt_path| {
2429 watcher
2430 .prefixes
2431 .lock()
2432 .iter()
2433 .any(|prefix| evt_path.path.starts_with(prefix))
2434 });
2435 let executor = executor.clone();
2436 async move {
2437 executor.simulate_random_delay().await;
2438 result
2439 }
2440 }
2441 })),
2442 watcher,
2443 )
2444 }
2445
2446 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
2447 use util::ResultExt as _;
2448
2449 self.with_git_state_and_paths(
2450 abs_dot_git,
2451 false,
2452 |_, repository_dir_path, common_dir_path| {
2453 Arc::new(fake_git_repo::FakeGitRepository {
2454 fs: self.this.upgrade().unwrap(),
2455 executor: self.executor.clone(),
2456 dot_git_path: abs_dot_git.to_path_buf(),
2457 repository_dir_path: repository_dir_path.to_owned(),
2458 common_dir_path: common_dir_path.to_owned(),
2459 checkpoints: Arc::default(),
2460 }) as _
2461 },
2462 )
2463 .log_err()
2464 }
2465
2466 fn git_init(
2467 &self,
2468 abs_work_directory_path: &Path,
2469 _fallback_branch_name: String,
2470 ) -> Result<()> {
2471 smol::block_on(self.create_dir(&abs_work_directory_path.join(".git")))
2472 }
2473
2474 async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2475 anyhow::bail!("Git clone is not supported in fake Fs")
2476 }
2477
2478 fn is_fake(&self) -> bool {
2479 true
2480 }
2481
2482 async fn is_case_sensitive(&self) -> Result<bool> {
2483 Ok(true)
2484 }
2485
2486 #[cfg(any(test, feature = "test-support"))]
2487 fn as_fake(&self) -> Arc<FakeFs> {
2488 self.this.upgrade().unwrap()
2489 }
2490
2491 fn home_dir(&self) -> Option<PathBuf> {
2492 self.state.lock().home_dir.clone()
2493 }
2494}
2495
2496fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2497 rope.chunks().flat_map(move |chunk| {
2498 let mut newline = false;
2499 let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
2500 chunk
2501 .lines()
2502 .flat_map(move |line| {
2503 let ending = if newline {
2504 Some(line_ending.as_str())
2505 } else {
2506 None
2507 };
2508 newline = true;
2509 ending.into_iter().chain([line])
2510 })
2511 .chain(end_with_newline)
2512 })
2513}
2514
2515pub fn normalize_path(path: &Path) -> PathBuf {
2516 let mut components = path.components().peekable();
2517 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2518 components.next();
2519 PathBuf::from(c.as_os_str())
2520 } else {
2521 PathBuf::new()
2522 };
2523
2524 for component in components {
2525 match component {
2526 Component::Prefix(..) => unreachable!(),
2527 Component::RootDir => {
2528 ret.push(component.as_os_str());
2529 }
2530 Component::CurDir => {}
2531 Component::ParentDir => {
2532 ret.pop();
2533 }
2534 Component::Normal(c) => {
2535 ret.push(c);
2536 }
2537 }
2538 }
2539 ret
2540}
2541
2542pub async fn copy_recursive<'a>(
2543 fs: &'a dyn Fs,
2544 source: &'a Path,
2545 target: &'a Path,
2546 options: CopyOptions,
2547) -> Result<()> {
2548 for (item, is_dir) in read_dir_items(fs, source).await? {
2549 let Ok(item_relative_path) = item.strip_prefix(source) else {
2550 continue;
2551 };
2552 let target_item = if item_relative_path == Path::new("") {
2553 target.to_path_buf()
2554 } else {
2555 target.join(item_relative_path)
2556 };
2557 if is_dir {
2558 if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2559 if options.ignore_if_exists {
2560 continue;
2561 } else {
2562 anyhow::bail!("{target_item:?} already exists");
2563 }
2564 }
2565 let _ = fs
2566 .remove_dir(
2567 &target_item,
2568 RemoveOptions {
2569 recursive: true,
2570 ignore_if_not_exists: true,
2571 },
2572 )
2573 .await;
2574 fs.create_dir(&target_item).await?;
2575 } else {
2576 fs.copy_file(&item, &target_item, options).await?;
2577 }
2578 }
2579 Ok(())
2580}
2581
2582/// Recursively reads all of the paths in the given directory.
2583///
2584/// Returns a vector of tuples of (path, is_dir).
2585pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2586 let mut items = Vec::new();
2587 read_recursive(fs, source, &mut items).await?;
2588 Ok(items)
2589}
2590
2591fn read_recursive<'a>(
2592 fs: &'a dyn Fs,
2593 source: &'a Path,
2594 output: &'a mut Vec<(PathBuf, bool)>,
2595) -> BoxFuture<'a, Result<()>> {
2596 use futures::future::FutureExt;
2597
2598 async move {
2599 let metadata = fs
2600 .metadata(source)
2601 .await?
2602 .with_context(|| format!("path does not exist: {source:?}"))?;
2603
2604 if metadata.is_dir {
2605 output.push((source.to_path_buf(), true));
2606 let mut children = fs.read_dir(source).await?;
2607 while let Some(child_path) = children.next().await {
2608 if let Ok(child_path) = child_path {
2609 read_recursive(fs, &child_path, output).await?;
2610 }
2611 }
2612 } else {
2613 output.push((source.to_path_buf(), false));
2614 }
2615 Ok(())
2616 }
2617 .boxed()
2618}
2619
2620// todo(windows)
2621// can we get file id not open the file twice?
2622// https://github.com/rust-lang/rust/issues/63010
2623#[cfg(target_os = "windows")]
2624async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2625 use std::os::windows::io::AsRawHandle;
2626
2627 use smol::fs::windows::OpenOptionsExt;
2628 use windows::Win32::{
2629 Foundation::HANDLE,
2630 Storage::FileSystem::{
2631 BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2632 },
2633 };
2634
2635 let file = smol::fs::OpenOptions::new()
2636 .read(true)
2637 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2638 .open(path)
2639 .await?;
2640
2641 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2642 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2643 // This function supports Windows XP+
2644 smol::unblock(move || {
2645 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2646
2647 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2648 })
2649 .await
2650}
2651
2652#[cfg(target_os = "windows")]
2653fn atomic_replace<P: AsRef<Path>>(
2654 replaced_file: P,
2655 replacement_file: P,
2656) -> windows::core::Result<()> {
2657 use windows::{
2658 Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2659 core::HSTRING,
2660 };
2661
2662 // If the file does not exist, create it.
2663 let _ = std::fs::File::create_new(replaced_file.as_ref());
2664
2665 unsafe {
2666 ReplaceFileW(
2667 &HSTRING::from(replaced_file.as_ref().to_string_lossy().to_string()),
2668 &HSTRING::from(replacement_file.as_ref().to_string_lossy().to_string()),
2669 None,
2670 REPLACE_FILE_FLAGS::default(),
2671 None,
2672 None,
2673 )
2674 }
2675}
2676
2677#[cfg(test)]
2678mod tests {
2679 use super::*;
2680 use gpui::BackgroundExecutor;
2681 use serde_json::json;
2682 use util::path;
2683
2684 #[gpui::test]
2685 async fn test_fake_fs(executor: BackgroundExecutor) {
2686 let fs = FakeFs::new(executor.clone());
2687 fs.insert_tree(
2688 path!("/root"),
2689 json!({
2690 "dir1": {
2691 "a": "A",
2692 "b": "B"
2693 },
2694 "dir2": {
2695 "c": "C",
2696 "dir3": {
2697 "d": "D"
2698 }
2699 }
2700 }),
2701 )
2702 .await;
2703
2704 assert_eq!(
2705 fs.files(),
2706 vec![
2707 PathBuf::from(path!("/root/dir1/a")),
2708 PathBuf::from(path!("/root/dir1/b")),
2709 PathBuf::from(path!("/root/dir2/c")),
2710 PathBuf::from(path!("/root/dir2/dir3/d")),
2711 ]
2712 );
2713
2714 fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2715 .await
2716 .unwrap();
2717
2718 assert_eq!(
2719 fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2720 .await
2721 .unwrap(),
2722 PathBuf::from(path!("/root/dir2/dir3")),
2723 );
2724 assert_eq!(
2725 fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2726 .await
2727 .unwrap(),
2728 PathBuf::from(path!("/root/dir2/dir3/d")),
2729 );
2730 assert_eq!(
2731 fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2732 .await
2733 .unwrap(),
2734 "D",
2735 );
2736 }
2737
2738 #[gpui::test]
2739 async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2740 let fs = FakeFs::new(executor.clone());
2741 fs.insert_tree(
2742 path!("/outer"),
2743 json!({
2744 "a": "A",
2745 "b": "B",
2746 "inner": {}
2747 }),
2748 )
2749 .await;
2750
2751 assert_eq!(
2752 fs.files(),
2753 vec![
2754 PathBuf::from(path!("/outer/a")),
2755 PathBuf::from(path!("/outer/b")),
2756 ]
2757 );
2758
2759 let source = Path::new(path!("/outer/a"));
2760 let target = Path::new(path!("/outer/a copy"));
2761 copy_recursive(fs.as_ref(), source, target, Default::default())
2762 .await
2763 .unwrap();
2764
2765 assert_eq!(
2766 fs.files(),
2767 vec![
2768 PathBuf::from(path!("/outer/a")),
2769 PathBuf::from(path!("/outer/a copy")),
2770 PathBuf::from(path!("/outer/b")),
2771 ]
2772 );
2773
2774 let source = Path::new(path!("/outer/a"));
2775 let target = Path::new(path!("/outer/inner/a copy"));
2776 copy_recursive(fs.as_ref(), source, target, Default::default())
2777 .await
2778 .unwrap();
2779
2780 assert_eq!(
2781 fs.files(),
2782 vec![
2783 PathBuf::from(path!("/outer/a")),
2784 PathBuf::from(path!("/outer/a copy")),
2785 PathBuf::from(path!("/outer/b")),
2786 PathBuf::from(path!("/outer/inner/a copy")),
2787 ]
2788 );
2789 }
2790
2791 #[gpui::test]
2792 async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2793 let fs = FakeFs::new(executor.clone());
2794 fs.insert_tree(
2795 path!("/outer"),
2796 json!({
2797 "a": "A",
2798 "empty": {},
2799 "non-empty": {
2800 "b": "B",
2801 }
2802 }),
2803 )
2804 .await;
2805
2806 assert_eq!(
2807 fs.files(),
2808 vec![
2809 PathBuf::from(path!("/outer/a")),
2810 PathBuf::from(path!("/outer/non-empty/b")),
2811 ]
2812 );
2813 assert_eq!(
2814 fs.directories(false),
2815 vec![
2816 PathBuf::from(path!("/")),
2817 PathBuf::from(path!("/outer")),
2818 PathBuf::from(path!("/outer/empty")),
2819 PathBuf::from(path!("/outer/non-empty")),
2820 ]
2821 );
2822
2823 let source = Path::new(path!("/outer/empty"));
2824 let target = Path::new(path!("/outer/empty copy"));
2825 copy_recursive(fs.as_ref(), source, target, Default::default())
2826 .await
2827 .unwrap();
2828
2829 assert_eq!(
2830 fs.files(),
2831 vec![
2832 PathBuf::from(path!("/outer/a")),
2833 PathBuf::from(path!("/outer/non-empty/b")),
2834 ]
2835 );
2836 assert_eq!(
2837 fs.directories(false),
2838 vec![
2839 PathBuf::from(path!("/")),
2840 PathBuf::from(path!("/outer")),
2841 PathBuf::from(path!("/outer/empty")),
2842 PathBuf::from(path!("/outer/empty copy")),
2843 PathBuf::from(path!("/outer/non-empty")),
2844 ]
2845 );
2846
2847 let source = Path::new(path!("/outer/non-empty"));
2848 let target = Path::new(path!("/outer/non-empty copy"));
2849 copy_recursive(fs.as_ref(), source, target, Default::default())
2850 .await
2851 .unwrap();
2852
2853 assert_eq!(
2854 fs.files(),
2855 vec![
2856 PathBuf::from(path!("/outer/a")),
2857 PathBuf::from(path!("/outer/non-empty/b")),
2858 PathBuf::from(path!("/outer/non-empty copy/b")),
2859 ]
2860 );
2861 assert_eq!(
2862 fs.directories(false),
2863 vec![
2864 PathBuf::from(path!("/")),
2865 PathBuf::from(path!("/outer")),
2866 PathBuf::from(path!("/outer/empty")),
2867 PathBuf::from(path!("/outer/empty copy")),
2868 PathBuf::from(path!("/outer/non-empty")),
2869 PathBuf::from(path!("/outer/non-empty copy")),
2870 ]
2871 );
2872 }
2873
2874 #[gpui::test]
2875 async fn test_copy_recursive(executor: BackgroundExecutor) {
2876 let fs = FakeFs::new(executor.clone());
2877 fs.insert_tree(
2878 path!("/outer"),
2879 json!({
2880 "inner1": {
2881 "a": "A",
2882 "b": "B",
2883 "inner3": {
2884 "d": "D",
2885 },
2886 "inner4": {}
2887 },
2888 "inner2": {
2889 "c": "C",
2890 }
2891 }),
2892 )
2893 .await;
2894
2895 assert_eq!(
2896 fs.files(),
2897 vec![
2898 PathBuf::from(path!("/outer/inner1/a")),
2899 PathBuf::from(path!("/outer/inner1/b")),
2900 PathBuf::from(path!("/outer/inner2/c")),
2901 PathBuf::from(path!("/outer/inner1/inner3/d")),
2902 ]
2903 );
2904 assert_eq!(
2905 fs.directories(false),
2906 vec![
2907 PathBuf::from(path!("/")),
2908 PathBuf::from(path!("/outer")),
2909 PathBuf::from(path!("/outer/inner1")),
2910 PathBuf::from(path!("/outer/inner2")),
2911 PathBuf::from(path!("/outer/inner1/inner3")),
2912 PathBuf::from(path!("/outer/inner1/inner4")),
2913 ]
2914 );
2915
2916 let source = Path::new(path!("/outer"));
2917 let target = Path::new(path!("/outer/inner1/outer"));
2918 copy_recursive(fs.as_ref(), source, target, Default::default())
2919 .await
2920 .unwrap();
2921
2922 assert_eq!(
2923 fs.files(),
2924 vec![
2925 PathBuf::from(path!("/outer/inner1/a")),
2926 PathBuf::from(path!("/outer/inner1/b")),
2927 PathBuf::from(path!("/outer/inner2/c")),
2928 PathBuf::from(path!("/outer/inner1/inner3/d")),
2929 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2930 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2931 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2932 PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2933 ]
2934 );
2935 assert_eq!(
2936 fs.directories(false),
2937 vec![
2938 PathBuf::from(path!("/")),
2939 PathBuf::from(path!("/outer")),
2940 PathBuf::from(path!("/outer/inner1")),
2941 PathBuf::from(path!("/outer/inner2")),
2942 PathBuf::from(path!("/outer/inner1/inner3")),
2943 PathBuf::from(path!("/outer/inner1/inner4")),
2944 PathBuf::from(path!("/outer/inner1/outer")),
2945 PathBuf::from(path!("/outer/inner1/outer/inner1")),
2946 PathBuf::from(path!("/outer/inner1/outer/inner2")),
2947 PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
2948 PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
2949 ]
2950 );
2951 }
2952
2953 #[gpui::test]
2954 async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2955 let fs = FakeFs::new(executor.clone());
2956 fs.insert_tree(
2957 path!("/outer"),
2958 json!({
2959 "inner1": {
2960 "a": "A",
2961 "b": "B",
2962 "outer": {
2963 "inner1": {
2964 "a": "B"
2965 }
2966 }
2967 },
2968 "inner2": {
2969 "c": "C",
2970 }
2971 }),
2972 )
2973 .await;
2974
2975 assert_eq!(
2976 fs.files(),
2977 vec![
2978 PathBuf::from(path!("/outer/inner1/a")),
2979 PathBuf::from(path!("/outer/inner1/b")),
2980 PathBuf::from(path!("/outer/inner2/c")),
2981 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2982 ]
2983 );
2984 assert_eq!(
2985 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2986 .await
2987 .unwrap(),
2988 "B",
2989 );
2990
2991 let source = Path::new(path!("/outer"));
2992 let target = Path::new(path!("/outer/inner1/outer"));
2993 copy_recursive(
2994 fs.as_ref(),
2995 source,
2996 target,
2997 CopyOptions {
2998 overwrite: true,
2999 ..Default::default()
3000 },
3001 )
3002 .await
3003 .unwrap();
3004
3005 assert_eq!(
3006 fs.files(),
3007 vec![
3008 PathBuf::from(path!("/outer/inner1/a")),
3009 PathBuf::from(path!("/outer/inner1/b")),
3010 PathBuf::from(path!("/outer/inner2/c")),
3011 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3012 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3013 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3014 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3015 ]
3016 );
3017 assert_eq!(
3018 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3019 .await
3020 .unwrap(),
3021 "A"
3022 );
3023 }
3024
3025 #[gpui::test]
3026 async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
3027 let fs = FakeFs::new(executor.clone());
3028 fs.insert_tree(
3029 path!("/outer"),
3030 json!({
3031 "inner1": {
3032 "a": "A",
3033 "b": "B",
3034 "outer": {
3035 "inner1": {
3036 "a": "B"
3037 }
3038 }
3039 },
3040 "inner2": {
3041 "c": "C",
3042 }
3043 }),
3044 )
3045 .await;
3046
3047 assert_eq!(
3048 fs.files(),
3049 vec![
3050 PathBuf::from(path!("/outer/inner1/a")),
3051 PathBuf::from(path!("/outer/inner1/b")),
3052 PathBuf::from(path!("/outer/inner2/c")),
3053 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3054 ]
3055 );
3056 assert_eq!(
3057 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3058 .await
3059 .unwrap(),
3060 "B",
3061 );
3062
3063 let source = Path::new(path!("/outer"));
3064 let target = Path::new(path!("/outer/inner1/outer"));
3065 copy_recursive(
3066 fs.as_ref(),
3067 source,
3068 target,
3069 CopyOptions {
3070 ignore_if_exists: true,
3071 ..Default::default()
3072 },
3073 )
3074 .await
3075 .unwrap();
3076
3077 assert_eq!(
3078 fs.files(),
3079 vec![
3080 PathBuf::from(path!("/outer/inner1/a")),
3081 PathBuf::from(path!("/outer/inner1/b")),
3082 PathBuf::from(path!("/outer/inner2/c")),
3083 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3084 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3085 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3086 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3087 ]
3088 );
3089 assert_eq!(
3090 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3091 .await
3092 .unwrap(),
3093 "B"
3094 );
3095 }
3096
3097 #[gpui::test]
3098 async fn test_realfs_atomic_write(executor: BackgroundExecutor) {
3099 // With the file handle still open, the file should be replaced
3100 // https://github.com/zed-industries/zed/issues/30054
3101 let fs = RealFs {
3102 git_binary_path: None,
3103 executor,
3104 };
3105 let temp_dir = TempDir::new().unwrap();
3106 let file_to_be_replaced = temp_dir.path().join("file.txt");
3107 let mut file = std::fs::File::create_new(&file_to_be_replaced).unwrap();
3108 file.write_all(b"Hello").unwrap();
3109 // drop(file); // We still hold the file handle here
3110 let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3111 assert_eq!(content, "Hello");
3112 smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "World".into())).unwrap();
3113 let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3114 assert_eq!(content, "World");
3115 }
3116
3117 #[gpui::test]
3118 async fn test_realfs_atomic_write_non_existing_file(executor: BackgroundExecutor) {
3119 let fs = RealFs {
3120 git_binary_path: None,
3121 executor,
3122 };
3123 let temp_dir = TempDir::new().unwrap();
3124 let file_to_be_replaced = temp_dir.path().join("file.txt");
3125 smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "Hello".into())).unwrap();
3126 let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3127 assert_eq!(content, "Hello");
3128 }
3129}