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