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