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