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