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