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