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