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