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