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