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