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