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