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