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