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