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