1pub mod repository;
2
3use anyhow::{anyhow, Result};
4pub use fsevent::Event;
5#[cfg(target_os = "macos")]
6use fsevent::EventStream;
7
8#[cfg(not(target_os = "macos"))]
9use fsevent::StreamFlags;
10
11#[cfg(not(target_os = "macos"))]
12use notify::{Config, EventKind, Watcher};
13
14#[cfg(unix)]
15use std::os::unix::fs::MetadataExt;
16
17use futures::{future::BoxFuture, Stream, StreamExt};
18use git2::Repository as LibGitRepository;
19use parking_lot::Mutex;
20use repository::GitRepository;
21use rope::Rope;
22use smol::io::{AsyncReadExt, AsyncWriteExt};
23use std::io::Write;
24use std::sync::Arc;
25use std::{
26 io,
27 path::{Component, Path, PathBuf},
28 pin::Pin,
29 time::{Duration, SystemTime},
30};
31use tempfile::{NamedTempFile, TempDir};
32use text::LineEnding;
33use util::{paths, ResultExt};
34
35#[cfg(any(test, feature = "test-support"))]
36use collections::{btree_map, BTreeMap};
37#[cfg(any(test, feature = "test-support"))]
38use repository::{FakeGitRepositoryState, GitFileStatus};
39#[cfg(any(test, feature = "test-support"))]
40use std::ffi::OsStr;
41
42#[async_trait::async_trait]
43pub trait Fs: Send + Sync {
44 async fn create_dir(&self, path: &Path) -> Result<()>;
45 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
46 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
47 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
48 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
49 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
50 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
51 async fn load(&self, path: &Path) -> Result<String>;
52 async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
53 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
54 async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
55 async fn is_file(&self, path: &Path) -> bool;
56 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
57 async fn read_link(&self, path: &Path) -> Result<PathBuf>;
58 async fn read_dir(
59 &self,
60 path: &Path,
61 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
62
63 async fn watch(
64 &self,
65 path: &Path,
66 latency: Duration,
67 ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>>;
68
69 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>>;
70 fn is_fake(&self) -> bool;
71 async fn is_case_sensitive(&self) -> Result<bool>;
72 #[cfg(any(test, feature = "test-support"))]
73 fn as_fake(&self) -> &FakeFs;
74}
75
76#[derive(Copy, Clone, Default)]
77pub struct CreateOptions {
78 pub overwrite: bool,
79 pub ignore_if_exists: bool,
80}
81
82#[derive(Copy, Clone, Default)]
83pub struct CopyOptions {
84 pub overwrite: bool,
85 pub ignore_if_exists: bool,
86}
87
88#[derive(Copy, Clone, Default)]
89pub struct RenameOptions {
90 pub overwrite: bool,
91 pub ignore_if_exists: bool,
92}
93
94#[derive(Copy, Clone, Default)]
95pub struct RemoveOptions {
96 pub recursive: bool,
97 pub ignore_if_not_exists: bool,
98}
99
100#[derive(Copy, Clone, Debug)]
101pub struct Metadata {
102 pub inode: u64,
103 pub mtime: SystemTime,
104 pub is_symlink: bool,
105 pub is_dir: bool,
106}
107
108pub struct RealFs;
109
110#[async_trait::async_trait]
111impl Fs for RealFs {
112 async fn create_dir(&self, path: &Path) -> Result<()> {
113 Ok(smol::fs::create_dir_all(path).await?)
114 }
115
116 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
117 let mut open_options = smol::fs::OpenOptions::new();
118 open_options.write(true).create(true);
119 if options.overwrite {
120 open_options.truncate(true);
121 } else if !options.ignore_if_exists {
122 open_options.create_new(true);
123 }
124 open_options.open(path).await?;
125 Ok(())
126 }
127
128 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
129 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
130 if options.ignore_if_exists {
131 return Ok(());
132 } else {
133 return Err(anyhow!("{target:?} already exists"));
134 }
135 }
136
137 smol::fs::copy(source, target).await?;
138 Ok(())
139 }
140
141 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
142 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
143 if options.ignore_if_exists {
144 return Ok(());
145 } else {
146 return Err(anyhow!("{target:?} already exists"));
147 }
148 }
149
150 smol::fs::rename(source, target).await?;
151 Ok(())
152 }
153
154 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
155 let result = if options.recursive {
156 smol::fs::remove_dir_all(path).await
157 } else {
158 smol::fs::remove_dir(path).await
159 };
160 match result {
161 Ok(()) => Ok(()),
162 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
163 Ok(())
164 }
165 Err(err) => Err(err)?,
166 }
167 }
168
169 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
170 match smol::fs::remove_file(path).await {
171 Ok(()) => Ok(()),
172 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
173 Ok(())
174 }
175 Err(err) => Err(err)?,
176 }
177 }
178
179 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
180 Ok(Box::new(std::fs::File::open(path)?))
181 }
182
183 async fn load(&self, path: &Path) -> Result<String> {
184 let mut file = smol::fs::File::open(path).await?;
185 let mut text = String::new();
186 file.read_to_string(&mut text).await?;
187 Ok(text)
188 }
189
190 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
191 smol::unblock(move || {
192 let mut tmp_file = if cfg!(target_os = "linux") {
193 // Use the directory of the destination as temp dir to avoid
194 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
195 // See https://github.com/zed-industries/zed/pull/8437 for more details.
196 NamedTempFile::new_in(path.parent().unwrap_or(&paths::TEMP_DIR))
197 } else {
198 NamedTempFile::new()
199 }?;
200 tmp_file.write_all(data.as_bytes())?;
201 tmp_file.persist(path)?;
202 Ok::<(), anyhow::Error>(())
203 })
204 .await?;
205
206 Ok(())
207 }
208
209 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
210 let buffer_size = text.summary().len.min(10 * 1024);
211 if let Some(path) = path.parent() {
212 self.create_dir(path).await?;
213 }
214 let file = smol::fs::File::create(path).await?;
215 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
216 for chunk in chunks(text, line_ending) {
217 writer.write_all(chunk.as_bytes()).await?;
218 }
219 writer.flush().await?;
220 Ok(())
221 }
222
223 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
224 Ok(smol::fs::canonicalize(path).await?)
225 }
226
227 async fn is_file(&self, path: &Path) -> bool {
228 smol::fs::metadata(path)
229 .await
230 .map_or(false, |metadata| metadata.is_file())
231 }
232
233 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
234 let symlink_metadata = match smol::fs::symlink_metadata(path).await {
235 Ok(metadata) => metadata,
236 Err(err) => {
237 return match (err.kind(), err.raw_os_error()) {
238 (io::ErrorKind::NotFound, _) => Ok(None),
239 (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
240 _ => Err(anyhow::Error::new(err)),
241 }
242 }
243 };
244
245 let is_symlink = symlink_metadata.file_type().is_symlink();
246 let metadata = if is_symlink {
247 smol::fs::metadata(path).await?
248 } else {
249 symlink_metadata
250 };
251
252 #[cfg(unix)]
253 let inode = metadata.ino();
254
255 #[cfg(windows)]
256 let inode = file_id(path).await?;
257
258 Ok(Some(Metadata {
259 inode,
260 mtime: metadata.modified().unwrap(),
261 is_symlink,
262 is_dir: metadata.file_type().is_dir(),
263 }))
264 }
265
266 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
267 let path = smol::fs::read_link(path).await?;
268 Ok(path)
269 }
270
271 async fn read_dir(
272 &self,
273 path: &Path,
274 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
275 let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
276 Ok(entry) => Ok(entry.path()),
277 Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
278 });
279 Ok(Box::pin(result))
280 }
281
282 #[cfg(target_os = "macos")]
283 async fn watch(
284 &self,
285 path: &Path,
286 latency: Duration,
287 ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
288 let (tx, rx) = smol::channel::unbounded();
289 let (stream, handle) = EventStream::new(&[path], latency);
290 std::thread::spawn(move || {
291 stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
292 });
293 Box::pin(rx.chain(futures::stream::once(async move {
294 drop(handle);
295 vec![]
296 })))
297 }
298
299 #[cfg(not(target_os = "macos"))]
300 async fn watch(
301 &self,
302 path: &Path,
303 latency: Duration,
304 ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
305 let (tx, rx) = smol::channel::unbounded();
306
307 if !path.exists() {
308 log::error!("watch path does not exist: {}", path.display());
309 return Box::pin(rx);
310 }
311
312 let mut watcher =
313 notify::recommended_watcher(move |res: Result<notify::Event, _>| match res {
314 Ok(event) => {
315 let flags = match event.kind {
316 // ITEM_REMOVED is currently the only flag we care about
317 EventKind::Remove(_) => StreamFlags::ITEM_REMOVED,
318 _ => StreamFlags::NONE,
319 };
320 let events = event
321 .paths
322 .into_iter()
323 .map(|path| Event {
324 event_id: 0,
325 flags,
326 path,
327 })
328 .collect::<Vec<_>>();
329 let _ = tx.try_send(events);
330 }
331 Err(err) => {
332 log::error!("watch error: {}", err);
333 }
334 })
335 .unwrap();
336
337 watcher
338 .configure(Config::default().with_poll_interval(latency))
339 .unwrap();
340
341 watcher
342 .watch(path, notify::RecursiveMode::Recursive)
343 .unwrap();
344
345 Box::pin(rx)
346 }
347
348 fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
349 LibGitRepository::open(&dotgit_path)
350 .log_err()
351 .and_then::<Arc<Mutex<dyn GitRepository>>, _>(|libgit_repository| {
352 Some(Arc::new(Mutex::new(libgit_repository)))
353 })
354 }
355
356 fn is_fake(&self) -> bool {
357 false
358 }
359
360 /// Checks whether the file system is case sensitive by attempting to create two files
361 /// that have the same name except for the casing.
362 ///
363 /// It creates both files in a temporary directory it removes at the end.
364 async fn is_case_sensitive(&self) -> Result<bool> {
365 let temp_dir = TempDir::new()?;
366 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
367 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
368
369 let create_opts = CreateOptions {
370 overwrite: false,
371 ignore_if_exists: false,
372 };
373
374 // Create file1
375 self.create_file(&test_file_1, create_opts).await?;
376
377 // Now check whether it's possible to create file2
378 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
379 Ok(_) => Ok(true),
380 Err(e) => {
381 if let Some(io_error) = e.downcast_ref::<io::Error>() {
382 if io_error.kind() == io::ErrorKind::AlreadyExists {
383 Ok(false)
384 } else {
385 Err(e)
386 }
387 } else {
388 Err(e)
389 }
390 }
391 };
392
393 temp_dir.close()?;
394 case_sensitive
395 }
396
397 #[cfg(any(test, feature = "test-support"))]
398 fn as_fake(&self) -> &FakeFs {
399 panic!("called `RealFs::as_fake`")
400 }
401}
402
403pub fn fs_events_paths(events: Vec<Event>) -> Vec<PathBuf> {
404 events.into_iter().map(|event| event.path).collect()
405}
406
407#[cfg(any(test, feature = "test-support"))]
408pub struct FakeFs {
409 // Use an unfair lock to ensure tests are deterministic.
410 state: Mutex<FakeFsState>,
411 executor: gpui::BackgroundExecutor,
412}
413
414#[cfg(any(test, feature = "test-support"))]
415struct FakeFsState {
416 root: Arc<Mutex<FakeFsEntry>>,
417 next_inode: u64,
418 next_mtime: SystemTime,
419 event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
420 events_paused: bool,
421 buffered_events: Vec<fsevent::Event>,
422 metadata_call_count: usize,
423 read_dir_call_count: usize,
424}
425
426#[cfg(any(test, feature = "test-support"))]
427#[derive(Debug)]
428enum FakeFsEntry {
429 File {
430 inode: u64,
431 mtime: SystemTime,
432 content: String,
433 },
434 Dir {
435 inode: u64,
436 mtime: SystemTime,
437 entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
438 git_repo_state: Option<Arc<Mutex<repository::FakeGitRepositoryState>>>,
439 },
440 Symlink {
441 target: PathBuf,
442 },
443}
444
445#[cfg(any(test, feature = "test-support"))]
446impl FakeFsState {
447 fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
448 Ok(self
449 .try_read_path(target, true)
450 .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
451 .0)
452 }
453
454 fn try_read_path<'a>(
455 &'a self,
456 target: &Path,
457 follow_symlink: bool,
458 ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
459 let mut path = target.to_path_buf();
460 let mut canonical_path = PathBuf::new();
461 let mut entry_stack = Vec::new();
462 'outer: loop {
463 let mut path_components = path.components().peekable();
464 while let Some(component) = path_components.next() {
465 match component {
466 Component::Prefix(_) => panic!("prefix paths aren't supported"),
467 Component::RootDir => {
468 entry_stack.clear();
469 entry_stack.push(self.root.clone());
470 canonical_path.clear();
471 canonical_path.push("/");
472 }
473 Component::CurDir => {}
474 Component::ParentDir => {
475 entry_stack.pop()?;
476 canonical_path.pop();
477 }
478 Component::Normal(name) => {
479 let current_entry = entry_stack.last().cloned()?;
480 let current_entry = current_entry.lock();
481 if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
482 let entry = entries.get(name.to_str().unwrap()).cloned()?;
483 if path_components.peek().is_some() || follow_symlink {
484 let entry = entry.lock();
485 if let FakeFsEntry::Symlink { target, .. } = &*entry {
486 let mut target = target.clone();
487 target.extend(path_components);
488 path = target;
489 continue 'outer;
490 }
491 }
492 entry_stack.push(entry.clone());
493 canonical_path.push(name);
494 } else {
495 return None;
496 }
497 }
498 }
499 }
500 break;
501 }
502 Some((entry_stack.pop()?, canonical_path))
503 }
504
505 fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
506 where
507 Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
508 {
509 let path = normalize_path(path);
510 let filename = path
511 .file_name()
512 .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
513 let parent_path = path.parent().unwrap();
514
515 let parent = self.read_path(parent_path)?;
516 let mut parent = parent.lock();
517 let new_entry = parent
518 .dir_entries(parent_path)?
519 .entry(filename.to_str().unwrap().into());
520 callback(new_entry)
521 }
522
523 fn emit_event<I, T>(&mut self, paths: I)
524 where
525 I: IntoIterator<Item = T>,
526 T: Into<PathBuf>,
527 {
528 self.buffered_events
529 .extend(paths.into_iter().map(|path| fsevent::Event {
530 event_id: 0,
531 flags: fsevent::StreamFlags::empty(),
532 path: path.into(),
533 }));
534
535 if !self.events_paused {
536 self.flush_events(self.buffered_events.len());
537 }
538 }
539
540 fn flush_events(&mut self, mut count: usize) {
541 count = count.min(self.buffered_events.len());
542 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
543 self.event_txs.retain(|tx| {
544 let _ = tx.try_send(events.clone());
545 !tx.is_closed()
546 });
547 }
548}
549
550#[cfg(any(test, feature = "test-support"))]
551lazy_static::lazy_static! {
552 pub static ref FS_DOT_GIT: &'static OsStr = OsStr::new(".git");
553}
554
555#[cfg(any(test, feature = "test-support"))]
556impl FakeFs {
557 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
558 Arc::new(Self {
559 executor,
560 state: Mutex::new(FakeFsState {
561 root: Arc::new(Mutex::new(FakeFsEntry::Dir {
562 inode: 0,
563 mtime: SystemTime::UNIX_EPOCH,
564 entries: Default::default(),
565 git_repo_state: None,
566 })),
567 next_mtime: SystemTime::UNIX_EPOCH,
568 next_inode: 1,
569 event_txs: Default::default(),
570 buffered_events: Vec::new(),
571 events_paused: false,
572 read_dir_call_count: 0,
573 metadata_call_count: 0,
574 }),
575 })
576 }
577
578 pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
579 self.write_file_internal(path, content).unwrap()
580 }
581
582 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
583 let mut state = self.state.lock();
584 let path = path.as_ref();
585 let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
586 state
587 .write_path(path.as_ref(), move |e| match e {
588 btree_map::Entry::Vacant(e) => {
589 e.insert(file);
590 Ok(())
591 }
592 btree_map::Entry::Occupied(mut e) => {
593 *e.get_mut() = file;
594 Ok(())
595 }
596 })
597 .unwrap();
598 state.emit_event(&[path]);
599 }
600
601 pub fn write_file_internal(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
602 let mut state = self.state.lock();
603 let path = path.as_ref();
604 let inode = state.next_inode;
605 let mtime = state.next_mtime;
606 state.next_inode += 1;
607 state.next_mtime += Duration::from_nanos(1);
608 let file = Arc::new(Mutex::new(FakeFsEntry::File {
609 inode,
610 mtime,
611 content,
612 }));
613 state.write_path(path, move |entry| {
614 match entry {
615 btree_map::Entry::Vacant(e) => {
616 e.insert(file);
617 }
618 btree_map::Entry::Occupied(mut e) => {
619 *e.get_mut() = file;
620 }
621 }
622 Ok(())
623 })?;
624 state.emit_event(&[path]);
625 Ok(())
626 }
627
628 pub fn pause_events(&self) {
629 self.state.lock().events_paused = true;
630 }
631
632 pub fn buffered_event_count(&self) -> usize {
633 self.state.lock().buffered_events.len()
634 }
635
636 pub fn flush_events(&self, count: usize) {
637 self.state.lock().flush_events(count);
638 }
639
640 #[must_use]
641 pub fn insert_tree<'a>(
642 &'a self,
643 path: impl 'a + AsRef<Path> + Send,
644 tree: serde_json::Value,
645 ) -> futures::future::BoxFuture<'a, ()> {
646 use futures::FutureExt as _;
647 use serde_json::Value::*;
648
649 async move {
650 let path = path.as_ref();
651
652 match tree {
653 Object(map) => {
654 self.create_dir(path).await.unwrap();
655 for (name, contents) in map {
656 let mut path = PathBuf::from(path);
657 path.push(name);
658 self.insert_tree(&path, contents).await;
659 }
660 }
661 Null => {
662 self.create_dir(path).await.unwrap();
663 }
664 String(contents) => {
665 self.insert_file(&path, contents).await;
666 }
667 _ => {
668 panic!("JSON object must contain only objects, strings, or null");
669 }
670 }
671 }
672 .boxed()
673 }
674
675 pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
676 where
677 F: FnOnce(&mut FakeGitRepositoryState),
678 {
679 let mut state = self.state.lock();
680 let entry = state.read_path(dot_git).unwrap();
681 let mut entry = entry.lock();
682
683 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
684 let repo_state = git_repo_state.get_or_insert_with(Default::default);
685 let mut repo_state = repo_state.lock();
686
687 f(&mut repo_state);
688
689 if emit_git_event {
690 state.emit_event([dot_git]);
691 }
692 } else {
693 panic!("not a directory");
694 }
695 }
696
697 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
698 self.with_git_state(dot_git, true, |state| {
699 state.branch_name = branch.map(Into::into)
700 })
701 }
702
703 pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
704 self.with_git_state(dot_git, true, |state| {
705 state.index_contents.clear();
706 state.index_contents.extend(
707 head_state
708 .iter()
709 .map(|(path, content)| (path.to_path_buf(), content.clone())),
710 );
711 });
712 }
713
714 pub fn set_status_for_repo_via_working_copy_change(
715 &self,
716 dot_git: &Path,
717 statuses: &[(&Path, GitFileStatus)],
718 ) {
719 self.with_git_state(dot_git, false, |state| {
720 state.worktree_statuses.clear();
721 state.worktree_statuses.extend(
722 statuses
723 .iter()
724 .map(|(path, content)| ((**path).into(), content.clone())),
725 );
726 });
727 self.state.lock().emit_event(
728 statuses
729 .iter()
730 .map(|(path, _)| dot_git.parent().unwrap().join(path)),
731 );
732 }
733
734 pub fn set_status_for_repo_via_git_operation(
735 &self,
736 dot_git: &Path,
737 statuses: &[(&Path, GitFileStatus)],
738 ) {
739 self.with_git_state(dot_git, true, |state| {
740 state.worktree_statuses.clear();
741 state.worktree_statuses.extend(
742 statuses
743 .iter()
744 .map(|(path, content)| ((**path).into(), content.clone())),
745 );
746 });
747 }
748
749 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
750 let mut result = Vec::new();
751 let mut queue = collections::VecDeque::new();
752 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
753 while let Some((path, entry)) = queue.pop_front() {
754 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
755 for (name, entry) in entries {
756 queue.push_back((path.join(name), entry.clone()));
757 }
758 }
759 if include_dot_git
760 || !path
761 .components()
762 .any(|component| component.as_os_str() == *FS_DOT_GIT)
763 {
764 result.push(path);
765 }
766 }
767 result
768 }
769
770 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
771 let mut result = Vec::new();
772 let mut queue = collections::VecDeque::new();
773 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
774 while let Some((path, entry)) = queue.pop_front() {
775 if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
776 for (name, entry) in entries {
777 queue.push_back((path.join(name), entry.clone()));
778 }
779 if include_dot_git
780 || !path
781 .components()
782 .any(|component| component.as_os_str() == *FS_DOT_GIT)
783 {
784 result.push(path);
785 }
786 }
787 }
788 result
789 }
790
791 pub fn files(&self) -> Vec<PathBuf> {
792 let mut result = Vec::new();
793 let mut queue = collections::VecDeque::new();
794 queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
795 while let Some((path, entry)) = queue.pop_front() {
796 let e = entry.lock();
797 match &*e {
798 FakeFsEntry::File { .. } => result.push(path),
799 FakeFsEntry::Dir { entries, .. } => {
800 for (name, entry) in entries {
801 queue.push_back((path.join(name), entry.clone()));
802 }
803 }
804 FakeFsEntry::Symlink { .. } => {}
805 }
806 }
807 result
808 }
809
810 /// How many `read_dir` calls have been issued.
811 pub fn read_dir_call_count(&self) -> usize {
812 self.state.lock().read_dir_call_count
813 }
814
815 /// How many `metadata` calls have been issued.
816 pub fn metadata_call_count(&self) -> usize {
817 self.state.lock().metadata_call_count
818 }
819
820 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
821 self.executor.simulate_random_delay()
822 }
823}
824
825#[cfg(any(test, feature = "test-support"))]
826impl FakeFsEntry {
827 fn is_file(&self) -> bool {
828 matches!(self, Self::File { .. })
829 }
830
831 fn is_symlink(&self) -> bool {
832 matches!(self, Self::Symlink { .. })
833 }
834
835 fn file_content(&self, path: &Path) -> Result<&String> {
836 if let Self::File { content, .. } = self {
837 Ok(content)
838 } else {
839 Err(anyhow!("not a file: {}", path.display()))
840 }
841 }
842
843 fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
844 if let Self::File { content, mtime, .. } = self {
845 *mtime = SystemTime::now();
846 *content = new_content;
847 Ok(())
848 } else {
849 Err(anyhow!("not a file: {}", path.display()))
850 }
851 }
852
853 fn dir_entries(
854 &mut self,
855 path: &Path,
856 ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
857 if let Self::Dir { entries, .. } = self {
858 Ok(entries)
859 } else {
860 Err(anyhow!("not a directory: {}", path.display()))
861 }
862 }
863}
864
865#[cfg(any(test, feature = "test-support"))]
866#[async_trait::async_trait]
867impl Fs for FakeFs {
868 async fn create_dir(&self, path: &Path) -> Result<()> {
869 self.simulate_random_delay().await;
870
871 let mut created_dirs = Vec::new();
872 let mut cur_path = PathBuf::new();
873 for component in path.components() {
874 let mut state = self.state.lock();
875 cur_path.push(component);
876 if cur_path == Path::new("/") {
877 continue;
878 }
879
880 let inode = state.next_inode;
881 let mtime = state.next_mtime;
882 state.next_mtime += Duration::from_nanos(1);
883 state.next_inode += 1;
884 state.write_path(&cur_path, |entry| {
885 entry.or_insert_with(|| {
886 created_dirs.push(cur_path.clone());
887 Arc::new(Mutex::new(FakeFsEntry::Dir {
888 inode,
889 mtime,
890 entries: Default::default(),
891 git_repo_state: None,
892 }))
893 });
894 Ok(())
895 })?
896 }
897
898 self.state.lock().emit_event(&created_dirs);
899 Ok(())
900 }
901
902 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
903 self.simulate_random_delay().await;
904 let mut state = self.state.lock();
905 let inode = state.next_inode;
906 let mtime = state.next_mtime;
907 state.next_mtime += Duration::from_nanos(1);
908 state.next_inode += 1;
909 let file = Arc::new(Mutex::new(FakeFsEntry::File {
910 inode,
911 mtime,
912 content: String::new(),
913 }));
914 state.write_path(path, |entry| {
915 match entry {
916 btree_map::Entry::Occupied(mut e) => {
917 if options.overwrite {
918 *e.get_mut() = file;
919 } else if !options.ignore_if_exists {
920 return Err(anyhow!("path already exists: {}", path.display()));
921 }
922 }
923 btree_map::Entry::Vacant(e) => {
924 e.insert(file);
925 }
926 }
927 Ok(())
928 })?;
929 state.emit_event(&[path]);
930 Ok(())
931 }
932
933 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
934 self.simulate_random_delay().await;
935
936 let old_path = normalize_path(old_path);
937 let new_path = normalize_path(new_path);
938
939 let mut state = self.state.lock();
940 let moved_entry = state.write_path(&old_path, |e| {
941 if let btree_map::Entry::Occupied(e) = e {
942 Ok(e.get().clone())
943 } else {
944 Err(anyhow!("path does not exist: {}", &old_path.display()))
945 }
946 })?;
947
948 state.write_path(&new_path, |e| {
949 match e {
950 btree_map::Entry::Occupied(mut e) => {
951 if options.overwrite {
952 *e.get_mut() = moved_entry;
953 } else if !options.ignore_if_exists {
954 return Err(anyhow!("path already exists: {}", new_path.display()));
955 }
956 }
957 btree_map::Entry::Vacant(e) => {
958 e.insert(moved_entry);
959 }
960 }
961 Ok(())
962 })?;
963
964 state
965 .write_path(&old_path, |e| {
966 if let btree_map::Entry::Occupied(e) = e {
967 Ok(e.remove())
968 } else {
969 unreachable!()
970 }
971 })
972 .unwrap();
973
974 state.emit_event(&[old_path, new_path]);
975 Ok(())
976 }
977
978 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
979 self.simulate_random_delay().await;
980
981 let source = normalize_path(source);
982 let target = normalize_path(target);
983 let mut state = self.state.lock();
984 let mtime = state.next_mtime;
985 let inode = util::post_inc(&mut state.next_inode);
986 state.next_mtime += Duration::from_nanos(1);
987 let source_entry = state.read_path(&source)?;
988 let content = source_entry.lock().file_content(&source)?.clone();
989 let entry = state.write_path(&target, |e| match e {
990 btree_map::Entry::Occupied(e) => {
991 if options.overwrite {
992 Ok(Some(e.get().clone()))
993 } else if !options.ignore_if_exists {
994 return Err(anyhow!("{target:?} already exists"));
995 } else {
996 Ok(None)
997 }
998 }
999 btree_map::Entry::Vacant(e) => Ok(Some(
1000 e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1001 inode,
1002 mtime,
1003 content: String::new(),
1004 })))
1005 .clone(),
1006 )),
1007 })?;
1008 if let Some(entry) = entry {
1009 entry.lock().set_file_content(&target, content)?;
1010 }
1011 state.emit_event(&[target]);
1012 Ok(())
1013 }
1014
1015 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1016 self.simulate_random_delay().await;
1017
1018 let path = normalize_path(path);
1019 let parent_path = path
1020 .parent()
1021 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1022 let base_name = path.file_name().unwrap();
1023
1024 let mut state = self.state.lock();
1025 let parent_entry = state.read_path(parent_path)?;
1026 let mut parent_entry = parent_entry.lock();
1027 let entry = parent_entry
1028 .dir_entries(parent_path)?
1029 .entry(base_name.to_str().unwrap().into());
1030
1031 match entry {
1032 btree_map::Entry::Vacant(_) => {
1033 if !options.ignore_if_not_exists {
1034 return Err(anyhow!("{path:?} does not exist"));
1035 }
1036 }
1037 btree_map::Entry::Occupied(e) => {
1038 {
1039 let mut entry = e.get().lock();
1040 let children = entry.dir_entries(&path)?;
1041 if !options.recursive && !children.is_empty() {
1042 return Err(anyhow!("{path:?} is not empty"));
1043 }
1044 }
1045 e.remove();
1046 }
1047 }
1048 state.emit_event(&[path]);
1049 Ok(())
1050 }
1051
1052 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1053 self.simulate_random_delay().await;
1054
1055 let path = normalize_path(path);
1056 let parent_path = path
1057 .parent()
1058 .ok_or_else(|| anyhow!("cannot remove the root"))?;
1059 let base_name = path.file_name().unwrap();
1060 let mut state = self.state.lock();
1061 let parent_entry = state.read_path(parent_path)?;
1062 let mut parent_entry = parent_entry.lock();
1063 let entry = parent_entry
1064 .dir_entries(parent_path)?
1065 .entry(base_name.to_str().unwrap().into());
1066 match entry {
1067 btree_map::Entry::Vacant(_) => {
1068 if !options.ignore_if_not_exists {
1069 return Err(anyhow!("{path:?} does not exist"));
1070 }
1071 }
1072 btree_map::Entry::Occupied(e) => {
1073 e.get().lock().file_content(&path)?;
1074 e.remove();
1075 }
1076 }
1077 state.emit_event(&[path]);
1078 Ok(())
1079 }
1080
1081 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1082 let text = self.load(path).await?;
1083 Ok(Box::new(io::Cursor::new(text)))
1084 }
1085
1086 async fn load(&self, path: &Path) -> Result<String> {
1087 let path = normalize_path(path);
1088 self.simulate_random_delay().await;
1089 let state = self.state.lock();
1090 let entry = state.read_path(&path)?;
1091 let entry = entry.lock();
1092 entry.file_content(&path).cloned()
1093 }
1094
1095 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1096 self.simulate_random_delay().await;
1097 let path = normalize_path(path.as_path());
1098 self.write_file_internal(path, data.to_string())?;
1099
1100 Ok(())
1101 }
1102
1103 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1104 self.simulate_random_delay().await;
1105 let path = normalize_path(path);
1106 let content = chunks(text, line_ending).collect();
1107 if let Some(path) = path.parent() {
1108 self.create_dir(path).await?;
1109 }
1110 self.write_file_internal(path, content)?;
1111 Ok(())
1112 }
1113
1114 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1115 let path = normalize_path(path);
1116 self.simulate_random_delay().await;
1117 let state = self.state.lock();
1118 if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1119 Ok(canonical_path)
1120 } else {
1121 Err(anyhow!("path does not exist: {}", path.display()))
1122 }
1123 }
1124
1125 async fn is_file(&self, path: &Path) -> bool {
1126 let path = normalize_path(path);
1127 self.simulate_random_delay().await;
1128 let state = self.state.lock();
1129 if let Some((entry, _)) = state.try_read_path(&path, true) {
1130 entry.lock().is_file()
1131 } else {
1132 false
1133 }
1134 }
1135
1136 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1137 self.simulate_random_delay().await;
1138 let path = normalize_path(path);
1139 let mut state = self.state.lock();
1140 state.metadata_call_count += 1;
1141 if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1142 let is_symlink = entry.lock().is_symlink();
1143 if is_symlink {
1144 if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1145 entry = e;
1146 } else {
1147 return Ok(None);
1148 }
1149 }
1150
1151 let entry = entry.lock();
1152 Ok(Some(match &*entry {
1153 FakeFsEntry::File { inode, mtime, .. } => Metadata {
1154 inode: *inode,
1155 mtime: *mtime,
1156 is_dir: false,
1157 is_symlink,
1158 },
1159 FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1160 inode: *inode,
1161 mtime: *mtime,
1162 is_dir: true,
1163 is_symlink,
1164 },
1165 FakeFsEntry::Symlink { .. } => unreachable!(),
1166 }))
1167 } else {
1168 Ok(None)
1169 }
1170 }
1171
1172 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1173 self.simulate_random_delay().await;
1174 let path = normalize_path(path);
1175 let state = self.state.lock();
1176 if let Some((entry, _)) = state.try_read_path(&path, false) {
1177 let entry = entry.lock();
1178 if let FakeFsEntry::Symlink { target } = &*entry {
1179 Ok(target.clone())
1180 } else {
1181 Err(anyhow!("not a symlink: {}", path.display()))
1182 }
1183 } else {
1184 Err(anyhow!("path does not exist: {}", path.display()))
1185 }
1186 }
1187
1188 async fn read_dir(
1189 &self,
1190 path: &Path,
1191 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1192 self.simulate_random_delay().await;
1193 let path = normalize_path(path);
1194 let mut state = self.state.lock();
1195 state.read_dir_call_count += 1;
1196 let entry = state.read_path(&path)?;
1197 let mut entry = entry.lock();
1198 let children = entry.dir_entries(&path)?;
1199 let paths = children
1200 .keys()
1201 .map(|file_name| Ok(path.join(file_name)))
1202 .collect::<Vec<_>>();
1203 Ok(Box::pin(futures::stream::iter(paths)))
1204 }
1205
1206 async fn watch(
1207 &self,
1208 path: &Path,
1209 _: Duration,
1210 ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
1211 self.simulate_random_delay().await;
1212 let (tx, rx) = smol::channel::unbounded();
1213 self.state.lock().event_txs.push(tx);
1214 let path = path.to_path_buf();
1215 let executor = self.executor.clone();
1216 Box::pin(futures::StreamExt::filter(rx, move |events| {
1217 let result = events.iter().any(|event| event.path.starts_with(&path));
1218 let executor = executor.clone();
1219 async move {
1220 executor.simulate_random_delay().await;
1221 result
1222 }
1223 }))
1224 }
1225
1226 fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
1227 let state = self.state.lock();
1228 let entry = state.read_path(abs_dot_git).unwrap();
1229 let mut entry = entry.lock();
1230 if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1231 let state = git_repo_state
1232 .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
1233 .clone();
1234 Some(repository::FakeGitRepository::open(state))
1235 } else {
1236 None
1237 }
1238 }
1239
1240 fn is_fake(&self) -> bool {
1241 true
1242 }
1243
1244 async fn is_case_sensitive(&self) -> Result<bool> {
1245 Ok(true)
1246 }
1247
1248 #[cfg(any(test, feature = "test-support"))]
1249 fn as_fake(&self) -> &FakeFs {
1250 self
1251 }
1252}
1253
1254fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1255 rope.chunks().flat_map(move |chunk| {
1256 let mut newline = false;
1257 chunk.split('\n').flat_map(move |line| {
1258 let ending = if newline {
1259 Some(line_ending.as_str())
1260 } else {
1261 None
1262 };
1263 newline = true;
1264 ending.into_iter().chain([line])
1265 })
1266 })
1267}
1268
1269pub fn normalize_path(path: &Path) -> PathBuf {
1270 let mut components = path.components().peekable();
1271 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1272 components.next();
1273 PathBuf::from(c.as_os_str())
1274 } else {
1275 PathBuf::new()
1276 };
1277
1278 for component in components {
1279 match component {
1280 Component::Prefix(..) => unreachable!(),
1281 Component::RootDir => {
1282 ret.push(component.as_os_str());
1283 }
1284 Component::CurDir => {}
1285 Component::ParentDir => {
1286 ret.pop();
1287 }
1288 Component::Normal(c) => {
1289 ret.push(c);
1290 }
1291 }
1292 }
1293 ret
1294}
1295
1296pub fn copy_recursive<'a>(
1297 fs: &'a dyn Fs,
1298 source: &'a Path,
1299 target: &'a Path,
1300 options: CopyOptions,
1301) -> BoxFuture<'a, Result<()>> {
1302 use futures::future::FutureExt;
1303
1304 async move {
1305 let metadata = fs
1306 .metadata(source)
1307 .await?
1308 .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1309 if metadata.is_dir {
1310 if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1311 if options.ignore_if_exists {
1312 return Ok(());
1313 } else {
1314 return Err(anyhow!("{target:?} already exists"));
1315 }
1316 }
1317
1318 let _ = fs
1319 .remove_dir(
1320 target,
1321 RemoveOptions {
1322 recursive: true,
1323 ignore_if_not_exists: true,
1324 },
1325 )
1326 .await;
1327 fs.create_dir(target).await?;
1328 let mut children = fs.read_dir(source).await?;
1329 while let Some(child_path) = children.next().await {
1330 if let Ok(child_path) = child_path {
1331 if let Some(file_name) = child_path.file_name() {
1332 let child_target_path = target.join(file_name);
1333 copy_recursive(fs, &child_path, &child_target_path, options).await?;
1334 }
1335 }
1336 }
1337
1338 Ok(())
1339 } else {
1340 fs.copy_file(source, target, options).await
1341 }
1342 }
1343 .boxed()
1344}
1345
1346// todo(windows)
1347// can we get file id not open the file twice?
1348// https://github.com/rust-lang/rust/issues/63010
1349#[cfg(target_os = "windows")]
1350async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
1351 use std::os::windows::io::AsRawHandle;
1352
1353 use smol::fs::windows::OpenOptionsExt;
1354 use windows_sys::Win32::{
1355 Foundation::HANDLE,
1356 Storage::FileSystem::{
1357 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
1358 },
1359 };
1360
1361 let file = smol::fs::OpenOptions::new()
1362 .read(true)
1363 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1364 .open(path)
1365 .await?;
1366
1367 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
1368 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
1369 // This function supports Windows XP+
1370 smol::unblock(move || {
1371 let ret = unsafe { GetFileInformationByHandle(file.as_raw_handle() as HANDLE, &mut info) };
1372 if ret == 0 {
1373 return Err(anyhow!(format!("{}", std::io::Error::last_os_error())));
1374 };
1375
1376 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
1377 })
1378 .await
1379}
1380
1381#[cfg(test)]
1382mod tests {
1383 use super::*;
1384 use gpui::BackgroundExecutor;
1385 use serde_json::json;
1386
1387 #[gpui::test]
1388 async fn test_fake_fs(executor: BackgroundExecutor) {
1389 let fs = FakeFs::new(executor.clone());
1390 fs.insert_tree(
1391 "/root",
1392 json!({
1393 "dir1": {
1394 "a": "A",
1395 "b": "B"
1396 },
1397 "dir2": {
1398 "c": "C",
1399 "dir3": {
1400 "d": "D"
1401 }
1402 }
1403 }),
1404 )
1405 .await;
1406
1407 assert_eq!(
1408 fs.files(),
1409 vec![
1410 PathBuf::from("/root/dir1/a"),
1411 PathBuf::from("/root/dir1/b"),
1412 PathBuf::from("/root/dir2/c"),
1413 PathBuf::from("/root/dir2/dir3/d"),
1414 ]
1415 );
1416
1417 fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
1418 .await;
1419
1420 assert_eq!(
1421 fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1422 .await
1423 .unwrap(),
1424 PathBuf::from("/root/dir2/dir3"),
1425 );
1426 assert_eq!(
1427 fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1428 .await
1429 .unwrap(),
1430 PathBuf::from("/root/dir2/dir3/d"),
1431 );
1432 assert_eq!(
1433 fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1434 "D",
1435 );
1436 }
1437}