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