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