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