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