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