1use anyhow::{anyhow, Result};
2use fsevent::EventStream;
3use futures::{future::BoxFuture, Stream, StreamExt};
4use language::LineEnding;
5use smol::io::{AsyncReadExt, AsyncWriteExt};
6use std::{
7 io,
8 os::unix::fs::MetadataExt,
9 path::{Component, Path, PathBuf},
10 pin::Pin,
11 time::{Duration, SystemTime},
12};
13use text::Rope;
14
15#[cfg(any(test, feature = "test-support"))]
16use collections::{btree_map, BTreeMap};
17#[cfg(any(test, feature = "test-support"))]
18use futures::lock::Mutex;
19#[cfg(any(test, feature = "test-support"))]
20use std::sync::{Arc, Weak};
21
22#[async_trait::async_trait]
23pub trait Fs: Send + Sync {
24 async fn create_dir(&self, path: &Path) -> Result<()>;
25 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
26 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
27 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
28 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
29 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
30 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
31 async fn load(&self, path: &Path) -> Result<String>;
32 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
33 async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
34 async fn is_file(&self, path: &Path) -> bool;
35 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
36 async fn read_dir(
37 &self,
38 path: &Path,
39 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
40 async fn watch(
41 &self,
42 path: &Path,
43 latency: Duration,
44 ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>;
45 fn is_fake(&self) -> bool;
46 #[cfg(any(test, feature = "test-support"))]
47 fn as_fake(&self) -> &FakeFs;
48}
49
50#[derive(Copy, Clone, Default)]
51pub struct CreateOptions {
52 pub overwrite: bool,
53 pub ignore_if_exists: bool,
54}
55
56#[derive(Copy, Clone, Default)]
57pub struct CopyOptions {
58 pub overwrite: bool,
59 pub ignore_if_exists: bool,
60}
61
62#[derive(Copy, Clone, Default)]
63pub struct RenameOptions {
64 pub overwrite: bool,
65 pub ignore_if_exists: bool,
66}
67
68#[derive(Copy, Clone, Default)]
69pub struct RemoveOptions {
70 pub recursive: bool,
71 pub ignore_if_not_exists: bool,
72}
73
74#[derive(Clone, Debug)]
75pub struct Metadata {
76 pub inode: u64,
77 pub mtime: SystemTime,
78 pub is_symlink: bool,
79 pub is_dir: bool,
80}
81
82pub struct RealFs;
83
84#[async_trait::async_trait]
85impl Fs for RealFs {
86 async fn create_dir(&self, path: &Path) -> Result<()> {
87 Ok(smol::fs::create_dir_all(path).await?)
88 }
89
90 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
91 let mut open_options = smol::fs::OpenOptions::new();
92 open_options.write(true).create(true);
93 if options.overwrite {
94 open_options.truncate(true);
95 } else if !options.ignore_if_exists {
96 open_options.create_new(true);
97 }
98 open_options.open(path).await?;
99 Ok(())
100 }
101
102 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
103 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
104 if options.ignore_if_exists {
105 return Ok(());
106 } else {
107 return Err(anyhow!("{target:?} already exists"));
108 }
109 }
110
111 smol::fs::copy(source, target).await?;
112 Ok(())
113 }
114
115 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
116 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
117 if options.ignore_if_exists {
118 return Ok(());
119 } else {
120 return Err(anyhow!("{target:?} already exists"));
121 }
122 }
123
124 smol::fs::rename(source, target).await?;
125 Ok(())
126 }
127
128 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
129 let result = if options.recursive {
130 smol::fs::remove_dir_all(path).await
131 } else {
132 smol::fs::remove_dir(path).await
133 };
134 match result {
135 Ok(()) => Ok(()),
136 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
137 Ok(())
138 }
139 Err(err) => Err(err)?,
140 }
141 }
142
143 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
144 match smol::fs::remove_file(path).await {
145 Ok(()) => Ok(()),
146 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
147 Ok(())
148 }
149 Err(err) => Err(err)?,
150 }
151 }
152
153 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
154 Ok(Box::new(std::fs::File::open(path)?))
155 }
156
157 async fn load(&self, path: &Path) -> Result<String> {
158 let mut file = smol::fs::File::open(path).await?;
159 let mut text = String::new();
160 file.read_to_string(&mut text).await?;
161 Ok(text)
162 }
163
164 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
165 let buffer_size = text.summary().bytes.min(10 * 1024);
166 let file = smol::fs::File::create(path).await?;
167 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
168 for chunk in chunks(text, line_ending) {
169 writer.write_all(chunk.as_bytes()).await?;
170 }
171 writer.flush().await?;
172 Ok(())
173 }
174
175 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
176 Ok(smol::fs::canonicalize(path).await?)
177 }
178
179 async fn is_file(&self, path: &Path) -> bool {
180 smol::fs::metadata(path)
181 .await
182 .map_or(false, |metadata| metadata.is_file())
183 }
184
185 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
186 let symlink_metadata = match smol::fs::symlink_metadata(path).await {
187 Ok(metadata) => metadata,
188 Err(err) => {
189 return match (err.kind(), err.raw_os_error()) {
190 (io::ErrorKind::NotFound, _) => Ok(None),
191 (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
192 _ => Err(anyhow::Error::new(err)),
193 }
194 }
195 };
196
197 let is_symlink = symlink_metadata.file_type().is_symlink();
198 let metadata = if is_symlink {
199 smol::fs::metadata(path).await?
200 } else {
201 symlink_metadata
202 };
203 Ok(Some(Metadata {
204 inode: metadata.ino(),
205 mtime: metadata.modified().unwrap(),
206 is_symlink,
207 is_dir: metadata.file_type().is_dir(),
208 }))
209 }
210
211 async fn read_dir(
212 &self,
213 path: &Path,
214 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
215 let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
216 Ok(entry) => Ok(entry.path()),
217 Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
218 });
219 Ok(Box::pin(result))
220 }
221
222 async fn watch(
223 &self,
224 path: &Path,
225 latency: Duration,
226 ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
227 let (tx, rx) = smol::channel::unbounded();
228 let (stream, handle) = EventStream::new(&[path], latency);
229 std::mem::forget(handle);
230 std::thread::spawn(move || {
231 stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
232 });
233 Box::pin(rx)
234 }
235
236 fn is_fake(&self) -> bool {
237 false
238 }
239 #[cfg(any(test, feature = "test-support"))]
240 fn as_fake(&self) -> &FakeFs {
241 panic!("called `RealFs::as_fake`")
242 }
243}
244
245#[cfg(any(test, feature = "test-support"))]
246pub struct FakeFs {
247 // Use an unfair lock to ensure tests are deterministic.
248 state: Mutex<FakeFsState>,
249 executor: Weak<gpui::executor::Background>,
250}
251
252#[cfg(any(test, feature = "test-support"))]
253struct FakeFsState {
254 root: Arc<Mutex<FakeFsEntry>>,
255 next_inode: u64,
256 event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
257}
258
259#[cfg(any(test, feature = "test-support"))]
260#[derive(Debug)]
261enum FakeFsEntry {
262 File {
263 inode: u64,
264 mtime: SystemTime,
265 content: String,
266 },
267 Dir {
268 inode: u64,
269 mtime: SystemTime,
270 entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
271 },
272 Symlink {
273 target: PathBuf,
274 },
275}
276
277#[cfg(any(test, feature = "test-support"))]
278impl FakeFsState {
279 async fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
280 Ok(self
281 .try_read_path(target)
282 .await
283 .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
284 .0)
285 }
286
287 async fn try_read_path<'a>(
288 &'a self,
289 target: &Path,
290 ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
291 let mut path = target.to_path_buf();
292 let mut real_path = PathBuf::new();
293 let mut entry_stack = Vec::new();
294 'outer: loop {
295 let mut path_components = path.components().collect::<collections::VecDeque<_>>();
296 while let Some(component) = path_components.pop_front() {
297 match component {
298 Component::Prefix(_) => panic!("prefix paths aren't supported"),
299 Component::RootDir => {
300 entry_stack.clear();
301 entry_stack.push(self.root.clone());
302 real_path.clear();
303 real_path.push("/");
304 }
305 Component::CurDir => {}
306 Component::ParentDir => {
307 entry_stack.pop()?;
308 real_path.pop();
309 }
310 Component::Normal(name) => {
311 let current_entry = entry_stack.last().cloned()?;
312 let current_entry = current_entry.lock().await;
313 if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
314 let entry = entries.get(name.to_str().unwrap()).cloned()?;
315 let _entry = entry.lock().await;
316 if let FakeFsEntry::Symlink { target, .. } = &*_entry {
317 let mut target = target.clone();
318 target.extend(path_components);
319 path = target;
320 continue 'outer;
321 } else {
322 entry_stack.push(entry.clone());
323 real_path.push(name);
324 }
325 } else {
326 return None;
327 }
328 }
329 }
330 }
331 break;
332 }
333 entry_stack.pop().map(|entry| (entry, real_path))
334 }
335
336 async fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
337 where
338 Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
339 {
340 let path = normalize_path(path);
341 let filename = path
342 .file_name()
343 .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
344 let parent_path = path.parent().unwrap();
345
346 let parent = self.read_path(parent_path).await?;
347 let mut parent = parent.lock().await;
348 let new_entry = parent
349 .dir_entries(parent_path)?
350 .entry(filename.to_str().unwrap().into());
351 callback(new_entry)
352 }
353
354 fn emit_event<I, T>(&mut self, paths: I)
355 where
356 I: IntoIterator<Item = T>,
357 T: Into<PathBuf>,
358 {
359 let events = paths
360 .into_iter()
361 .map(|path| fsevent::Event {
362 event_id: 0,
363 flags: fsevent::StreamFlags::empty(),
364 path: path.into(),
365 })
366 .collect::<Vec<_>>();
367
368 self.event_txs.retain(|tx| {
369 let _ = tx.try_send(events.clone());
370 !tx.is_closed()
371 });
372 }
373}
374
375#[cfg(any(test, feature = "test-support"))]
376impl FakeFs {
377 pub fn new(executor: Arc<gpui::executor::Background>) -> Arc<Self> {
378 Arc::new(Self {
379 executor: Arc::downgrade(&executor),
380 state: Mutex::new(FakeFsState {
381 root: Arc::new(Mutex::new(FakeFsEntry::Dir {
382 inode: 0,
383 mtime: SystemTime::now(),
384 entries: Default::default(),
385 })),
386 next_inode: 1,
387 event_txs: Default::default(),
388 }),
389 })
390 }
391
392 pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
393 let mut state = self.state.lock().await;
394 let path = path.as_ref();
395 let inode = state.next_inode;
396 state.next_inode += 1;
397 let file = Arc::new(Mutex::new(FakeFsEntry::File {
398 inode,
399 mtime: SystemTime::now(),
400 content,
401 }));
402 state
403 .write_path(path, move |entry| {
404 match entry {
405 btree_map::Entry::Vacant(e) => {
406 e.insert(file);
407 }
408 btree_map::Entry::Occupied(mut e) => {
409 *e.get_mut() = file;
410 }
411 }
412 Ok(())
413 })
414 .await
415 .unwrap();
416 state.emit_event(&[path]);
417 }
418
419 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
420 let mut state = self.state.lock().await;
421 let path = path.as_ref();
422 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
423 state
424 .write_path(path.as_ref(), move |e| match e {
425 btree_map::Entry::Vacant(e) => {
426 e.insert(file);
427 Ok(())
428 }
429 btree_map::Entry::Occupied(mut e) => {
430 *e.get_mut() = file;
431 Ok(())
432 }
433 })
434 .await
435 .unwrap();
436 state.emit_event(&[path]);
437 }
438
439 #[must_use]
440 pub fn insert_tree<'a>(
441 &'a self,
442 path: impl 'a + AsRef<Path> + Send,
443 tree: serde_json::Value,
444 ) -> futures::future::BoxFuture<'a, ()> {
445 use futures::FutureExt as _;
446 use serde_json::Value::*;
447
448 async move {
449 let path = path.as_ref();
450
451 match tree {
452 Object(map) => {
453 self.create_dir(path).await.unwrap();
454 for (name, contents) in map {
455 let mut path = PathBuf::from(path);
456 path.push(name);
457 self.insert_tree(&path, contents).await;
458 }
459 }
460 Null => {
461 self.create_dir(&path).await.unwrap();
462 }
463 String(contents) => {
464 self.insert_file(&path, contents).await;
465 }
466 _ => {
467 panic!("JSON object must contain only objects, strings, or null");
468 }
469 }
470 }
471 .boxed()
472 }
473
474 pub async fn files(&self) -> Vec<PathBuf> {
475 let mut result = Vec::new();
476 let mut queue = collections::VecDeque::new();
477 queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone()));
478 while let Some((path, entry)) = queue.pop_front() {
479 let e = entry.lock().await;
480 match &*e {
481 FakeFsEntry::File { .. } => result.push(path),
482 FakeFsEntry::Dir { entries, .. } => {
483 for (name, entry) in entries {
484 queue.push_back((path.join(name), entry.clone()));
485 }
486 }
487 FakeFsEntry::Symlink { .. } => {}
488 }
489 }
490 result
491 }
492
493 async fn simulate_random_delay(&self) {
494 self.executor
495 .upgrade()
496 .expect("executor has been dropped")
497 .simulate_random_delay()
498 .await;
499 }
500}
501
502#[cfg(any(test, feature = "test-support"))]
503impl FakeFsEntry {
504 fn is_file(&self) -> bool {
505 matches!(self, Self::File { .. })
506 }
507
508 fn file_content(&self, path: &Path) -> Result<&String> {
509 if let Self::File { content, .. } = self {
510 Ok(content)
511 } else {
512 Err(anyhow!("not a file: {}", path.display()))
513 }
514 }
515
516 fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
517 if let Self::File { content, mtime, .. } = self {
518 *mtime = SystemTime::now();
519 *content = new_content;
520 Ok(())
521 } else {
522 Err(anyhow!("not a file: {}", path.display()))
523 }
524 }
525
526 fn dir_entries(
527 &mut self,
528 path: &Path,
529 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
530 if let Self::Dir { entries, .. } = self {
531 Ok(entries)
532 } else {
533 Err(anyhow!("not a directory: {}", path.display()))
534 }
535 }
536}
537
538#[cfg(any(test, feature = "test-support"))]
539#[async_trait::async_trait]
540impl Fs for FakeFs {
541 async fn create_dir(&self, path: &Path) -> Result<()> {
542 self.simulate_random_delay().await;
543 let mut state = self.state.lock().await;
544
545 let mut created_dirs = Vec::new();
546 let mut cur_path = PathBuf::new();
547 for component in path.components() {
548 cur_path.push(component);
549 if cur_path == Path::new("/") {
550 continue;
551 }
552
553 let inode = state.next_inode;
554 state.next_inode += 1;
555 state
556 .write_path(&cur_path, |entry| {
557 entry.or_insert(Arc::new(Mutex::new(FakeFsEntry::Dir {
558 inode,
559 mtime: SystemTime::now(),
560 entries: Default::default(),
561 })));
562 created_dirs.push(cur_path.clone());
563 Ok(())
564 })
565 .await?;
566 }
567
568 state.emit_event(&created_dirs);
569 Ok(())
570 }
571
572 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
573 self.simulate_random_delay().await;
574 let mut state = self.state.lock().await;
575 let inode = state.next_inode;
576 state.next_inode += 1;
577 let file = Arc::new(Mutex::new(FakeFsEntry::File {
578 inode,
579 mtime: SystemTime::now(),
580 content: String::new(),
581 }));
582 state
583 .write_path(path, |entry| {
584 match entry {
585 btree_map::Entry::Occupied(mut e) => {
586 if options.overwrite {
587 *e.get_mut() = file;
588 } else if !options.ignore_if_exists {
589 return Err(anyhow!("path already exists: {}", path.display()));
590 }
591 }
592 btree_map::Entry::Vacant(e) => {
593 e.insert(file);
594 }
595 }
596 Ok(())
597 })
598 .await?;
599 state.emit_event(&[path]);
600 Ok(())
601 }
602
603 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
604 let old_path = normalize_path(old_path);
605 let new_path = normalize_path(new_path);
606 let mut state = self.state.lock().await;
607 let moved_entry = state
608 .write_path(&old_path, |e| {
609 if let btree_map::Entry::Occupied(e) = e {
610 Ok(e.remove())
611 } else {
612 Err(anyhow!("path does not exist: {}", &old_path.display()))
613 }
614 })
615 .await?;
616 state
617 .write_path(&new_path, |e| {
618 match e {
619 btree_map::Entry::Occupied(mut e) => {
620 if options.overwrite {
621 *e.get_mut() = moved_entry;
622 } else if !options.ignore_if_exists {
623 return Err(anyhow!("path already exists: {}", new_path.display()));
624 }
625 }
626 btree_map::Entry::Vacant(e) => {
627 e.insert(moved_entry);
628 }
629 }
630 Ok(())
631 })
632 .await?;
633 state.emit_event(&[old_path, new_path]);
634 Ok(())
635 }
636
637 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
638 let source = normalize_path(source);
639 let target = normalize_path(target);
640 let mut state = self.state.lock().await;
641 let source_entry = state.read_path(&source).await?;
642 let content = source_entry.lock().await.file_content(&source)?.clone();
643 let entry = state
644 .write_path(&target, |e| match e {
645 btree_map::Entry::Occupied(e) => {
646 if options.overwrite {
647 Ok(Some(e.get().clone()))
648 } else if !options.ignore_if_exists {
649 return Err(anyhow!("{target:?} already exists"));
650 } else {
651 Ok(None)
652 }
653 }
654 btree_map::Entry::Vacant(e) => Ok(Some(
655 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
656 inode: 0,
657 mtime: SystemTime::now(),
658 content: String::new(),
659 })))
660 .clone(),
661 )),
662 })
663 .await?;
664 if let Some(entry) = entry {
665 entry.lock().await.set_file_content(&target, content)?;
666 }
667 state.emit_event(&[target]);
668 Ok(())
669 }
670
671 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
672 let path = normalize_path(path);
673 let parent_path = path
674 .parent()
675 .ok_or_else(|| anyhow!("cannot remove the root"))?;
676 let base_name = path.file_name().unwrap();
677
678 let state = self.state.lock().await;
679 let parent_entry = state.read_path(parent_path).await?;
680 let mut parent_entry = parent_entry.lock().await;
681 let entry = parent_entry
682 .dir_entries(parent_path)?
683 .entry(base_name.to_str().unwrap().into());
684
685 match entry {
686 btree_map::Entry::Vacant(_) => {
687 if !options.ignore_if_not_exists {
688 return Err(anyhow!("{path:?} does not exist"));
689 }
690 }
691 btree_map::Entry::Occupied(e) => {
692 {
693 let mut entry = e.get().lock().await;
694 let children = entry.dir_entries(&path)?;
695 if !options.recursive && !children.is_empty() {
696 return Err(anyhow!("{path:?} is not empty"));
697 }
698 }
699 e.remove();
700 }
701 }
702
703 Ok(())
704 }
705
706 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
707 let path = normalize_path(path);
708 let parent_path = path
709 .parent()
710 .ok_or_else(|| anyhow!("cannot remove the root"))?;
711 let base_name = path.file_name().unwrap();
712 let mut state = self.state.lock().await;
713 let parent_entry = state.read_path(parent_path).await?;
714 let mut parent_entry = parent_entry.lock().await;
715 let entry = parent_entry
716 .dir_entries(parent_path)?
717 .entry(base_name.to_str().unwrap().into());
718 match entry {
719 btree_map::Entry::Vacant(_) => {
720 if !options.ignore_if_not_exists {
721 return Err(anyhow!("{path:?} does not exist"));
722 }
723 }
724 btree_map::Entry::Occupied(e) => {
725 e.get().lock().await.file_content(&path)?;
726 e.remove();
727 }
728 }
729 state.emit_event(&[path]);
730 Ok(())
731 }
732
733 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
734 let text = self.load(path).await?;
735 Ok(Box::new(io::Cursor::new(text)))
736 }
737
738 async fn load(&self, path: &Path) -> Result<String> {
739 let path = normalize_path(path);
740 self.simulate_random_delay().await;
741 let state = self.state.lock().await;
742 let entry = state.read_path(&path).await?;
743 let entry = entry.lock().await;
744 entry.file_content(&path).cloned()
745 }
746
747 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
748 self.simulate_random_delay().await;
749 let path = normalize_path(path);
750 let content = chunks(text, line_ending).collect();
751 self.insert_file(path, content).await;
752 Ok(())
753 }
754
755 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
756 let path = normalize_path(path);
757 self.simulate_random_delay().await;
758 let state = self.state.lock().await;
759 if let Some((_, real_path)) = state.try_read_path(&path).await {
760 Ok(real_path)
761 } else {
762 Err(anyhow!("path does not exist: {}", path.display()))
763 }
764 }
765
766 async fn is_file(&self, path: &Path) -> bool {
767 let path = normalize_path(path);
768 self.simulate_random_delay().await;
769 let state = self.state.lock().await;
770 if let Some((entry, _)) = state.try_read_path(&path).await {
771 entry.lock().await.is_file()
772 } else {
773 false
774 }
775 }
776
777 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
778 self.simulate_random_delay().await;
779 let path = normalize_path(path);
780 let state = self.state.lock().await;
781 if let Some((entry, real_path)) = state.try_read_path(&path).await {
782 let entry = entry.lock().await;
783 let is_symlink = real_path != path;
784
785 Ok(Some(match &*entry {
786 FakeFsEntry::File { inode, mtime, .. } => Metadata {
787 inode: *inode,
788 mtime: *mtime,
789 is_dir: false,
790 is_symlink,
791 },
792 FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
793 inode: *inode,
794 mtime: *mtime,
795 is_dir: true,
796 is_symlink,
797 },
798 FakeFsEntry::Symlink { .. } => unreachable!(),
799 }))
800 } else {
801 Ok(None)
802 }
803 }
804
805 async fn read_dir(
806 &self,
807 path: &Path,
808 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
809 self.simulate_random_delay().await;
810 let path = normalize_path(path);
811 let state = self.state.lock().await;
812 let entry = state.read_path(&path).await?;
813 let mut entry = entry.lock().await;
814 let children = entry.dir_entries(&path)?;
815 let paths = children
816 .keys()
817 .map(|file_name| Ok(path.join(file_name)))
818 .collect::<Vec<_>>();
819 Ok(Box::pin(futures::stream::iter(paths)))
820 }
821
822 async fn watch(
823 &self,
824 path: &Path,
825 _: Duration,
826 ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
827 let mut state = self.state.lock().await;
828 self.simulate_random_delay().await;
829 let (tx, rx) = smol::channel::unbounded();
830 state.event_txs.push(tx);
831 let path = path.to_path_buf();
832 let executor = self.executor.clone();
833 Box::pin(futures::StreamExt::filter(rx, move |events| {
834 let result = events.iter().any(|event| event.path.starts_with(&path));
835 let executor = executor.clone();
836 async move {
837 if let Some(executor) = executor.clone().upgrade() {
838 executor.simulate_random_delay().await;
839 }
840 result
841 }
842 }))
843 }
844
845 fn is_fake(&self) -> bool {
846 true
847 }
848
849 #[cfg(any(test, feature = "test-support"))]
850 fn as_fake(&self) -> &FakeFs {
851 self
852 }
853}
854
855fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
856 rope.chunks().flat_map(move |chunk| {
857 let mut newline = false;
858 chunk.split('\n').flat_map(move |line| {
859 let ending = if newline {
860 Some(line_ending.as_str())
861 } else {
862 None
863 };
864 newline = true;
865 ending.into_iter().chain([line])
866 })
867 })
868}
869
870pub fn normalize_path(path: &Path) -> PathBuf {
871 let mut components = path.components().peekable();
872 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
873 components.next();
874 PathBuf::from(c.as_os_str())
875 } else {
876 PathBuf::new()
877 };
878
879 for component in components {
880 match component {
881 Component::Prefix(..) => unreachable!(),
882 Component::RootDir => {
883 ret.push(component.as_os_str());
884 }
885 Component::CurDir => {}
886 Component::ParentDir => {
887 ret.pop();
888 }
889 Component::Normal(c) => {
890 ret.push(c);
891 }
892 }
893 }
894 ret
895}
896
897pub fn copy_recursive<'a>(
898 fs: &'a dyn Fs,
899 source: &'a Path,
900 target: &'a Path,
901 options: CopyOptions,
902) -> BoxFuture<'a, Result<()>> {
903 use futures::future::FutureExt;
904
905 async move {
906 let metadata = fs
907 .metadata(source)
908 .await?
909 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
910 if metadata.is_dir {
911 if !options.overwrite && fs.metadata(target).await.is_ok() {
912 if options.ignore_if_exists {
913 return Ok(());
914 } else {
915 return Err(anyhow!("{target:?} already exists"));
916 }
917 }
918
919 let _ = fs
920 .remove_dir(
921 target,
922 RemoveOptions {
923 recursive: true,
924 ignore_if_not_exists: true,
925 },
926 )
927 .await;
928 fs.create_dir(target).await?;
929 let mut children = fs.read_dir(source).await?;
930 while let Some(child_path) = children.next().await {
931 if let Ok(child_path) = child_path {
932 if let Some(file_name) = child_path.file_name() {
933 let child_target_path = target.join(file_name);
934 copy_recursive(fs, &child_path, &child_target_path, options).await?;
935 }
936 }
937 }
938
939 Ok(())
940 } else {
941 fs.copy_file(source, target, options).await
942 }
943 }
944 .boxed()
945}
946
947#[cfg(test)]
948mod tests {
949 use super::*;
950 use gpui::TestAppContext;
951 use serde_json::json;
952
953 #[gpui::test]
954 async fn test_fake_fs(cx: &mut TestAppContext) {
955 let fs = FakeFs::new(cx.background());
956
957 fs.insert_tree(
958 "/root",
959 json!({
960 "dir1": {
961 "a": "A",
962 "b": "B"
963 },
964 "dir2": {
965 "c": "C",
966 "dir3": {
967 "d": "D"
968 }
969 }
970 }),
971 )
972 .await;
973
974 assert_eq!(
975 fs.files().await,
976 vec![
977 PathBuf::from("/root/dir1/a"),
978 PathBuf::from("/root/dir1/b"),
979 PathBuf::from("/root/dir2/c"),
980 PathBuf::from("/root/dir2/dir3/d"),
981 ]
982 );
983
984 fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
985 .await;
986
987 assert_eq!(
988 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
989 .await
990 .unwrap(),
991 PathBuf::from("/root/dir2/dir3"),
992 );
993 assert_eq!(
994 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
995 .await
996 .unwrap(),
997 PathBuf::from("/root/dir2/dir3/d"),
998 );
999 assert_eq!(
1000 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1001 "D",
1002 );
1003 }
1004}