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