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