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