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