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