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 buffered_event_count(&self) -> usize {
1180 self.state.lock().buffered_events.len()
1181 }
1182
1183 pub fn flush_events(&self, count: usize) {
1184 self.state.lock().flush_events(count);
1185 }
1186
1187 #[must_use]
1188 pub fn insert_tree<'a>(
1189 &'a self,
1190 path: impl 'a + AsRef<Path> + Send,
1191 tree: serde_json::Value,
1192 ) -> futures::future::BoxFuture<'a, ()> {
1193 use futures::FutureExt as _;
1194 use serde_json::Value::*;
1195
1196 async move {
1197 let path = path.as_ref();
1198
1199 match tree {
1200 Object(map) => {
1201 self.create_dir(path).await.unwrap();
1202 for (name, contents) in map {
1203 let mut path = PathBuf::from(path);
1204 path.push(name);
1205 self.insert_tree(&path, contents).await;
1206 }
1207 }
1208 Null => {
1209 self.create_dir(path).await.unwrap();
1210 }
1211 String(contents) => {
1212 self.insert_file(&path, contents.into_bytes()).await;
1213 }
1214 _ => {
1215 panic!("JSON object must contain only objects, strings, or null");
1216 }
1217 }
1218 }
1219 .boxed()
1220 }
1221
1222 pub fn insert_tree_from_real_fs<'a>(
1223 &'a self,
1224 path: impl 'a + AsRef<Path> + Send,
1225 src_path: impl 'a + AsRef<Path> + Send,
1226 ) -> futures::future::BoxFuture<'a, ()> {
1227 use futures::FutureExt as _;
1228
1229 async move {
1230 let path = path.as_ref();
1231 if std::fs::metadata(&src_path).unwrap().is_file() {
1232 let contents = std::fs::read(src_path).unwrap();
1233 self.insert_file(path, contents).await;
1234 } else {
1235 self.create_dir(path).await.unwrap();
1236 for entry in std::fs::read_dir(&src_path).unwrap() {
1237 let entry = entry.unwrap();
1238 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1239 .await;
1240 }
1241 }
1242 }
1243 .boxed()
1244 }
1245
1246 pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> T
1247 where
1248 F: FnOnce(&mut FakeGitRepositoryState) -> T,
1249 {
1250 let mut state = self.state.lock();
1251 let entry = state.read_path(dot_git).unwrap();
1252 let mut entry = entry.lock();
1253
1254 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1255 let repo_state = git_repo_state.get_or_insert_with(|| {
1256 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1257 dot_git.to_path_buf(),
1258 state.git_event_tx.clone(),
1259 )))
1260 });
1261 let mut repo_state = repo_state.lock();
1262
1263 let result = f(&mut repo_state);
1264
1265 if emit_git_event {
1266 state.emit_event([(dot_git, None)]);
1267 }
1268
1269 result
1270 } else {
1271 panic!("not a directory");
1272 }
1273 }
1274
1275 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1276 self.with_git_state(dot_git, true, |state| {
1277 let branch = branch.map(Into::into);
1278 state.branches.extend(branch.clone());
1279 state.current_branch_name = branch
1280 })
1281 }
1282
1283 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1284 self.with_git_state(dot_git, true, |state| {
1285 if let Some(first) = branches.first() {
1286 if state.current_branch_name.is_none() {
1287 state.current_branch_name = Some(first.to_string())
1288 }
1289 }
1290 state
1291 .branches
1292 .extend(branches.iter().map(ToString::to_string));
1293 })
1294 }
1295
1296 pub fn set_unmerged_paths_for_repo(
1297 &self,
1298 dot_git: &Path,
1299 unmerged_state: &[(RepoPath, UnmergedStatus)],
1300 ) {
1301 self.with_git_state(dot_git, true, |state| {
1302 state.unmerged_paths.clear();
1303 state.unmerged_paths.extend(
1304 unmerged_state
1305 .iter()
1306 .map(|(path, content)| (path.clone(), *content)),
1307 );
1308 });
1309 }
1310
1311 pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(RepoPath, String)]) {
1312 self.with_git_state(dot_git, true, |state| {
1313 state.index_contents.clear();
1314 state.index_contents.extend(
1315 index_state
1316 .iter()
1317 .map(|(path, content)| (path.clone(), content.clone())),
1318 );
1319 });
1320 }
1321
1322 pub fn set_head_for_repo(&self, dot_git: &Path, head_state: &[(RepoPath, String)]) {
1323 self.with_git_state(dot_git, true, |state| {
1324 state.head_contents.clear();
1325 state.head_contents.extend(
1326 head_state
1327 .iter()
1328 .map(|(path, content)| (path.clone(), content.clone())),
1329 );
1330 });
1331 }
1332
1333 pub fn set_git_content_for_repo(
1334 &self,
1335 dot_git: &Path,
1336 head_state: &[(RepoPath, String, Option<String>)],
1337 ) {
1338 self.with_git_state(dot_git, true, |state| {
1339 state.head_contents.clear();
1340 state.head_contents.extend(
1341 head_state
1342 .iter()
1343 .map(|(path, head_content, _)| (path.clone(), head_content.clone())),
1344 );
1345 state.index_contents.clear();
1346 state.index_contents.extend(head_state.iter().map(
1347 |(path, head_content, index_content)| {
1348 (
1349 path.clone(),
1350 index_content.as_ref().unwrap_or(head_content).clone(),
1351 )
1352 },
1353 ));
1354 });
1355 }
1356
1357 pub fn set_head_and_index_for_repo(
1358 &self,
1359 dot_git: &Path,
1360 contents_by_path: &[(RepoPath, String)],
1361 ) {
1362 self.with_git_state(dot_git, true, |state| {
1363 state.head_contents.clear();
1364 state.index_contents.clear();
1365 state.head_contents.extend(contents_by_path.iter().cloned());
1366 state
1367 .index_contents
1368 .extend(contents_by_path.iter().cloned());
1369 });
1370 }
1371
1372 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1373 self.with_git_state(dot_git, true, |state| {
1374 state.blames.clear();
1375 state.blames.extend(blames);
1376 });
1377 }
1378
1379 /// Put the given git repository into a state with the given status,
1380 /// by mutating the head, index, and unmerged state.
1381 pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&Path, FileStatus)]) {
1382 let workdir_path = dot_git.parent().unwrap();
1383 let workdir_contents = self.files_with_contents(&workdir_path);
1384 self.with_git_state(dot_git, true, |state| {
1385 state.index_contents.clear();
1386 state.head_contents.clear();
1387 state.unmerged_paths.clear();
1388 for (path, content) in workdir_contents {
1389 let repo_path: RepoPath = path.strip_prefix(&workdir_path).unwrap().into();
1390 let status = statuses
1391 .iter()
1392 .find_map(|(p, status)| (**p == *repo_path.0).then_some(status));
1393 let mut content = String::from_utf8_lossy(&content).to_string();
1394
1395 let mut index_content = None;
1396 let mut head_content = None;
1397 match status {
1398 None => {
1399 index_content = Some(content.clone());
1400 head_content = Some(content);
1401 }
1402 Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1403 Some(FileStatus::Unmerged(unmerged_status)) => {
1404 state
1405 .unmerged_paths
1406 .insert(repo_path.clone(), *unmerged_status);
1407 content.push_str(" (unmerged)");
1408 index_content = Some(content.clone());
1409 head_content = Some(content);
1410 }
1411 Some(FileStatus::Tracked(TrackedStatus {
1412 index_status,
1413 worktree_status,
1414 })) => {
1415 match worktree_status {
1416 StatusCode::Modified => {
1417 let mut content = content.clone();
1418 content.push_str(" (modified in working copy)");
1419 index_content = Some(content);
1420 }
1421 StatusCode::TypeChanged | StatusCode::Unmodified => {
1422 index_content = Some(content.clone());
1423 }
1424 StatusCode::Added => {}
1425 StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1426 panic!("cannot create these statuses for an existing file");
1427 }
1428 };
1429 match index_status {
1430 StatusCode::Modified => {
1431 let mut content = index_content.clone().expect(
1432 "file cannot be both modified in index and created in working copy",
1433 );
1434 content.push_str(" (modified in index)");
1435 head_content = Some(content);
1436 }
1437 StatusCode::TypeChanged | StatusCode::Unmodified => {
1438 head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1439 }
1440 StatusCode::Added => {}
1441 StatusCode::Deleted => {
1442 head_content = Some("".into());
1443 }
1444 StatusCode::Renamed | StatusCode::Copied => {
1445 panic!("cannot create these statuses for an existing file");
1446 }
1447 };
1448 }
1449 };
1450
1451 if let Some(content) = index_content {
1452 state.index_contents.insert(repo_path.clone(), content);
1453 }
1454 if let Some(content) = head_content {
1455 state.head_contents.insert(repo_path.clone(), content);
1456 }
1457 }
1458 });
1459 }
1460
1461 pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1462 self.with_git_state(dot_git, true, |state| {
1463 state.simulated_index_write_error_message = message;
1464 });
1465 }
1466
1467 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1468 let mut result = Vec::new();
1469 let mut queue = collections::VecDeque::new();
1470 queue.push_back((
1471 PathBuf::from(util::path!("/")),
1472 self.state.lock().root.clone(),
1473 ));
1474 while let Some((path, entry)) = queue.pop_front() {
1475 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1476 for (name, entry) in entries {
1477 queue.push_back((path.join(name), entry.clone()));
1478 }
1479 }
1480 if include_dot_git
1481 || !path
1482 .components()
1483 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1484 {
1485 result.push(path);
1486 }
1487 }
1488 result
1489 }
1490
1491 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1492 let mut result = Vec::new();
1493 let mut queue = collections::VecDeque::new();
1494 queue.push_back((
1495 PathBuf::from(util::path!("/")),
1496 self.state.lock().root.clone(),
1497 ));
1498 while let Some((path, entry)) = queue.pop_front() {
1499 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1500 for (name, entry) in entries {
1501 queue.push_back((path.join(name), entry.clone()));
1502 }
1503 if include_dot_git
1504 || !path
1505 .components()
1506 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1507 {
1508 result.push(path);
1509 }
1510 }
1511 }
1512 result
1513 }
1514
1515 pub fn files(&self) -> Vec<PathBuf> {
1516 let mut result = Vec::new();
1517 let mut queue = collections::VecDeque::new();
1518 queue.push_back((
1519 PathBuf::from(util::path!("/")),
1520 self.state.lock().root.clone(),
1521 ));
1522 while let Some((path, entry)) = queue.pop_front() {
1523 let e = entry.lock();
1524 match &*e {
1525 FakeFsEntry::File { .. } => result.push(path),
1526 FakeFsEntry::Dir { entries, .. } => {
1527 for (name, entry) in entries {
1528 queue.push_back((path.join(name), entry.clone()));
1529 }
1530 }
1531 FakeFsEntry::Symlink { .. } => {}
1532 }
1533 }
1534 result
1535 }
1536
1537 pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1538 let mut result = Vec::new();
1539 let mut queue = collections::VecDeque::new();
1540 queue.push_back((
1541 PathBuf::from(util::path!("/")),
1542 self.state.lock().root.clone(),
1543 ));
1544 while let Some((path, entry)) = queue.pop_front() {
1545 let e = entry.lock();
1546 match &*e {
1547 FakeFsEntry::File { content, .. } => {
1548 if path.starts_with(prefix) {
1549 result.push((path, content.clone()));
1550 }
1551 }
1552 FakeFsEntry::Dir { entries, .. } => {
1553 for (name, entry) in entries {
1554 queue.push_back((path.join(name), entry.clone()));
1555 }
1556 }
1557 FakeFsEntry::Symlink { .. } => {}
1558 }
1559 }
1560 result
1561 }
1562
1563 /// How many `read_dir` calls have been issued.
1564 pub fn read_dir_call_count(&self) -> usize {
1565 self.state.lock().read_dir_call_count
1566 }
1567
1568 /// How many `metadata` calls have been issued.
1569 pub fn metadata_call_count(&self) -> usize {
1570 self.state.lock().metadata_call_count
1571 }
1572
1573 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1574 self.executor.simulate_random_delay()
1575 }
1576
1577 pub fn set_home_dir(&self, home_dir: PathBuf) {
1578 self.state.lock().home_dir = Some(home_dir);
1579 }
1580}
1581
1582#[cfg(any(test, feature = "test-support"))]
1583impl FakeFsEntry {
1584 fn is_file(&self) -> bool {
1585 matches!(self, Self::File { .. })
1586 }
1587
1588 fn is_symlink(&self) -> bool {
1589 matches!(self, Self::Symlink { .. })
1590 }
1591
1592 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1593 if let Self::File { content, .. } = self {
1594 Ok(content)
1595 } else {
1596 Err(anyhow!("not a file: {}", path.display()))
1597 }
1598 }
1599
1600 fn dir_entries(
1601 &mut self,
1602 path: &Path,
1603 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1604 if let Self::Dir { entries, .. } = self {
1605 Ok(entries)
1606 } else {
1607 Err(anyhow!("not a directory: {}", path.display()))
1608 }
1609 }
1610}
1611
1612#[cfg(any(test, feature = "test-support"))]
1613struct FakeWatcher {}
1614
1615#[cfg(any(test, feature = "test-support"))]
1616impl Watcher for FakeWatcher {
1617 fn add(&self, _: &Path) -> Result<()> {
1618 Ok(())
1619 }
1620
1621 fn remove(&self, _: &Path) -> Result<()> {
1622 Ok(())
1623 }
1624}
1625
1626#[cfg(any(test, feature = "test-support"))]
1627#[derive(Debug)]
1628struct FakeHandle {
1629 inode: u64,
1630}
1631
1632#[cfg(any(test, feature = "test-support"))]
1633impl FileHandle for FakeHandle {
1634 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1635 let fs = fs.as_fake();
1636 let state = fs.state.lock();
1637 let Some(target) = state.moves.get(&self.inode) else {
1638 anyhow::bail!("fake fd not moved")
1639 };
1640
1641 if state.try_read_path(&target, false).is_some() {
1642 return Ok(target.clone());
1643 }
1644 anyhow::bail!("fake fd target not found")
1645 }
1646}
1647
1648#[cfg(any(test, feature = "test-support"))]
1649#[async_trait::async_trait]
1650impl Fs for FakeFs {
1651 async fn create_dir(&self, path: &Path) -> Result<()> {
1652 self.simulate_random_delay().await;
1653
1654 let mut created_dirs = Vec::new();
1655 let mut cur_path = PathBuf::new();
1656 for component in path.components() {
1657 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1658 cur_path.push(component);
1659 if should_skip {
1660 continue;
1661 }
1662 let mut state = self.state.lock();
1663
1664 let inode = state.get_and_increment_inode();
1665 let mtime = state.get_and_increment_mtime();
1666 state.write_path(&cur_path, |entry| {
1667 entry.or_insert_with(|| {
1668 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1669 Arc::new(Mutex::new(FakeFsEntry::Dir {
1670 inode,
1671 mtime,
1672 len: 0,
1673 entries: Default::default(),
1674 git_repo_state: None,
1675 }))
1676 });
1677 Ok(())
1678 })?
1679 }
1680
1681 self.state.lock().emit_event(created_dirs);
1682 Ok(())
1683 }
1684
1685 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1686 self.simulate_random_delay().await;
1687 let mut state = self.state.lock();
1688 let inode = state.get_and_increment_inode();
1689 let mtime = state.get_and_increment_mtime();
1690 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1691 inode,
1692 mtime,
1693 len: 0,
1694 content: Vec::new(),
1695 }));
1696 let mut kind = Some(PathEventKind::Created);
1697 state.write_path(path, |entry| {
1698 match entry {
1699 btree_map::Entry::Occupied(mut e) => {
1700 if options.overwrite {
1701 kind = Some(PathEventKind::Changed);
1702 *e.get_mut() = file;
1703 } else if !options.ignore_if_exists {
1704 return Err(anyhow!("path already exists: {}", path.display()));
1705 }
1706 }
1707 btree_map::Entry::Vacant(e) => {
1708 e.insert(file);
1709 }
1710 }
1711 Ok(())
1712 })?;
1713 state.emit_event([(path, kind)]);
1714 Ok(())
1715 }
1716
1717 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1718 let mut state = self.state.lock();
1719 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1720 state
1721 .write_path(path.as_ref(), move |e| match e {
1722 btree_map::Entry::Vacant(e) => {
1723 e.insert(file);
1724 Ok(())
1725 }
1726 btree_map::Entry::Occupied(mut e) => {
1727 *e.get_mut() = file;
1728 Ok(())
1729 }
1730 })
1731 .unwrap();
1732 state.emit_event([(path, None)]);
1733
1734 Ok(())
1735 }
1736
1737 async fn create_file_with(
1738 &self,
1739 path: &Path,
1740 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1741 ) -> Result<()> {
1742 let mut bytes = Vec::new();
1743 content.read_to_end(&mut bytes).await?;
1744 self.write_file_internal(path, bytes)?;
1745 Ok(())
1746 }
1747
1748 async fn extract_tar_file(
1749 &self,
1750 path: &Path,
1751 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1752 ) -> Result<()> {
1753 let mut entries = content.entries()?;
1754 while let Some(entry) = entries.next().await {
1755 let mut entry = entry?;
1756 if entry.header().entry_type().is_file() {
1757 let path = path.join(entry.path()?.as_ref());
1758 let mut bytes = Vec::new();
1759 entry.read_to_end(&mut bytes).await?;
1760 self.create_dir(path.parent().unwrap()).await?;
1761 self.write_file_internal(&path, bytes)?;
1762 }
1763 }
1764 Ok(())
1765 }
1766
1767 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1768 self.simulate_random_delay().await;
1769
1770 let old_path = normalize_path(old_path);
1771 let new_path = normalize_path(new_path);
1772
1773 let mut state = self.state.lock();
1774 let moved_entry = state.write_path(&old_path, |e| {
1775 if let btree_map::Entry::Occupied(e) = e {
1776 Ok(e.get().clone())
1777 } else {
1778 Err(anyhow!("path does not exist: {}", &old_path.display()))
1779 }
1780 })?;
1781
1782 let inode = match *moved_entry.lock() {
1783 FakeFsEntry::File { inode, .. } => inode,
1784 FakeFsEntry::Dir { inode, .. } => inode,
1785 _ => 0,
1786 };
1787
1788 state.moves.insert(inode, new_path.clone());
1789
1790 state.write_path(&new_path, |e| {
1791 match e {
1792 btree_map::Entry::Occupied(mut e) => {
1793 if options.overwrite {
1794 *e.get_mut() = moved_entry;
1795 } else if !options.ignore_if_exists {
1796 return Err(anyhow!("path already exists: {}", new_path.display()));
1797 }
1798 }
1799 btree_map::Entry::Vacant(e) => {
1800 e.insert(moved_entry);
1801 }
1802 }
1803 Ok(())
1804 })?;
1805
1806 state
1807 .write_path(&old_path, |e| {
1808 if let btree_map::Entry::Occupied(e) = e {
1809 Ok(e.remove())
1810 } else {
1811 unreachable!()
1812 }
1813 })
1814 .unwrap();
1815
1816 state.emit_event([
1817 (old_path, Some(PathEventKind::Removed)),
1818 (new_path, Some(PathEventKind::Created)),
1819 ]);
1820 Ok(())
1821 }
1822
1823 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1824 self.simulate_random_delay().await;
1825
1826 let source = normalize_path(source);
1827 let target = normalize_path(target);
1828 let mut state = self.state.lock();
1829 let mtime = state.get_and_increment_mtime();
1830 let inode = state.get_and_increment_inode();
1831 let source_entry = state.read_path(&source)?;
1832 let content = source_entry.lock().file_content(&source)?.clone();
1833 let mut kind = Some(PathEventKind::Created);
1834 state.write_path(&target, |e| match e {
1835 btree_map::Entry::Occupied(e) => {
1836 if options.overwrite {
1837 kind = Some(PathEventKind::Changed);
1838 Ok(Some(e.get().clone()))
1839 } else if !options.ignore_if_exists {
1840 return Err(anyhow!("{target:?} already exists"));
1841 } else {
1842 Ok(None)
1843 }
1844 }
1845 btree_map::Entry::Vacant(e) => Ok(Some(
1846 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1847 inode,
1848 mtime,
1849 len: content.len() as u64,
1850 content,
1851 })))
1852 .clone(),
1853 )),
1854 })?;
1855 state.emit_event([(target, kind)]);
1856 Ok(())
1857 }
1858
1859 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1860 self.simulate_random_delay().await;
1861
1862 let path = normalize_path(path);
1863 let parent_path = path
1864 .parent()
1865 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1866 let base_name = path.file_name().unwrap();
1867
1868 let mut state = self.state.lock();
1869 let parent_entry = state.read_path(parent_path)?;
1870 let mut parent_entry = parent_entry.lock();
1871 let entry = parent_entry
1872 .dir_entries(parent_path)?
1873 .entry(base_name.to_str().unwrap().into());
1874
1875 match entry {
1876 btree_map::Entry::Vacant(_) => {
1877 if !options.ignore_if_not_exists {
1878 return Err(anyhow!("{path:?} does not exist"));
1879 }
1880 }
1881 btree_map::Entry::Occupied(e) => {
1882 {
1883 let mut entry = e.get().lock();
1884 let children = entry.dir_entries(&path)?;
1885 if !options.recursive && !children.is_empty() {
1886 return Err(anyhow!("{path:?} is not empty"));
1887 }
1888 }
1889 e.remove();
1890 }
1891 }
1892 state.emit_event([(path, Some(PathEventKind::Removed))]);
1893 Ok(())
1894 }
1895
1896 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1897 self.simulate_random_delay().await;
1898
1899 let path = normalize_path(path);
1900 let parent_path = path
1901 .parent()
1902 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1903 let base_name = path.file_name().unwrap();
1904 let mut state = self.state.lock();
1905 let parent_entry = state.read_path(parent_path)?;
1906 let mut parent_entry = parent_entry.lock();
1907 let entry = parent_entry
1908 .dir_entries(parent_path)?
1909 .entry(base_name.to_str().unwrap().into());
1910 match entry {
1911 btree_map::Entry::Vacant(_) => {
1912 if !options.ignore_if_not_exists {
1913 return Err(anyhow!("{path:?} does not exist"));
1914 }
1915 }
1916 btree_map::Entry::Occupied(e) => {
1917 e.get().lock().file_content(&path)?;
1918 e.remove();
1919 }
1920 }
1921 state.emit_event([(path, Some(PathEventKind::Removed))]);
1922 Ok(())
1923 }
1924
1925 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
1926 let bytes = self.load_internal(path).await?;
1927 Ok(Box::new(io::Cursor::new(bytes)))
1928 }
1929
1930 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1931 self.simulate_random_delay().await;
1932 let state = self.state.lock();
1933 let entry = state.read_path(&path)?;
1934 let entry = entry.lock();
1935 let inode = match *entry {
1936 FakeFsEntry::File { inode, .. } => inode,
1937 FakeFsEntry::Dir { inode, .. } => inode,
1938 _ => unreachable!(),
1939 };
1940 Ok(Arc::new(FakeHandle { inode }))
1941 }
1942
1943 async fn load(&self, path: &Path) -> Result<String> {
1944 let content = self.load_internal(path).await?;
1945 Ok(String::from_utf8(content.clone())?)
1946 }
1947
1948 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1949 self.load_internal(path).await
1950 }
1951
1952 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1953 self.simulate_random_delay().await;
1954 let path = normalize_path(path.as_path());
1955 self.write_file_internal(path, data.into_bytes())?;
1956 Ok(())
1957 }
1958
1959 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1960 self.simulate_random_delay().await;
1961 let path = normalize_path(path);
1962 let content = chunks(text, line_ending).collect::<String>();
1963 if let Some(path) = path.parent() {
1964 self.create_dir(path).await?;
1965 }
1966 self.write_file_internal(path, content.into_bytes())?;
1967 Ok(())
1968 }
1969
1970 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1971 let path = normalize_path(path);
1972 self.simulate_random_delay().await;
1973 let state = self.state.lock();
1974 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1975 Ok(canonical_path)
1976 } else {
1977 Err(anyhow!("path does not exist: {}", path.display()))
1978 }
1979 }
1980
1981 async fn is_file(&self, path: &Path) -> bool {
1982 let path = normalize_path(path);
1983 self.simulate_random_delay().await;
1984 let state = self.state.lock();
1985 if let Some((entry, _)) = state.try_read_path(&path, true) {
1986 entry.lock().is_file()
1987 } else {
1988 false
1989 }
1990 }
1991
1992 async fn is_dir(&self, path: &Path) -> bool {
1993 self.metadata(path)
1994 .await
1995 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1996 }
1997
1998 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1999 self.simulate_random_delay().await;
2000 let path = normalize_path(path);
2001 let mut state = self.state.lock();
2002 state.metadata_call_count += 1;
2003 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
2004 let is_symlink = entry.lock().is_symlink();
2005 if is_symlink {
2006 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
2007 entry = e;
2008 } else {
2009 return Ok(None);
2010 }
2011 }
2012
2013 let entry = entry.lock();
2014 Ok(Some(match &*entry {
2015 FakeFsEntry::File {
2016 inode, mtime, len, ..
2017 } => Metadata {
2018 inode: *inode,
2019 mtime: *mtime,
2020 len: *len,
2021 is_dir: false,
2022 is_symlink,
2023 is_fifo: false,
2024 },
2025 FakeFsEntry::Dir {
2026 inode, mtime, len, ..
2027 } => Metadata {
2028 inode: *inode,
2029 mtime: *mtime,
2030 len: *len,
2031 is_dir: true,
2032 is_symlink,
2033 is_fifo: false,
2034 },
2035 FakeFsEntry::Symlink { .. } => unreachable!(),
2036 }))
2037 } else {
2038 Ok(None)
2039 }
2040 }
2041
2042 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2043 self.simulate_random_delay().await;
2044 let path = normalize_path(path);
2045 let state = self.state.lock();
2046 if let Some((entry, _)) = state.try_read_path(&path, false) {
2047 let entry = entry.lock();
2048 if let FakeFsEntry::Symlink { target } = &*entry {
2049 Ok(target.clone())
2050 } else {
2051 Err(anyhow!("not a symlink: {}", path.display()))
2052 }
2053 } else {
2054 Err(anyhow!("path does not exist: {}", path.display()))
2055 }
2056 }
2057
2058 async fn read_dir(
2059 &self,
2060 path: &Path,
2061 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2062 self.simulate_random_delay().await;
2063 let path = normalize_path(path);
2064 let mut state = self.state.lock();
2065 state.read_dir_call_count += 1;
2066 let entry = state.read_path(&path)?;
2067 let mut entry = entry.lock();
2068 let children = entry.dir_entries(&path)?;
2069 let paths = children
2070 .keys()
2071 .map(|file_name| Ok(path.join(file_name)))
2072 .collect::<Vec<_>>();
2073 Ok(Box::pin(futures::stream::iter(paths)))
2074 }
2075
2076 async fn watch(
2077 &self,
2078 path: &Path,
2079 _: Duration,
2080 ) -> (
2081 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2082 Arc<dyn Watcher>,
2083 ) {
2084 self.simulate_random_delay().await;
2085 let (tx, rx) = smol::channel::unbounded();
2086 self.state.lock().event_txs.push(tx);
2087 let path = path.to_path_buf();
2088 let executor = self.executor.clone();
2089 (
2090 Box::pin(futures::StreamExt::filter(rx, move |events| {
2091 let result = events
2092 .iter()
2093 .any(|evt_path| evt_path.path.starts_with(&path));
2094 let executor = executor.clone();
2095 async move {
2096 executor.simulate_random_delay().await;
2097 result
2098 }
2099 })),
2100 Arc::new(FakeWatcher {}),
2101 )
2102 }
2103
2104 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
2105 let state = self.state.lock();
2106 let entry = state.read_path(abs_dot_git).unwrap();
2107 let mut entry = entry.lock();
2108 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
2109 git_repo_state.get_or_insert_with(|| {
2110 Arc::new(Mutex::new(FakeGitRepositoryState::new(
2111 abs_dot_git.to_path_buf(),
2112 state.git_event_tx.clone(),
2113 )))
2114 });
2115 Some(Arc::new(fake_git_repo::FakeGitRepository {
2116 fs: self.this.upgrade().unwrap(),
2117 executor: self.executor.clone(),
2118 dot_git_path: abs_dot_git.to_path_buf(),
2119 }))
2120 } else {
2121 None
2122 }
2123 }
2124
2125 fn git_init(
2126 &self,
2127 abs_work_directory_path: &Path,
2128 _fallback_branch_name: String,
2129 ) -> Result<()> {
2130 smol::block_on(self.create_dir(&abs_work_directory_path.join(".git")))
2131 }
2132
2133 fn is_fake(&self) -> bool {
2134 true
2135 }
2136
2137 async fn is_case_sensitive(&self) -> Result<bool> {
2138 Ok(true)
2139 }
2140
2141 #[cfg(any(test, feature = "test-support"))]
2142 fn as_fake(&self) -> Arc<FakeFs> {
2143 self.this.upgrade().unwrap()
2144 }
2145
2146 fn home_dir(&self) -> Option<PathBuf> {
2147 self.state.lock().home_dir.clone()
2148 }
2149}
2150
2151fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2152 rope.chunks().flat_map(move |chunk| {
2153 let mut newline = false;
2154 chunk.split('\n').flat_map(move |line| {
2155 let ending = if newline {
2156 Some(line_ending.as_str())
2157 } else {
2158 None
2159 };
2160 newline = true;
2161 ending.into_iter().chain([line])
2162 })
2163 })
2164}
2165
2166pub fn normalize_path(path: &Path) -> PathBuf {
2167 let mut components = path.components().peekable();
2168 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2169 components.next();
2170 PathBuf::from(c.as_os_str())
2171 } else {
2172 PathBuf::new()
2173 };
2174
2175 for component in components {
2176 match component {
2177 Component::Prefix(..) => unreachable!(),
2178 Component::RootDir => {
2179 ret.push(component.as_os_str());
2180 }
2181 Component::CurDir => {}
2182 Component::ParentDir => {
2183 ret.pop();
2184 }
2185 Component::Normal(c) => {
2186 ret.push(c);
2187 }
2188 }
2189 }
2190 ret
2191}
2192
2193pub async fn copy_recursive<'a>(
2194 fs: &'a dyn Fs,
2195 source: &'a Path,
2196 target: &'a Path,
2197 options: CopyOptions,
2198) -> Result<()> {
2199 for (is_dir, item) in read_dir_items(fs, source).await? {
2200 let Ok(item_relative_path) = item.strip_prefix(source) else {
2201 continue;
2202 };
2203 let target_item = if item_relative_path == Path::new("") {
2204 target.to_path_buf()
2205 } else {
2206 target.join(item_relative_path)
2207 };
2208 if is_dir {
2209 if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2210 if options.ignore_if_exists {
2211 continue;
2212 } else {
2213 return Err(anyhow!("{target_item:?} already exists"));
2214 }
2215 }
2216 let _ = fs
2217 .remove_dir(
2218 &target_item,
2219 RemoveOptions {
2220 recursive: true,
2221 ignore_if_not_exists: true,
2222 },
2223 )
2224 .await;
2225 fs.create_dir(&target_item).await?;
2226 } else {
2227 fs.copy_file(&item, &target_item, options).await?;
2228 }
2229 }
2230 Ok(())
2231}
2232
2233async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(bool, PathBuf)>> {
2234 let mut items = Vec::new();
2235 read_recursive(fs, source, &mut items).await?;
2236 Ok(items)
2237}
2238
2239fn read_recursive<'a>(
2240 fs: &'a dyn Fs,
2241 source: &'a Path,
2242 output: &'a mut Vec<(bool, PathBuf)>,
2243) -> BoxFuture<'a, Result<()>> {
2244 use futures::future::FutureExt;
2245
2246 async move {
2247 let metadata = fs
2248 .metadata(source)
2249 .await?
2250 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2251
2252 if metadata.is_dir {
2253 output.push((true, source.to_path_buf()));
2254 let mut children = fs.read_dir(source).await?;
2255 while let Some(child_path) = children.next().await {
2256 if let Ok(child_path) = child_path {
2257 read_recursive(fs, &child_path, output).await?;
2258 }
2259 }
2260 } else {
2261 output.push((false, source.to_path_buf()));
2262 }
2263 Ok(())
2264 }
2265 .boxed()
2266}
2267
2268// todo(windows)
2269// can we get file id not open the file twice?
2270// https://github.com/rust-lang/rust/issues/63010
2271#[cfg(target_os = "windows")]
2272async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2273 use std::os::windows::io::AsRawHandle;
2274
2275 use smol::fs::windows::OpenOptionsExt;
2276 use windows::Win32::{
2277 Foundation::HANDLE,
2278 Storage::FileSystem::{
2279 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2280 },
2281 };
2282
2283 let file = smol::fs::OpenOptions::new()
2284 .read(true)
2285 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2286 .open(path)
2287 .await?;
2288
2289 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2290 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2291 // This function supports Windows XP+
2292 smol::unblock(move || {
2293 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2294
2295 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2296 })
2297 .await
2298}
2299
2300#[cfg(test)]
2301mod tests {
2302 use super::*;
2303 use gpui::BackgroundExecutor;
2304 use serde_json::json;
2305 use util::path;
2306
2307 #[gpui::test]
2308 async fn test_fake_fs(executor: BackgroundExecutor) {
2309 let fs = FakeFs::new(executor.clone());
2310 fs.insert_tree(
2311 path!("/root"),
2312 json!({
2313 "dir1": {
2314 "a": "A",
2315 "b": "B"
2316 },
2317 "dir2": {
2318 "c": "C",
2319 "dir3": {
2320 "d": "D"
2321 }
2322 }
2323 }),
2324 )
2325 .await;
2326
2327 assert_eq!(
2328 fs.files(),
2329 vec![
2330 PathBuf::from(path!("/root/dir1/a")),
2331 PathBuf::from(path!("/root/dir1/b")),
2332 PathBuf::from(path!("/root/dir2/c")),
2333 PathBuf::from(path!("/root/dir2/dir3/d")),
2334 ]
2335 );
2336
2337 fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2338 .await
2339 .unwrap();
2340
2341 assert_eq!(
2342 fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2343 .await
2344 .unwrap(),
2345 PathBuf::from(path!("/root/dir2/dir3")),
2346 );
2347 assert_eq!(
2348 fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2349 .await
2350 .unwrap(),
2351 PathBuf::from(path!("/root/dir2/dir3/d")),
2352 );
2353 assert_eq!(
2354 fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2355 .await
2356 .unwrap(),
2357 "D",
2358 );
2359 }
2360
2361 #[gpui::test]
2362 async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2363 let fs = FakeFs::new(executor.clone());
2364 fs.insert_tree(
2365 path!("/outer"),
2366 json!({
2367 "a": "A",
2368 "b": "B",
2369 "inner": {}
2370 }),
2371 )
2372 .await;
2373
2374 assert_eq!(
2375 fs.files(),
2376 vec![
2377 PathBuf::from(path!("/outer/a")),
2378 PathBuf::from(path!("/outer/b")),
2379 ]
2380 );
2381
2382 let source = Path::new(path!("/outer/a"));
2383 let target = Path::new(path!("/outer/a copy"));
2384 copy_recursive(fs.as_ref(), source, target, Default::default())
2385 .await
2386 .unwrap();
2387
2388 assert_eq!(
2389 fs.files(),
2390 vec![
2391 PathBuf::from(path!("/outer/a")),
2392 PathBuf::from(path!("/outer/a copy")),
2393 PathBuf::from(path!("/outer/b")),
2394 ]
2395 );
2396
2397 let source = Path::new(path!("/outer/a"));
2398 let target = Path::new(path!("/outer/inner/a copy"));
2399 copy_recursive(fs.as_ref(), source, target, Default::default())
2400 .await
2401 .unwrap();
2402
2403 assert_eq!(
2404 fs.files(),
2405 vec![
2406 PathBuf::from(path!("/outer/a")),
2407 PathBuf::from(path!("/outer/a copy")),
2408 PathBuf::from(path!("/outer/b")),
2409 PathBuf::from(path!("/outer/inner/a copy")),
2410 ]
2411 );
2412 }
2413
2414 #[gpui::test]
2415 async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2416 let fs = FakeFs::new(executor.clone());
2417 fs.insert_tree(
2418 path!("/outer"),
2419 json!({
2420 "a": "A",
2421 "empty": {},
2422 "non-empty": {
2423 "b": "B",
2424 }
2425 }),
2426 )
2427 .await;
2428
2429 assert_eq!(
2430 fs.files(),
2431 vec![
2432 PathBuf::from(path!("/outer/a")),
2433 PathBuf::from(path!("/outer/non-empty/b")),
2434 ]
2435 );
2436 assert_eq!(
2437 fs.directories(false),
2438 vec![
2439 PathBuf::from(path!("/")),
2440 PathBuf::from(path!("/outer")),
2441 PathBuf::from(path!("/outer/empty")),
2442 PathBuf::from(path!("/outer/non-empty")),
2443 ]
2444 );
2445
2446 let source = Path::new(path!("/outer/empty"));
2447 let target = Path::new(path!("/outer/empty copy"));
2448 copy_recursive(fs.as_ref(), source, target, Default::default())
2449 .await
2450 .unwrap();
2451
2452 assert_eq!(
2453 fs.files(),
2454 vec![
2455 PathBuf::from(path!("/outer/a")),
2456 PathBuf::from(path!("/outer/non-empty/b")),
2457 ]
2458 );
2459 assert_eq!(
2460 fs.directories(false),
2461 vec![
2462 PathBuf::from(path!("/")),
2463 PathBuf::from(path!("/outer")),
2464 PathBuf::from(path!("/outer/empty")),
2465 PathBuf::from(path!("/outer/empty copy")),
2466 PathBuf::from(path!("/outer/non-empty")),
2467 ]
2468 );
2469
2470 let source = Path::new(path!("/outer/non-empty"));
2471 let target = Path::new(path!("/outer/non-empty copy"));
2472 copy_recursive(fs.as_ref(), source, target, Default::default())
2473 .await
2474 .unwrap();
2475
2476 assert_eq!(
2477 fs.files(),
2478 vec![
2479 PathBuf::from(path!("/outer/a")),
2480 PathBuf::from(path!("/outer/non-empty/b")),
2481 PathBuf::from(path!("/outer/non-empty copy/b")),
2482 ]
2483 );
2484 assert_eq!(
2485 fs.directories(false),
2486 vec![
2487 PathBuf::from(path!("/")),
2488 PathBuf::from(path!("/outer")),
2489 PathBuf::from(path!("/outer/empty")),
2490 PathBuf::from(path!("/outer/empty copy")),
2491 PathBuf::from(path!("/outer/non-empty")),
2492 PathBuf::from(path!("/outer/non-empty copy")),
2493 ]
2494 );
2495 }
2496
2497 #[gpui::test]
2498 async fn test_copy_recursive(executor: BackgroundExecutor) {
2499 let fs = FakeFs::new(executor.clone());
2500 fs.insert_tree(
2501 path!("/outer"),
2502 json!({
2503 "inner1": {
2504 "a": "A",
2505 "b": "B",
2506 "inner3": {
2507 "d": "D",
2508 },
2509 "inner4": {}
2510 },
2511 "inner2": {
2512 "c": "C",
2513 }
2514 }),
2515 )
2516 .await;
2517
2518 assert_eq!(
2519 fs.files(),
2520 vec![
2521 PathBuf::from(path!("/outer/inner1/a")),
2522 PathBuf::from(path!("/outer/inner1/b")),
2523 PathBuf::from(path!("/outer/inner2/c")),
2524 PathBuf::from(path!("/outer/inner1/inner3/d")),
2525 ]
2526 );
2527 assert_eq!(
2528 fs.directories(false),
2529 vec![
2530 PathBuf::from(path!("/")),
2531 PathBuf::from(path!("/outer")),
2532 PathBuf::from(path!("/outer/inner1")),
2533 PathBuf::from(path!("/outer/inner2")),
2534 PathBuf::from(path!("/outer/inner1/inner3")),
2535 PathBuf::from(path!("/outer/inner1/inner4")),
2536 ]
2537 );
2538
2539 let source = Path::new(path!("/outer"));
2540 let target = Path::new(path!("/outer/inner1/outer"));
2541 copy_recursive(fs.as_ref(), source, target, Default::default())
2542 .await
2543 .unwrap();
2544
2545 assert_eq!(
2546 fs.files(),
2547 vec![
2548 PathBuf::from(path!("/outer/inner1/a")),
2549 PathBuf::from(path!("/outer/inner1/b")),
2550 PathBuf::from(path!("/outer/inner2/c")),
2551 PathBuf::from(path!("/outer/inner1/inner3/d")),
2552 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2553 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2554 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2555 PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2556 ]
2557 );
2558 assert_eq!(
2559 fs.directories(false),
2560 vec![
2561 PathBuf::from(path!("/")),
2562 PathBuf::from(path!("/outer")),
2563 PathBuf::from(path!("/outer/inner1")),
2564 PathBuf::from(path!("/outer/inner2")),
2565 PathBuf::from(path!("/outer/inner1/inner3")),
2566 PathBuf::from(path!("/outer/inner1/inner4")),
2567 PathBuf::from(path!("/outer/inner1/outer")),
2568 PathBuf::from(path!("/outer/inner1/outer/inner1")),
2569 PathBuf::from(path!("/outer/inner1/outer/inner2")),
2570 PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
2571 PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
2572 ]
2573 );
2574 }
2575
2576 #[gpui::test]
2577 async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2578 let fs = FakeFs::new(executor.clone());
2579 fs.insert_tree(
2580 path!("/outer"),
2581 json!({
2582 "inner1": {
2583 "a": "A",
2584 "b": "B",
2585 "outer": {
2586 "inner1": {
2587 "a": "B"
2588 }
2589 }
2590 },
2591 "inner2": {
2592 "c": "C",
2593 }
2594 }),
2595 )
2596 .await;
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/outer/inner1/a")),
2605 ]
2606 );
2607 assert_eq!(
2608 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2609 .await
2610 .unwrap(),
2611 "B",
2612 );
2613
2614 let source = Path::new(path!("/outer"));
2615 let target = Path::new(path!("/outer/inner1/outer"));
2616 copy_recursive(
2617 fs.as_ref(),
2618 source,
2619 target,
2620 CopyOptions {
2621 overwrite: true,
2622 ..Default::default()
2623 },
2624 )
2625 .await
2626 .unwrap();
2627
2628 assert_eq!(
2629 fs.files(),
2630 vec![
2631 PathBuf::from(path!("/outer/inner1/a")),
2632 PathBuf::from(path!("/outer/inner1/b")),
2633 PathBuf::from(path!("/outer/inner2/c")),
2634 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2635 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2636 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2637 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2638 ]
2639 );
2640 assert_eq!(
2641 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2642 .await
2643 .unwrap(),
2644 "A"
2645 );
2646 }
2647
2648 #[gpui::test]
2649 async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
2650 let fs = FakeFs::new(executor.clone());
2651 fs.insert_tree(
2652 path!("/outer"),
2653 json!({
2654 "inner1": {
2655 "a": "A",
2656 "b": "B",
2657 "outer": {
2658 "inner1": {
2659 "a": "B"
2660 }
2661 }
2662 },
2663 "inner2": {
2664 "c": "C",
2665 }
2666 }),
2667 )
2668 .await;
2669
2670 assert_eq!(
2671 fs.files(),
2672 vec![
2673 PathBuf::from(path!("/outer/inner1/a")),
2674 PathBuf::from(path!("/outer/inner1/b")),
2675 PathBuf::from(path!("/outer/inner2/c")),
2676 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2677 ]
2678 );
2679 assert_eq!(
2680 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2681 .await
2682 .unwrap(),
2683 "B",
2684 );
2685
2686 let source = Path::new(path!("/outer"));
2687 let target = Path::new(path!("/outer/inner1/outer"));
2688 copy_recursive(
2689 fs.as_ref(),
2690 source,
2691 target,
2692 CopyOptions {
2693 ignore_if_exists: true,
2694 ..Default::default()
2695 },
2696 )
2697 .await
2698 .unwrap();
2699
2700 assert_eq!(
2701 fs.files(),
2702 vec![
2703 PathBuf::from(path!("/outer/inner1/a")),
2704 PathBuf::from(path!("/outer/inner1/b")),
2705 PathBuf::from(path!("/outer/inner2/c")),
2706 PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2707 PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2708 PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2709 PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2710 ]
2711 );
2712 assert_eq!(
2713 fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2714 .await
2715 .unwrap(),
2716 "B"
2717 );
2718 }
2719}