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