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(mut target) = self.read_link(&path).await.ok() {
724 // Check if symlink target is relative path, if so make it absolute
725 if target.is_relative() {
726 if let Some(parent) = path.parent() {
727 target = parent.join(target);
728 if let Ok(canonical) = self.canonicalize(&target).await {
729 target = canonical;
730 }
731 }
732 }
733 watcher.add(&target).ok();
734 if let Some(parent) = target.parent() {
735 watcher.add(parent).log_err();
736 }
737 }
738
739 (
740 Box::pin(rx.filter_map({
741 let watcher = watcher.clone();
742 move |_| {
743 let _ = watcher.clone();
744 let pending_paths = pending_paths.clone();
745 async move {
746 smol::Timer::after(latency).await;
747 let paths = std::mem::take(&mut *pending_paths.lock());
748 (!paths.is_empty()).then_some(paths)
749 }
750 }
751 })),
752 watcher,
753 )
754 }
755
756 #[cfg(target_os = "windows")]
757 async fn watch(
758 &self,
759 path: &Path,
760 _latency: Duration,
761 ) -> (
762 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
763 Arc<dyn Watcher>,
764 ) {
765 use notify::{EventKind, Watcher};
766
767 let (tx, rx) = smol::channel::unbounded();
768
769 let mut file_watcher = notify::recommended_watcher({
770 let tx = tx.clone();
771 move |event: Result<notify::Event, _>| {
772 if let Some(event) = event.log_err() {
773 let kind = match event.kind {
774 EventKind::Create(_) => Some(PathEventKind::Created),
775 EventKind::Modify(_) => Some(PathEventKind::Changed),
776 EventKind::Remove(_) => Some(PathEventKind::Removed),
777 _ => None,
778 };
779
780 tx.try_send(
781 event
782 .paths
783 .into_iter()
784 .map(|path| PathEvent { path, kind })
785 .collect::<Vec<_>>(),
786 )
787 .ok();
788 }
789 }
790 })
791 .expect("Could not start file watcher");
792
793 file_watcher
794 .watch(path, notify::RecursiveMode::Recursive)
795 .log_err();
796
797 (
798 Box::pin(rx.chain(futures::stream::once(async move {
799 drop(file_watcher);
800 vec![]
801 }))),
802 Arc::new(RealWatcher {}),
803 )
804 }
805
806 fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
807 // with libgit2, we can open git repo from an existing work dir
808 // https://libgit2.org/docs/reference/main/repository/git_repository_open.html
809 let workdir_root = dotgit_path.parent()?;
810 let repo = git2::Repository::open(workdir_root).log_err()?;
811 Some(Arc::new(RealGitRepository::new(
812 repo,
813 self.git_binary_path.clone(),
814 self.git_hosting_provider_registry.clone(),
815 )))
816 }
817
818 fn is_fake(&self) -> bool {
819 false
820 }
821
822 /// Checks whether the file system is case sensitive by attempting to create two files
823 /// that have the same name except for the casing.
824 ///
825 /// It creates both files in a temporary directory it removes at the end.
826 async fn is_case_sensitive(&self) -> Result<bool> {
827 let temp_dir = TempDir::new()?;
828 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
829 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
830
831 let create_opts = CreateOptions {
832 overwrite: false,
833 ignore_if_exists: false,
834 };
835
836 // Create file1
837 self.create_file(&test_file_1, create_opts).await?;
838
839 // Now check whether it's possible to create file2
840 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
841 Ok(_) => Ok(true),
842 Err(e) => {
843 if let Some(io_error) = e.downcast_ref::<io::Error>() {
844 if io_error.kind() == io::ErrorKind::AlreadyExists {
845 Ok(false)
846 } else {
847 Err(e)
848 }
849 } else {
850 Err(e)
851 }
852 }
853 };
854
855 temp_dir.close()?;
856 case_sensitive
857 }
858}
859
860#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
861impl Watcher for RealWatcher {
862 fn add(&self, _: &Path) -> Result<()> {
863 Ok(())
864 }
865
866 fn remove(&self, _: &Path) -> Result<()> {
867 Ok(())
868 }
869}
870
871#[cfg(any(test, feature = "test-support"))]
872pub struct FakeFs {
873 this: std::sync::Weak<Self>,
874 // Use an unfair lock to ensure tests are deterministic.
875 state: Mutex<FakeFsState>,
876 executor: gpui::BackgroundExecutor,
877}
878
879#[cfg(any(test, feature = "test-support"))]
880struct FakeFsState {
881 root: Arc<Mutex<FakeFsEntry>>,
882 next_inode: u64,
883 next_mtime: SystemTime,
884 git_event_tx: smol::channel::Sender<PathBuf>,
885 event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
886 events_paused: bool,
887 buffered_events: Vec<PathEvent>,
888 metadata_call_count: usize,
889 read_dir_call_count: usize,
890 moves: std::collections::HashMap<u64, PathBuf>,
891}
892
893#[cfg(any(test, feature = "test-support"))]
894#[derive(Debug)]
895enum FakeFsEntry {
896 File {
897 inode: u64,
898 mtime: MTime,
899 len: u64,
900 content: Vec<u8>,
901 },
902 Dir {
903 inode: u64,
904 mtime: MTime,
905 len: u64,
906 entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
907 git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
908 },
909 Symlink {
910 target: PathBuf,
911 },
912}
913
914#[cfg(any(test, feature = "test-support"))]
915impl FakeFsState {
916 fn get_and_increment_mtime(&mut self) -> MTime {
917 let mtime = self.next_mtime;
918 self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
919 MTime(mtime)
920 }
921
922 fn get_and_increment_inode(&mut self) -> u64 {
923 let inode = self.next_inode;
924 self.next_inode += 1;
925 inode
926 }
927
928 fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
929 Ok(self
930 .try_read_path(target, true)
931 .ok_or_else(|| {
932 anyhow!(io::Error::new(
933 io::ErrorKind::NotFound,
934 format!("not found: {}", target.display())
935 ))
936 })?
937 .0)
938 }
939
940 fn try_read_path(
941 &self,
942 target: &Path,
943 follow_symlink: bool,
944 ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
945 let mut path = target.to_path_buf();
946 let mut canonical_path = PathBuf::new();
947 let mut entry_stack = Vec::new();
948 'outer: loop {
949 let mut path_components = path.components().peekable();
950 let mut prefix = None;
951 while let Some(component) = path_components.next() {
952 match component {
953 Component::Prefix(prefix_component) => prefix = Some(prefix_component),
954 Component::RootDir => {
955 entry_stack.clear();
956 entry_stack.push(self.root.clone());
957 canonical_path.clear();
958 match prefix {
959 Some(prefix_component) => {
960 canonical_path = PathBuf::from(prefix_component.as_os_str());
961 // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
962 canonical_path.push(std::path::MAIN_SEPARATOR_STR);
963 }
964 None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
965 }
966 }
967 Component::CurDir => {}
968 Component::ParentDir => {
969 entry_stack.pop()?;
970 canonical_path.pop();
971 }
972 Component::Normal(name) => {
973 let current_entry = entry_stack.last().cloned()?;
974 let current_entry = current_entry.lock();
975 if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
976 let entry = entries.get(name.to_str().unwrap()).cloned()?;
977 if path_components.peek().is_some() || follow_symlink {
978 let entry = entry.lock();
979 if let FakeFsEntry::Symlink { target, .. } = &*entry {
980 let mut target = target.clone();
981 target.extend(path_components);
982 path = target;
983 continue 'outer;
984 }
985 }
986 entry_stack.push(entry.clone());
987 canonical_path = canonical_path.join(name);
988 } else {
989 return None;
990 }
991 }
992 }
993 }
994 break;
995 }
996 Some((entry_stack.pop()?, canonical_path))
997 }
998
999 fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
1000 where
1001 Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
1002 {
1003 let path = normalize_path(path);
1004 let filename = path
1005 .file_name()
1006 .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
1007 let parent_path = path.parent().unwrap();
1008
1009 let parent = self.read_path(parent_path)?;
1010 let mut parent = parent.lock();
1011 let new_entry = parent
1012 .dir_entries(parent_path)?
1013 .entry(filename.to_str().unwrap().into());
1014 callback(new_entry)
1015 }
1016
1017 fn emit_event<I, T>(&mut self, paths: I)
1018 where
1019 I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1020 T: Into<PathBuf>,
1021 {
1022 self.buffered_events
1023 .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1024 path: path.into(),
1025 kind,
1026 }));
1027
1028 if !self.events_paused {
1029 self.flush_events(self.buffered_events.len());
1030 }
1031 }
1032
1033 fn flush_events(&mut self, mut count: usize) {
1034 count = count.min(self.buffered_events.len());
1035 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1036 self.event_txs.retain(|tx| {
1037 let _ = tx.try_send(events.clone());
1038 !tx.is_closed()
1039 });
1040 }
1041}
1042
1043#[cfg(any(test, feature = "test-support"))]
1044pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1045 std::sync::LazyLock::new(|| OsStr::new(".git"));
1046
1047#[cfg(any(test, feature = "test-support"))]
1048impl FakeFs {
1049 /// We need to use something large enough for Windows and Unix to consider this a new file.
1050 /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1051 const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1052
1053 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1054 let (tx, mut rx) = smol::channel::bounded::<PathBuf>(10);
1055
1056 let this = Arc::new_cyclic(|this| Self {
1057 this: this.clone(),
1058 executor: executor.clone(),
1059 state: Mutex::new(FakeFsState {
1060 root: Arc::new(Mutex::new(FakeFsEntry::Dir {
1061 inode: 0,
1062 mtime: MTime(UNIX_EPOCH),
1063 len: 0,
1064 entries: Default::default(),
1065 git_repo_state: None,
1066 })),
1067 git_event_tx: tx,
1068 next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1069 next_inode: 1,
1070 event_txs: Default::default(),
1071 buffered_events: Vec::new(),
1072 events_paused: false,
1073 read_dir_call_count: 0,
1074 metadata_call_count: 0,
1075 moves: Default::default(),
1076 }),
1077 });
1078
1079 executor.spawn({
1080 let this = this.clone();
1081 async move {
1082 while let Some(git_event) = rx.next().await {
1083 if let Some(mut state) = this.state.try_lock() {
1084 state.emit_event([(git_event, None)]);
1085 } else {
1086 panic!("Failed to lock file system state, this execution would have caused a test hang");
1087 }
1088 }
1089 }
1090 }).detach();
1091
1092 this
1093 }
1094
1095 pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1096 let mut state = self.state.lock();
1097 state.next_mtime = next_mtime;
1098 }
1099
1100 pub fn get_and_increment_mtime(&self) -> MTime {
1101 let mut state = self.state.lock();
1102 state.get_and_increment_mtime()
1103 }
1104
1105 pub async fn touch_path(&self, path: impl AsRef<Path>) {
1106 let mut state = self.state.lock();
1107 let path = path.as_ref();
1108 let new_mtime = state.get_and_increment_mtime();
1109 let new_inode = state.get_and_increment_inode();
1110 state
1111 .write_path(path, move |entry| {
1112 match entry {
1113 btree_map::Entry::Vacant(e) => {
1114 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1115 inode: new_inode,
1116 mtime: new_mtime,
1117 content: Vec::new(),
1118 len: 0,
1119 })));
1120 }
1121 btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1122 FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1123 FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1124 FakeFsEntry::Symlink { .. } => {}
1125 },
1126 }
1127 Ok(())
1128 })
1129 .unwrap();
1130 state.emit_event([(path.to_path_buf(), None)]);
1131 }
1132
1133 pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1134 self.write_file_internal(path, content).unwrap()
1135 }
1136
1137 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1138 let mut state = self.state.lock();
1139 let path = path.as_ref();
1140 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1141 state
1142 .write_path(path.as_ref(), move |e| match e {
1143 btree_map::Entry::Vacant(e) => {
1144 e.insert(file);
1145 Ok(())
1146 }
1147 btree_map::Entry::Occupied(mut e) => {
1148 *e.get_mut() = file;
1149 Ok(())
1150 }
1151 })
1152 .unwrap();
1153 state.emit_event([(path, None)]);
1154 }
1155
1156 fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1157 let mut state = self.state.lock();
1158 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1159 inode: state.get_and_increment_inode(),
1160 mtime: state.get_and_increment_mtime(),
1161 len: content.len() as u64,
1162 content,
1163 }));
1164 let mut kind = None;
1165 state.write_path(path.as_ref(), {
1166 let kind = &mut kind;
1167 move |entry| {
1168 match entry {
1169 btree_map::Entry::Vacant(e) => {
1170 *kind = Some(PathEventKind::Created);
1171 e.insert(file);
1172 }
1173 btree_map::Entry::Occupied(mut e) => {
1174 *kind = Some(PathEventKind::Changed);
1175 *e.get_mut() = file;
1176 }
1177 }
1178 Ok(())
1179 }
1180 })?;
1181 state.emit_event([(path.as_ref(), kind)]);
1182 Ok(())
1183 }
1184
1185 pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1186 let path = path.as_ref();
1187 let path = normalize_path(path);
1188 let state = self.state.lock();
1189 let entry = state.read_path(&path)?;
1190 let entry = entry.lock();
1191 entry.file_content(&path).cloned()
1192 }
1193
1194 async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1195 let path = path.as_ref();
1196 let path = normalize_path(path);
1197 self.simulate_random_delay().await;
1198 let state = self.state.lock();
1199 let entry = state.read_path(&path)?;
1200 let entry = entry.lock();
1201 entry.file_content(&path).cloned()
1202 }
1203
1204 pub fn pause_events(&self) {
1205 self.state.lock().events_paused = true;
1206 }
1207
1208 pub fn buffered_event_count(&self) -> usize {
1209 self.state.lock().buffered_events.len()
1210 }
1211
1212 pub fn flush_events(&self, count: usize) {
1213 self.state.lock().flush_events(count);
1214 }
1215
1216 #[must_use]
1217 pub fn insert_tree<'a>(
1218 &'a self,
1219 path: impl 'a + AsRef<Path> + Send,
1220 tree: serde_json::Value,
1221 ) -> futures::future::BoxFuture<'a, ()> {
1222 use futures::FutureExt as _;
1223 use serde_json::Value::*;
1224
1225 async move {
1226 let path = path.as_ref();
1227
1228 match tree {
1229 Object(map) => {
1230 self.create_dir(path).await.unwrap();
1231 for (name, contents) in map {
1232 let mut path = PathBuf::from(path);
1233 path.push(name);
1234 self.insert_tree(&path, contents).await;
1235 }
1236 }
1237 Null => {
1238 self.create_dir(path).await.unwrap();
1239 }
1240 String(contents) => {
1241 self.insert_file(&path, contents.into_bytes()).await;
1242 }
1243 _ => {
1244 panic!("JSON object must contain only objects, strings, or null");
1245 }
1246 }
1247 }
1248 .boxed()
1249 }
1250
1251 pub fn insert_tree_from_real_fs<'a>(
1252 &'a self,
1253 path: impl 'a + AsRef<Path> + Send,
1254 src_path: impl 'a + AsRef<Path> + Send,
1255 ) -> futures::future::BoxFuture<'a, ()> {
1256 use futures::FutureExt as _;
1257
1258 async move {
1259 let path = path.as_ref();
1260 if std::fs::metadata(&src_path).unwrap().is_file() {
1261 let contents = std::fs::read(src_path).unwrap();
1262 self.insert_file(path, contents).await;
1263 } else {
1264 self.create_dir(path).await.unwrap();
1265 for entry in std::fs::read_dir(&src_path).unwrap() {
1266 let entry = entry.unwrap();
1267 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1268 .await;
1269 }
1270 }
1271 }
1272 .boxed()
1273 }
1274
1275 pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1276 where
1277 F: FnOnce(&mut FakeGitRepositoryState),
1278 {
1279 let mut state = self.state.lock();
1280 let entry = state.read_path(dot_git).unwrap();
1281 let mut entry = entry.lock();
1282
1283 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1284 let repo_state = git_repo_state.get_or_insert_with(|| {
1285 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1286 dot_git.to_path_buf(),
1287 state.git_event_tx.clone(),
1288 )))
1289 });
1290 let mut repo_state = repo_state.lock();
1291
1292 f(&mut repo_state);
1293
1294 if emit_git_event {
1295 state.emit_event([(dot_git, None)]);
1296 }
1297 } else {
1298 panic!("not a directory");
1299 }
1300 }
1301
1302 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1303 self.with_git_state(dot_git, true, |state| {
1304 let branch = branch.map(Into::into);
1305 state.branches.extend(branch.clone());
1306 state.current_branch_name = branch.map(Into::into)
1307 })
1308 }
1309
1310 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1311 self.with_git_state(dot_git, true, |state| {
1312 if let Some(first) = branches.first() {
1313 if state.current_branch_name.is_none() {
1314 state.current_branch_name = Some(first.to_string())
1315 }
1316 }
1317 state
1318 .branches
1319 .extend(branches.iter().map(ToString::to_string));
1320 })
1321 }
1322
1323 pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1324 self.with_git_state(dot_git, true, |state| {
1325 state.index_contents.clear();
1326 state.index_contents.extend(
1327 head_state
1328 .iter()
1329 .map(|(path, content)| (path.to_path_buf(), content.clone())),
1330 );
1331 });
1332 }
1333
1334 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1335 self.with_git_state(dot_git, true, |state| {
1336 state.blames.clear();
1337 state.blames.extend(
1338 blames
1339 .into_iter()
1340 .map(|(path, blame)| (path.to_path_buf(), blame)),
1341 );
1342 });
1343 }
1344
1345 pub fn set_status_for_repo_via_working_copy_change(
1346 &self,
1347 dot_git: &Path,
1348 statuses: &[(&Path, GitFileStatus)],
1349 ) {
1350 self.with_git_state(dot_git, false, |state| {
1351 state.worktree_statuses.clear();
1352 state.worktree_statuses.extend(
1353 statuses
1354 .iter()
1355 .map(|(path, content)| ((**path).into(), *content)),
1356 );
1357 });
1358 self.state.lock().emit_event(
1359 statuses
1360 .iter()
1361 .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1362 );
1363 }
1364
1365 pub fn set_status_for_repo_via_git_operation(
1366 &self,
1367 dot_git: &Path,
1368 statuses: &[(&Path, GitFileStatus)],
1369 ) {
1370 self.with_git_state(dot_git, true, |state| {
1371 state.worktree_statuses.clear();
1372 state.worktree_statuses.extend(
1373 statuses
1374 .iter()
1375 .map(|(path, content)| ((**path).into(), *content)),
1376 );
1377 });
1378 }
1379
1380 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1381 let mut result = Vec::new();
1382 let mut queue = collections::VecDeque::new();
1383 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1384 while let Some((path, entry)) = queue.pop_front() {
1385 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1386 for (name, entry) in entries {
1387 queue.push_back((path.join(name), entry.clone()));
1388 }
1389 }
1390 if include_dot_git
1391 || !path
1392 .components()
1393 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1394 {
1395 result.push(path);
1396 }
1397 }
1398 result
1399 }
1400
1401 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1402 let mut result = Vec::new();
1403 let mut queue = collections::VecDeque::new();
1404 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1405 while let Some((path, entry)) = queue.pop_front() {
1406 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1407 for (name, entry) in entries {
1408 queue.push_back((path.join(name), entry.clone()));
1409 }
1410 if include_dot_git
1411 || !path
1412 .components()
1413 .any(|component| component.as_os_str() == *FS_DOT_GIT)
1414 {
1415 result.push(path);
1416 }
1417 }
1418 }
1419 result
1420 }
1421
1422 pub fn files(&self) -> Vec<PathBuf> {
1423 let mut result = Vec::new();
1424 let mut queue = collections::VecDeque::new();
1425 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1426 while let Some((path, entry)) = queue.pop_front() {
1427 let e = entry.lock();
1428 match &*e {
1429 FakeFsEntry::File { .. } => result.push(path),
1430 FakeFsEntry::Dir { entries, .. } => {
1431 for (name, entry) in entries {
1432 queue.push_back((path.join(name), entry.clone()));
1433 }
1434 }
1435 FakeFsEntry::Symlink { .. } => {}
1436 }
1437 }
1438 result
1439 }
1440
1441 /// How many `read_dir` calls have been issued.
1442 pub fn read_dir_call_count(&self) -> usize {
1443 self.state.lock().read_dir_call_count
1444 }
1445
1446 /// How many `metadata` calls have been issued.
1447 pub fn metadata_call_count(&self) -> usize {
1448 self.state.lock().metadata_call_count
1449 }
1450
1451 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1452 self.executor.simulate_random_delay()
1453 }
1454}
1455
1456#[cfg(any(test, feature = "test-support"))]
1457impl FakeFsEntry {
1458 fn is_file(&self) -> bool {
1459 matches!(self, Self::File { .. })
1460 }
1461
1462 fn is_symlink(&self) -> bool {
1463 matches!(self, Self::Symlink { .. })
1464 }
1465
1466 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1467 if let Self::File { content, .. } = self {
1468 Ok(content)
1469 } else {
1470 Err(anyhow!("not a file: {}", path.display()))
1471 }
1472 }
1473
1474 fn dir_entries(
1475 &mut self,
1476 path: &Path,
1477 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1478 if let Self::Dir { entries, .. } = self {
1479 Ok(entries)
1480 } else {
1481 Err(anyhow!("not a directory: {}", path.display()))
1482 }
1483 }
1484}
1485
1486#[cfg(any(test, feature = "test-support"))]
1487struct FakeWatcher {}
1488
1489#[cfg(any(test, feature = "test-support"))]
1490impl Watcher for FakeWatcher {
1491 fn add(&self, _: &Path) -> Result<()> {
1492 Ok(())
1493 }
1494
1495 fn remove(&self, _: &Path) -> Result<()> {
1496 Ok(())
1497 }
1498}
1499
1500#[cfg(any(test, feature = "test-support"))]
1501#[derive(Debug)]
1502struct FakeHandle {
1503 inode: u64,
1504}
1505
1506#[cfg(any(test, feature = "test-support"))]
1507impl FileHandle for FakeHandle {
1508 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1509 let fs = fs.as_fake();
1510 let state = fs.state.lock();
1511 let Some(target) = state.moves.get(&self.inode) else {
1512 anyhow::bail!("fake fd not moved")
1513 };
1514
1515 if state.try_read_path(&target, false).is_some() {
1516 return Ok(target.clone());
1517 }
1518 anyhow::bail!("fake fd target not found")
1519 }
1520}
1521
1522#[cfg(any(test, feature = "test-support"))]
1523#[async_trait::async_trait]
1524impl Fs for FakeFs {
1525 async fn create_dir(&self, path: &Path) -> Result<()> {
1526 self.simulate_random_delay().await;
1527
1528 let mut created_dirs = Vec::new();
1529 let mut cur_path = PathBuf::new();
1530 for component in path.components() {
1531 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1532 cur_path.push(component);
1533 if should_skip {
1534 continue;
1535 }
1536 let mut state = self.state.lock();
1537
1538 let inode = state.get_and_increment_inode();
1539 let mtime = state.get_and_increment_mtime();
1540 state.write_path(&cur_path, |entry| {
1541 entry.or_insert_with(|| {
1542 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1543 Arc::new(Mutex::new(FakeFsEntry::Dir {
1544 inode,
1545 mtime,
1546 len: 0,
1547 entries: Default::default(),
1548 git_repo_state: None,
1549 }))
1550 });
1551 Ok(())
1552 })?
1553 }
1554
1555 self.state.lock().emit_event(created_dirs);
1556 Ok(())
1557 }
1558
1559 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1560 self.simulate_random_delay().await;
1561 let mut state = self.state.lock();
1562 let inode = state.get_and_increment_inode();
1563 let mtime = state.get_and_increment_mtime();
1564 let file = Arc::new(Mutex::new(FakeFsEntry::File {
1565 inode,
1566 mtime,
1567 len: 0,
1568 content: Vec::new(),
1569 }));
1570 let mut kind = Some(PathEventKind::Created);
1571 state.write_path(path, |entry| {
1572 match entry {
1573 btree_map::Entry::Occupied(mut e) => {
1574 if options.overwrite {
1575 kind = Some(PathEventKind::Changed);
1576 *e.get_mut() = file;
1577 } else if !options.ignore_if_exists {
1578 return Err(anyhow!("path already exists: {}", path.display()));
1579 }
1580 }
1581 btree_map::Entry::Vacant(e) => {
1582 e.insert(file);
1583 }
1584 }
1585 Ok(())
1586 })?;
1587 state.emit_event([(path, kind)]);
1588 Ok(())
1589 }
1590
1591 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1592 let mut state = self.state.lock();
1593 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1594 state
1595 .write_path(path.as_ref(), move |e| match e {
1596 btree_map::Entry::Vacant(e) => {
1597 e.insert(file);
1598 Ok(())
1599 }
1600 btree_map::Entry::Occupied(mut e) => {
1601 *e.get_mut() = file;
1602 Ok(())
1603 }
1604 })
1605 .unwrap();
1606 state.emit_event([(path, None)]);
1607
1608 Ok(())
1609 }
1610
1611 async fn create_file_with(
1612 &self,
1613 path: &Path,
1614 mut content: Pin<&mut (dyn AsyncRead + Send)>,
1615 ) -> Result<()> {
1616 let mut bytes = Vec::new();
1617 content.read_to_end(&mut bytes).await?;
1618 self.write_file_internal(path, bytes)?;
1619 Ok(())
1620 }
1621
1622 async fn extract_tar_file(
1623 &self,
1624 path: &Path,
1625 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1626 ) -> Result<()> {
1627 let mut entries = content.entries()?;
1628 while let Some(entry) = entries.next().await {
1629 let mut entry = entry?;
1630 if entry.header().entry_type().is_file() {
1631 let path = path.join(entry.path()?.as_ref());
1632 let mut bytes = Vec::new();
1633 entry.read_to_end(&mut bytes).await?;
1634 self.create_dir(path.parent().unwrap()).await?;
1635 self.write_file_internal(&path, bytes)?;
1636 }
1637 }
1638 Ok(())
1639 }
1640
1641 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1642 self.simulate_random_delay().await;
1643
1644 let old_path = normalize_path(old_path);
1645 let new_path = normalize_path(new_path);
1646
1647 let mut state = self.state.lock();
1648 let moved_entry = state.write_path(&old_path, |e| {
1649 if let btree_map::Entry::Occupied(e) = e {
1650 Ok(e.get().clone())
1651 } else {
1652 Err(anyhow!("path does not exist: {}", &old_path.display()))
1653 }
1654 })?;
1655
1656 let inode = match *moved_entry.lock() {
1657 FakeFsEntry::File { inode, .. } => inode,
1658 FakeFsEntry::Dir { inode, .. } => inode,
1659 _ => 0,
1660 };
1661
1662 state.moves.insert(inode, new_path.clone());
1663
1664 state.write_path(&new_path, |e| {
1665 match e {
1666 btree_map::Entry::Occupied(mut e) => {
1667 if options.overwrite {
1668 *e.get_mut() = moved_entry;
1669 } else if !options.ignore_if_exists {
1670 return Err(anyhow!("path already exists: {}", new_path.display()));
1671 }
1672 }
1673 btree_map::Entry::Vacant(e) => {
1674 e.insert(moved_entry);
1675 }
1676 }
1677 Ok(())
1678 })?;
1679
1680 state
1681 .write_path(&old_path, |e| {
1682 if let btree_map::Entry::Occupied(e) = e {
1683 Ok(e.remove())
1684 } else {
1685 unreachable!()
1686 }
1687 })
1688 .unwrap();
1689
1690 state.emit_event([
1691 (old_path, Some(PathEventKind::Removed)),
1692 (new_path, Some(PathEventKind::Created)),
1693 ]);
1694 Ok(())
1695 }
1696
1697 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1698 self.simulate_random_delay().await;
1699
1700 let source = normalize_path(source);
1701 let target = normalize_path(target);
1702 let mut state = self.state.lock();
1703 let mtime = state.get_and_increment_mtime();
1704 let inode = state.get_and_increment_inode();
1705 let source_entry = state.read_path(&source)?;
1706 let content = source_entry.lock().file_content(&source)?.clone();
1707 let mut kind = Some(PathEventKind::Created);
1708 state.write_path(&target, |e| match e {
1709 btree_map::Entry::Occupied(e) => {
1710 if options.overwrite {
1711 kind = Some(PathEventKind::Changed);
1712 Ok(Some(e.get().clone()))
1713 } else if !options.ignore_if_exists {
1714 return Err(anyhow!("{target:?} already exists"));
1715 } else {
1716 Ok(None)
1717 }
1718 }
1719 btree_map::Entry::Vacant(e) => Ok(Some(
1720 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1721 inode,
1722 mtime,
1723 len: content.len() as u64,
1724 content,
1725 })))
1726 .clone(),
1727 )),
1728 })?;
1729 state.emit_event([(target, kind)]);
1730 Ok(())
1731 }
1732
1733 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1734 self.simulate_random_delay().await;
1735
1736 let path = normalize_path(path);
1737 let parent_path = path
1738 .parent()
1739 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1740 let base_name = path.file_name().unwrap();
1741
1742 let mut state = self.state.lock();
1743 let parent_entry = state.read_path(parent_path)?;
1744 let mut parent_entry = parent_entry.lock();
1745 let entry = parent_entry
1746 .dir_entries(parent_path)?
1747 .entry(base_name.to_str().unwrap().into());
1748
1749 match entry {
1750 btree_map::Entry::Vacant(_) => {
1751 if !options.ignore_if_not_exists {
1752 return Err(anyhow!("{path:?} does not exist"));
1753 }
1754 }
1755 btree_map::Entry::Occupied(e) => {
1756 {
1757 let mut entry = e.get().lock();
1758 let children = entry.dir_entries(&path)?;
1759 if !options.recursive && !children.is_empty() {
1760 return Err(anyhow!("{path:?} is not empty"));
1761 }
1762 }
1763 e.remove();
1764 }
1765 }
1766 state.emit_event([(path, Some(PathEventKind::Removed))]);
1767 Ok(())
1768 }
1769
1770 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1771 self.simulate_random_delay().await;
1772
1773 let path = normalize_path(path);
1774 let parent_path = path
1775 .parent()
1776 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1777 let base_name = path.file_name().unwrap();
1778 let mut state = self.state.lock();
1779 let parent_entry = state.read_path(parent_path)?;
1780 let mut parent_entry = parent_entry.lock();
1781 let entry = parent_entry
1782 .dir_entries(parent_path)?
1783 .entry(base_name.to_str().unwrap().into());
1784 match entry {
1785 btree_map::Entry::Vacant(_) => {
1786 if !options.ignore_if_not_exists {
1787 return Err(anyhow!("{path:?} does not exist"));
1788 }
1789 }
1790 btree_map::Entry::Occupied(e) => {
1791 e.get().lock().file_content(&path)?;
1792 e.remove();
1793 }
1794 }
1795 state.emit_event([(path, Some(PathEventKind::Removed))]);
1796 Ok(())
1797 }
1798
1799 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1800 let bytes = self.load_internal(path).await?;
1801 Ok(Box::new(io::Cursor::new(bytes)))
1802 }
1803
1804 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1805 self.simulate_random_delay().await;
1806 let state = self.state.lock();
1807 let entry = state.read_path(&path)?;
1808 let entry = entry.lock();
1809 let inode = match *entry {
1810 FakeFsEntry::File { inode, .. } => inode,
1811 FakeFsEntry::Dir { inode, .. } => inode,
1812 _ => unreachable!(),
1813 };
1814 Ok(Arc::new(FakeHandle { inode }))
1815 }
1816
1817 async fn load(&self, path: &Path) -> Result<String> {
1818 let content = self.load_internal(path).await?;
1819 Ok(String::from_utf8(content.clone())?)
1820 }
1821
1822 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1823 self.load_internal(path).await
1824 }
1825
1826 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1827 self.simulate_random_delay().await;
1828 let path = normalize_path(path.as_path());
1829 self.write_file_internal(path, data.into_bytes())?;
1830 Ok(())
1831 }
1832
1833 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1834 self.simulate_random_delay().await;
1835 let path = normalize_path(path);
1836 let content = chunks(text, line_ending).collect::<String>();
1837 if let Some(path) = path.parent() {
1838 self.create_dir(path).await?;
1839 }
1840 self.write_file_internal(path, content.into_bytes())?;
1841 Ok(())
1842 }
1843
1844 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1845 let path = normalize_path(path);
1846 self.simulate_random_delay().await;
1847 let state = self.state.lock();
1848 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1849 Ok(canonical_path)
1850 } else {
1851 Err(anyhow!("path does not exist: {}", path.display()))
1852 }
1853 }
1854
1855 async fn is_file(&self, path: &Path) -> bool {
1856 let path = normalize_path(path);
1857 self.simulate_random_delay().await;
1858 let state = self.state.lock();
1859 if let Some((entry, _)) = state.try_read_path(&path, true) {
1860 entry.lock().is_file()
1861 } else {
1862 false
1863 }
1864 }
1865
1866 async fn is_dir(&self, path: &Path) -> bool {
1867 self.metadata(path)
1868 .await
1869 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1870 }
1871
1872 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1873 self.simulate_random_delay().await;
1874 let path = normalize_path(path);
1875 let mut state = self.state.lock();
1876 state.metadata_call_count += 1;
1877 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1878 let is_symlink = entry.lock().is_symlink();
1879 if is_symlink {
1880 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1881 entry = e;
1882 } else {
1883 return Ok(None);
1884 }
1885 }
1886
1887 let entry = entry.lock();
1888 Ok(Some(match &*entry {
1889 FakeFsEntry::File {
1890 inode, mtime, len, ..
1891 } => Metadata {
1892 inode: *inode,
1893 mtime: *mtime,
1894 len: *len,
1895 is_dir: false,
1896 is_symlink,
1897 is_fifo: false,
1898 },
1899 FakeFsEntry::Dir {
1900 inode, mtime, len, ..
1901 } => Metadata {
1902 inode: *inode,
1903 mtime: *mtime,
1904 len: *len,
1905 is_dir: true,
1906 is_symlink,
1907 is_fifo: false,
1908 },
1909 FakeFsEntry::Symlink { .. } => unreachable!(),
1910 }))
1911 } else {
1912 Ok(None)
1913 }
1914 }
1915
1916 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1917 self.simulate_random_delay().await;
1918 let path = normalize_path(path);
1919 let state = self.state.lock();
1920 if let Some((entry, _)) = state.try_read_path(&path, false) {
1921 let entry = entry.lock();
1922 if let FakeFsEntry::Symlink { target } = &*entry {
1923 Ok(target.clone())
1924 } else {
1925 Err(anyhow!("not a symlink: {}", path.display()))
1926 }
1927 } else {
1928 Err(anyhow!("path does not exist: {}", path.display()))
1929 }
1930 }
1931
1932 async fn read_dir(
1933 &self,
1934 path: &Path,
1935 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1936 self.simulate_random_delay().await;
1937 let path = normalize_path(path);
1938 let mut state = self.state.lock();
1939 state.read_dir_call_count += 1;
1940 let entry = state.read_path(&path)?;
1941 let mut entry = entry.lock();
1942 let children = entry.dir_entries(&path)?;
1943 let paths = children
1944 .keys()
1945 .map(|file_name| Ok(path.join(file_name)))
1946 .collect::<Vec<_>>();
1947 Ok(Box::pin(futures::stream::iter(paths)))
1948 }
1949
1950 async fn watch(
1951 &self,
1952 path: &Path,
1953 _: Duration,
1954 ) -> (
1955 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1956 Arc<dyn Watcher>,
1957 ) {
1958 self.simulate_random_delay().await;
1959 let (tx, rx) = smol::channel::unbounded();
1960 self.state.lock().event_txs.push(tx);
1961 let path = path.to_path_buf();
1962 let executor = self.executor.clone();
1963 (
1964 Box::pin(futures::StreamExt::filter(rx, move |events| {
1965 let result = events
1966 .iter()
1967 .any(|evt_path| evt_path.path.starts_with(&path));
1968 let executor = executor.clone();
1969 async move {
1970 executor.simulate_random_delay().await;
1971 result
1972 }
1973 })),
1974 Arc::new(FakeWatcher {}),
1975 )
1976 }
1977
1978 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1979 let state = self.state.lock();
1980 let entry = state.read_path(abs_dot_git).unwrap();
1981 let mut entry = entry.lock();
1982 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1983 let state = git_repo_state
1984 .get_or_insert_with(|| {
1985 Arc::new(Mutex::new(FakeGitRepositoryState::new(
1986 abs_dot_git.to_path_buf(),
1987 state.git_event_tx.clone(),
1988 )))
1989 })
1990 .clone();
1991 Some(git::repository::FakeGitRepository::open(state))
1992 } else {
1993 None
1994 }
1995 }
1996
1997 fn is_fake(&self) -> bool {
1998 true
1999 }
2000
2001 async fn is_case_sensitive(&self) -> Result<bool> {
2002 Ok(true)
2003 }
2004
2005 #[cfg(any(test, feature = "test-support"))]
2006 fn as_fake(&self) -> Arc<FakeFs> {
2007 self.this.upgrade().unwrap()
2008 }
2009}
2010
2011fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2012 rope.chunks().flat_map(move |chunk| {
2013 let mut newline = false;
2014 chunk.split('\n').flat_map(move |line| {
2015 let ending = if newline {
2016 Some(line_ending.as_str())
2017 } else {
2018 None
2019 };
2020 newline = true;
2021 ending.into_iter().chain([line])
2022 })
2023 })
2024}
2025
2026fn create_temp_file(path: &Path) -> Result<NamedTempFile> {
2027 let temp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
2028 // Use the directory of the destination as temp dir to avoid
2029 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
2030 // See https://github.com/zed-industries/zed/pull/8437 for more details.
2031 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?
2032 } else if cfg!(target_os = "windows") {
2033 // If temp dir is set to a different drive than the destination,
2034 // we receive error:
2035 //
2036 // failed to persist temporary file:
2037 // The system cannot move the file to a different disk drive. (os error 17)
2038 //
2039 // So we use the directory of the destination as a temp dir to avoid it.
2040 // https://github.com/zed-industries/zed/issues/16571
2041 NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?
2042 } else {
2043 NamedTempFile::new()?
2044 };
2045
2046 Ok(temp_file)
2047}
2048
2049#[cfg(target_os = "macos")]
2050async fn write_to_file_as_root(_temp_file_path: PathBuf, _target_file_path: PathBuf) -> Result<()> {
2051 unimplemented!("write_to_file_as_root is not implemented")
2052}
2053
2054#[cfg(target_os = "windows")]
2055async fn write_to_file_as_root(_temp_file_path: PathBuf, _target_file_path: PathBuf) -> Result<()> {
2056 unimplemented!("write_to_file_as_root is not implemented")
2057}
2058
2059#[cfg(any(target_os = "linux", target_os = "freebsd"))]
2060async fn write_to_file_as_root(temp_file_path: PathBuf, target_file_path: PathBuf) -> Result<()> {
2061 use shlex::try_quote;
2062 use std::os::unix::fs::PermissionsExt;
2063 use which::which;
2064
2065 let pkexec_path = smol::unblock(|| which("pkexec"))
2066 .await
2067 .map_err(|_| anyhow::anyhow!("pkexec not found in PATH"))?;
2068
2069 let script_file = smol::unblock(move || {
2070 let script_file = tempfile::Builder::new()
2071 .prefix("write-to-file-as-root-")
2072 .tempfile_in(paths::temp_dir())?;
2073
2074 writeln!(
2075 script_file.as_file(),
2076 "#!/usr/bin/env sh\nset -eu\ncat \"{}\" > \"{}\"",
2077 try_quote(&temp_file_path.to_string_lossy())?,
2078 try_quote(&target_file_path.to_string_lossy())?
2079 )?;
2080
2081 let mut perms = script_file.as_file().metadata()?.permissions();
2082 perms.set_mode(0o700); // rwx------
2083 script_file.as_file().set_permissions(perms)?;
2084
2085 Result::<_>::Ok(script_file)
2086 })
2087 .await?;
2088
2089 let script_path = script_file.into_temp_path();
2090
2091 let output = Command::new(&pkexec_path)
2092 .arg("--disable-internal-agent")
2093 .arg(&script_path)
2094 .output()
2095 .await?;
2096
2097 if !output.status.success() {
2098 return Err(anyhow::anyhow!("Failed to write to file as root"));
2099 }
2100
2101 Ok(())
2102}
2103
2104pub fn normalize_path(path: &Path) -> PathBuf {
2105 let mut components = path.components().peekable();
2106 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2107 components.next();
2108 PathBuf::from(c.as_os_str())
2109 } else {
2110 PathBuf::new()
2111 };
2112
2113 for component in components {
2114 match component {
2115 Component::Prefix(..) => unreachable!(),
2116 Component::RootDir => {
2117 ret.push(component.as_os_str());
2118 }
2119 Component::CurDir => {}
2120 Component::ParentDir => {
2121 ret.pop();
2122 }
2123 Component::Normal(c) => {
2124 ret.push(c);
2125 }
2126 }
2127 }
2128 ret
2129}
2130
2131pub fn copy_recursive<'a>(
2132 fs: &'a dyn Fs,
2133 source: &'a Path,
2134 target: &'a Path,
2135 options: CopyOptions,
2136) -> BoxFuture<'a, Result<()>> {
2137 use futures::future::FutureExt;
2138
2139 async move {
2140 let metadata = fs
2141 .metadata(source)
2142 .await?
2143 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2144 if metadata.is_dir {
2145 if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
2146 if options.ignore_if_exists {
2147 return Ok(());
2148 } else {
2149 return Err(anyhow!("{target:?} already exists"));
2150 }
2151 }
2152
2153 let _ = fs
2154 .remove_dir(
2155 target,
2156 RemoveOptions {
2157 recursive: true,
2158 ignore_if_not_exists: true,
2159 },
2160 )
2161 .await;
2162 fs.create_dir(target).await?;
2163 let mut children = fs.read_dir(source).await?;
2164 while let Some(child_path) = children.next().await {
2165 if let Ok(child_path) = child_path {
2166 if let Some(file_name) = child_path.file_name() {
2167 let child_target_path = target.join(file_name);
2168 copy_recursive(fs, &child_path, &child_target_path, options).await?;
2169 }
2170 }
2171 }
2172
2173 Ok(())
2174 } else {
2175 fs.copy_file(source, target, options).await
2176 }
2177 }
2178 .boxed()
2179}
2180
2181// todo(windows)
2182// can we get file id not open the file twice?
2183// https://github.com/rust-lang/rust/issues/63010
2184#[cfg(target_os = "windows")]
2185async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2186 use std::os::windows::io::AsRawHandle;
2187
2188 use smol::fs::windows::OpenOptionsExt;
2189 use windows::Win32::{
2190 Foundation::HANDLE,
2191 Storage::FileSystem::{
2192 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2193 },
2194 };
2195
2196 let file = smol::fs::OpenOptions::new()
2197 .read(true)
2198 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2199 .open(path)
2200 .await?;
2201
2202 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2203 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2204 // This function supports Windows XP+
2205 smol::unblock(move || {
2206 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2207
2208 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2209 })
2210 .await
2211}
2212
2213#[cfg(test)]
2214mod tests {
2215 use super::*;
2216 use gpui::BackgroundExecutor;
2217 use serde_json::json;
2218
2219 #[gpui::test]
2220 async fn test_fake_fs(executor: BackgroundExecutor) {
2221 let fs = FakeFs::new(executor.clone());
2222 fs.insert_tree(
2223 "/root",
2224 json!({
2225 "dir1": {
2226 "a": "A",
2227 "b": "B"
2228 },
2229 "dir2": {
2230 "c": "C",
2231 "dir3": {
2232 "d": "D"
2233 }
2234 }
2235 }),
2236 )
2237 .await;
2238
2239 assert_eq!(
2240 fs.files(),
2241 vec![
2242 PathBuf::from("/root/dir1/a"),
2243 PathBuf::from("/root/dir1/b"),
2244 PathBuf::from("/root/dir2/c"),
2245 PathBuf::from("/root/dir2/dir3/d"),
2246 ]
2247 );
2248
2249 fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2250 .await
2251 .unwrap();
2252
2253 assert_eq!(
2254 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2255 .await
2256 .unwrap(),
2257 PathBuf::from("/root/dir2/dir3"),
2258 );
2259 assert_eq!(
2260 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2261 .await
2262 .unwrap(),
2263 PathBuf::from("/root/dir2/dir3/d"),
2264 );
2265 assert_eq!(
2266 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2267 "D",
2268 );
2269 }
2270}