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