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