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