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