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