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