fs.rs

   1#[cfg(target_os = "macos")]
   2mod mac_watcher;
   3
   4#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   5pub mod linux_watcher;
   6
   7use anyhow::{anyhow, Result};
   8use git::GitHostingProviderRegistry;
   9
  10#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  11use ashpd::desktop::trash;
  12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  13use std::fs::File;
  14#[cfg(unix)]
  15use std::os::fd::AsFd;
  16#[cfg(unix)]
  17use std::os::fd::AsRawFd;
  18
  19#[cfg(unix)]
  20use std::os::unix::fs::MetadataExt;
  21
  22#[cfg(unix)]
  23use std::os::unix::fs::FileTypeExt;
  24
  25use async_tar::Archive;
  26use futures::{future::BoxFuture, AsyncRead, Stream, StreamExt};
  27use git::repository::{GitRepository, RealGitRepository};
  28use gpui::{AppContext, Global, ReadGlobal};
  29use rope::Rope;
  30use smol::io::AsyncWriteExt;
  31use std::{
  32    io::{self, Write},
  33    path::{Component, Path, PathBuf},
  34    pin::Pin,
  35    sync::Arc,
  36    time::{Duration, SystemTime},
  37};
  38use tempfile::{NamedTempFile, TempDir};
  39use text::LineEnding;
  40use util::ResultExt;
  41
  42#[cfg(any(test, feature = "test-support"))]
  43use collections::{btree_map, BTreeMap};
  44#[cfg(any(test, feature = "test-support"))]
  45use git::repository::{FakeGitRepositoryState, GitFileStatus};
  46#[cfg(any(test, feature = "test-support"))]
  47use parking_lot::Mutex;
  48#[cfg(any(test, feature = "test-support"))]
  49use smol::io::AsyncReadExt;
  50#[cfg(any(test, feature = "test-support"))]
  51use std::ffi::OsStr;
  52
  53pub trait Watcher: Send + Sync {
  54    fn add(&self, path: &Path) -> Result<()>;
  55    fn remove(&self, path: &Path) -> Result<()>;
  56}
  57
  58#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  59pub enum PathEventKind {
  60    Removed,
  61    Created,
  62    Changed,
  63}
  64
  65#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  66pub struct PathEvent {
  67    pub path: PathBuf,
  68    pub kind: Option<PathEventKind>,
  69}
  70
  71impl From<PathEvent> for PathBuf {
  72    fn from(event: PathEvent) -> Self {
  73        event.path
  74    }
  75}
  76
  77#[async_trait::async_trait]
  78pub trait Fs: Send + Sync {
  79    async fn create_dir(&self, path: &Path) -> Result<()>;
  80    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  81    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  82    async fn create_file_with(
  83        &self,
  84        path: &Path,
  85        content: Pin<&mut (dyn AsyncRead + Send)>,
  86    ) -> Result<()>;
  87    async fn extract_tar_file(
  88        &self,
  89        path: &Path,
  90        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
  91    ) -> Result<()>;
  92    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
  93    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
  94    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  95    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
  96        self.remove_dir(path, options).await
  97    }
  98    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  99    async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 100        self.remove_file(path, options).await
 101    }
 102    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
 103    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
 104    async fn load(&self, path: &Path) -> Result<String> {
 105        Ok(String::from_utf8(self.load_bytes(path).await?)?)
 106    }
 107    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
 108    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 109    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
 110    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 111    async fn is_file(&self, path: &Path) -> bool;
 112    async fn is_dir(&self, path: &Path) -> bool;
 113    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 114    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 115    async fn read_dir(
 116        &self,
 117        path: &Path,
 118    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 119
 120    async fn watch(
 121        &self,
 122        path: &Path,
 123        latency: Duration,
 124    ) -> (
 125        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 126        Arc<dyn Watcher>,
 127    );
 128
 129    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>>;
 130    fn is_fake(&self) -> bool;
 131    async fn is_case_sensitive(&self) -> Result<bool>;
 132
 133    #[cfg(any(test, feature = "test-support"))]
 134    fn as_fake(&self) -> &FakeFs {
 135        panic!("called as_fake on a real fs");
 136    }
 137}
 138
 139struct GlobalFs(Arc<dyn Fs>);
 140
 141impl Global for GlobalFs {}
 142
 143impl dyn Fs {
 144    /// Returns the global [`Fs`].
 145    pub fn global(cx: &AppContext) -> Arc<Self> {
 146        GlobalFs::global(cx).0.clone()
 147    }
 148
 149    /// Sets the global [`Fs`].
 150    pub fn set_global(fs: Arc<Self>, cx: &mut AppContext) {
 151        cx.set_global(GlobalFs(fs));
 152    }
 153}
 154
 155#[derive(Copy, Clone, Default)]
 156pub struct CreateOptions {
 157    pub overwrite: bool,
 158    pub ignore_if_exists: bool,
 159}
 160
 161#[derive(Copy, Clone, Default)]
 162pub struct CopyOptions {
 163    pub overwrite: bool,
 164    pub ignore_if_exists: bool,
 165}
 166
 167#[derive(Copy, Clone, Default)]
 168pub struct RenameOptions {
 169    pub overwrite: bool,
 170    pub ignore_if_exists: bool,
 171}
 172
 173#[derive(Copy, Clone, Default)]
 174pub struct RemoveOptions {
 175    pub recursive: bool,
 176    pub ignore_if_not_exists: bool,
 177}
 178
 179#[derive(Copy, Clone, Debug)]
 180pub struct Metadata {
 181    pub inode: u64,
 182    pub mtime: SystemTime,
 183    pub is_symlink: bool,
 184    pub is_dir: bool,
 185    pub len: u64,
 186    pub is_fifo: bool,
 187}
 188
 189#[derive(Default)]
 190pub struct RealFs {
 191    git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 192    git_binary_path: Option<PathBuf>,
 193}
 194
 195pub trait FileHandle: Send + Sync + std::fmt::Debug {
 196    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
 197}
 198
 199impl FileHandle for std::fs::File {
 200    #[cfg(target_os = "macos")]
 201    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 202        use std::{
 203            ffi::{CStr, OsStr},
 204            os::unix::ffi::OsStrExt,
 205        };
 206
 207        let fd = self.as_fd();
 208        let mut path_buf: [libc::c_char; libc::PATH_MAX as usize] = [0; libc::PATH_MAX as usize];
 209
 210        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
 211        if result == -1 {
 212            anyhow::bail!("fcntl returned -1".to_string());
 213        }
 214
 215        let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr()) };
 216        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 217        Ok(path)
 218    }
 219
 220    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 221    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 222        let fd = self.as_fd();
 223        let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
 224        let new_path = std::fs::read_link(fd_path)?;
 225        if new_path
 226            .file_name()
 227            .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
 228        {
 229            anyhow::bail!("file was deleted")
 230        };
 231
 232        Ok(new_path)
 233    }
 234
 235    #[cfg(target_os = "windows")]
 236    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 237        anyhow::bail!("unimplemented")
 238    }
 239}
 240
 241pub struct RealWatcher {}
 242
 243impl RealFs {
 244    pub fn new(
 245        git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 246        git_binary_path: Option<PathBuf>,
 247    ) -> Self {
 248        Self {
 249            git_hosting_provider_registry,
 250            git_binary_path,
 251        }
 252    }
 253}
 254
 255#[async_trait::async_trait]
 256impl Fs for RealFs {
 257    async fn create_dir(&self, path: &Path) -> Result<()> {
 258        Ok(smol::fs::create_dir_all(path).await?)
 259    }
 260
 261    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 262        #[cfg(unix)]
 263        smol::fs::unix::symlink(target, path).await?;
 264
 265        #[cfg(windows)]
 266        if smol::fs::metadata(&target).await?.is_dir() {
 267            smol::fs::windows::symlink_dir(target, path).await?
 268        } else {
 269            smol::fs::windows::symlink_file(target, path).await?
 270        }
 271
 272        Ok(())
 273    }
 274
 275    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 276        let mut open_options = smol::fs::OpenOptions::new();
 277        open_options.write(true).create(true);
 278        if options.overwrite {
 279            open_options.truncate(true);
 280        } else if !options.ignore_if_exists {
 281            open_options.create_new(true);
 282        }
 283        open_options.open(path).await?;
 284        Ok(())
 285    }
 286
 287    async fn create_file_with(
 288        &self,
 289        path: &Path,
 290        content: Pin<&mut (dyn AsyncRead + Send)>,
 291    ) -> Result<()> {
 292        let mut file = smol::fs::File::create(&path).await?;
 293        futures::io::copy(content, &mut file).await?;
 294        Ok(())
 295    }
 296
 297    async fn extract_tar_file(
 298        &self,
 299        path: &Path,
 300        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 301    ) -> Result<()> {
 302        content.unpack(path).await?;
 303        Ok(())
 304    }
 305
 306    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 307        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 308            if options.ignore_if_exists {
 309                return Ok(());
 310            } else {
 311                return Err(anyhow!("{target:?} already exists"));
 312            }
 313        }
 314
 315        smol::fs::copy(source, target).await?;
 316        Ok(())
 317    }
 318
 319    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 320        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 321            if options.ignore_if_exists {
 322                return Ok(());
 323            } else {
 324                return Err(anyhow!("{target:?} already exists"));
 325            }
 326        }
 327
 328        smol::fs::rename(source, target).await?;
 329        Ok(())
 330    }
 331
 332    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 333        let result = if options.recursive {
 334            smol::fs::remove_dir_all(path).await
 335        } else {
 336            smol::fs::remove_dir(path).await
 337        };
 338        match result {
 339            Ok(()) => Ok(()),
 340            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 341                Ok(())
 342            }
 343            Err(err) => Err(err)?,
 344        }
 345    }
 346
 347    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 348        #[cfg(windows)]
 349        if let Ok(Some(metadata)) = self.metadata(path).await {
 350            if metadata.is_symlink && metadata.is_dir {
 351                self.remove_dir(
 352                    path,
 353                    RemoveOptions {
 354                        recursive: false,
 355                        ignore_if_not_exists: true,
 356                    },
 357                )
 358                .await?;
 359                return Ok(());
 360            }
 361        }
 362
 363        match smol::fs::remove_file(path).await {
 364            Ok(()) => Ok(()),
 365            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 366                Ok(())
 367            }
 368            Err(err) => Err(err)?,
 369        }
 370    }
 371
 372    #[cfg(target_os = "macos")]
 373    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 374        use cocoa::{
 375            base::{id, nil},
 376            foundation::{NSAutoreleasePool, NSString},
 377        };
 378        use objc::{class, msg_send, sel, sel_impl};
 379
 380        unsafe {
 381            unsafe fn ns_string(string: &str) -> id {
 382                NSString::alloc(nil).init_str(string).autorelease()
 383            }
 384
 385            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 386            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 387            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 388
 389            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 390        }
 391        Ok(())
 392    }
 393
 394    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 395    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 396        let file = File::open(path)?;
 397        match trash::trash_file(&file.as_fd()).await {
 398            Ok(_) => Ok(()),
 399            Err(err) => Err(anyhow::Error::new(err)),
 400        }
 401    }
 402
 403    #[cfg(target_os = "windows")]
 404    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 405        use windows::{
 406            core::HSTRING,
 407            Storage::{StorageDeleteOption, StorageFile},
 408        };
 409        // todo(windows)
 410        // When new version of `windows-rs` release, make this operation `async`
 411        let path = path.canonicalize()?.to_string_lossy().to_string();
 412        let path_str = path.trim_start_matches("\\\\?\\");
 413        if path_str.is_empty() {
 414            anyhow::bail!("File path is empty!");
 415        }
 416        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_str))?.get()?;
 417        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 418        Ok(())
 419    }
 420
 421    #[cfg(target_os = "macos")]
 422    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 423        self.trash_file(path, options).await
 424    }
 425
 426    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 427    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 428        self.trash_file(path, options).await
 429    }
 430
 431    #[cfg(target_os = "windows")]
 432    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 433        use windows::{
 434            core::HSTRING,
 435            Storage::{StorageDeleteOption, StorageFolder},
 436        };
 437
 438        let path = path.canonicalize()?.to_string_lossy().to_string();
 439        let path_str = path.trim_start_matches("\\\\?\\");
 440        if path_str.is_empty() {
 441            anyhow::bail!("Folder path is empty!");
 442        }
 443        // todo(windows)
 444        // When new version of `windows-rs` release, make this operation `async`
 445        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_str))?.get()?;
 446        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 447        Ok(())
 448    }
 449
 450    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 451        Ok(Box::new(std::fs::File::open(path)?))
 452    }
 453
 454    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 455        Ok(Arc::new(std::fs::File::open(path)?))
 456    }
 457
 458    async fn load(&self, path: &Path) -> Result<String> {
 459        let path = path.to_path_buf();
 460        let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
 461        Ok(text)
 462    }
 463    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 464        let path = path.to_path_buf();
 465        let bytes = smol::unblock(|| std::fs::read(path)).await?;
 466        Ok(bytes)
 467    }
 468
 469    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 470        smol::unblock(move || {
 471            let mut tmp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 472                // Use the directory of the destination as temp dir to avoid
 473                // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 474                // See https://github.com/zed-industries/zed/pull/8437 for more details.
 475                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 476            } else if cfg!(target_os = "windows") {
 477                // If temp dir is set to a different drive than the destination,
 478                // we receive error:
 479                //
 480                // failed to persist temporary file:
 481                // The system cannot move the file to a different disk drive. (os error 17)
 482                //
 483                // So we use the directory of the destination as a temp dir to avoid it.
 484                // https://github.com/zed-industries/zed/issues/16571
 485                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 486            } else {
 487                NamedTempFile::new()
 488            }?;
 489            tmp_file.write_all(data.as_bytes())?;
 490            tmp_file.persist(path)?;
 491            Ok::<(), anyhow::Error>(())
 492        })
 493        .await?;
 494
 495        Ok(())
 496    }
 497
 498    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 499        let buffer_size = text.summary().len.min(10 * 1024);
 500        if let Some(path) = path.parent() {
 501            self.create_dir(path).await?;
 502        }
 503        let file = smol::fs::File::create(path).await?;
 504        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 505        for chunk in chunks(text, line_ending) {
 506            writer.write_all(chunk.as_bytes()).await?;
 507        }
 508        writer.flush().await?;
 509        Ok(())
 510    }
 511
 512    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 513        Ok(smol::fs::canonicalize(path).await?)
 514    }
 515
 516    async fn is_file(&self, path: &Path) -> bool {
 517        smol::fs::metadata(path)
 518            .await
 519            .map_or(false, |metadata| metadata.is_file())
 520    }
 521
 522    async fn is_dir(&self, path: &Path) -> bool {
 523        smol::fs::metadata(path)
 524            .await
 525            .map_or(false, |metadata| metadata.is_dir())
 526    }
 527
 528    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 529        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 530            Ok(metadata) => metadata,
 531            Err(err) => {
 532                return match (err.kind(), err.raw_os_error()) {
 533                    (io::ErrorKind::NotFound, _) => Ok(None),
 534                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 535                    _ => Err(anyhow::Error::new(err)),
 536                }
 537            }
 538        };
 539
 540        let is_symlink = symlink_metadata.file_type().is_symlink();
 541        let metadata = if is_symlink {
 542            smol::fs::metadata(path).await?
 543        } else {
 544            symlink_metadata
 545        };
 546
 547        #[cfg(unix)]
 548        let inode = metadata.ino();
 549
 550        #[cfg(windows)]
 551        let inode = file_id(path).await?;
 552
 553        #[cfg(windows)]
 554        let is_fifo = false;
 555
 556        #[cfg(unix)]
 557        let is_fifo = metadata.file_type().is_fifo();
 558
 559        Ok(Some(Metadata {
 560            inode,
 561            mtime: metadata.modified().unwrap(),
 562            len: metadata.len(),
 563            is_symlink,
 564            is_dir: metadata.file_type().is_dir(),
 565            is_fifo,
 566        }))
 567    }
 568
 569    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 570        let path = smol::fs::read_link(path).await?;
 571        Ok(path)
 572    }
 573
 574    async fn read_dir(
 575        &self,
 576        path: &Path,
 577    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 578        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 579            Ok(entry) => Ok(entry.path()),
 580            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 581        });
 582        Ok(Box::pin(result))
 583    }
 584
 585    #[cfg(target_os = "macos")]
 586    async fn watch(
 587        &self,
 588        path: &Path,
 589        latency: Duration,
 590    ) -> (
 591        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 592        Arc<dyn Watcher>,
 593    ) {
 594        use fsevent::StreamFlags;
 595
 596        let (events_tx, events_rx) = smol::channel::unbounded();
 597        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 598        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 599            events_tx,
 600            Arc::downgrade(&handles),
 601            latency,
 602        ));
 603        watcher.add(path).expect("handles can't be dropped");
 604
 605        (
 606            Box::pin(
 607                events_rx
 608                    .map(|events| {
 609                        events
 610                            .into_iter()
 611                            .map(|event| {
 612                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 613                                    Some(PathEventKind::Removed)
 614                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 615                                    Some(PathEventKind::Created)
 616                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
 617                                    Some(PathEventKind::Changed)
 618                                } else {
 619                                    None
 620                                };
 621                                PathEvent {
 622                                    path: event.path,
 623                                    kind,
 624                                }
 625                            })
 626                            .collect()
 627                    })
 628                    .chain(futures::stream::once(async move {
 629                        drop(handles);
 630                        vec![]
 631                    })),
 632            ),
 633            watcher,
 634        )
 635    }
 636
 637    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 638    async fn watch(
 639        &self,
 640        path: &Path,
 641        latency: Duration,
 642    ) -> (
 643        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 644        Arc<dyn Watcher>,
 645    ) {
 646        use parking_lot::Mutex;
 647
 648        let (tx, rx) = smol::channel::unbounded();
 649        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 650        let watcher = Arc::new(linux_watcher::LinuxWatcher::new(tx, pending_paths.clone()));
 651
 652        watcher.add(&path).ok(); // Ignore "file doesn't exist error" and rely on parent watcher.
 653        if let Some(parent) = path.parent() {
 654            // watch the parent dir so we can tell when settings.json is created
 655            watcher.add(parent).log_err();
 656        }
 657
 658        // Check if path is a symlink and follow the target parent
 659        if let Some(target) = self.read_link(&path).await.ok() {
 660            watcher.add(&target).ok();
 661            if let Some(parent) = target.parent() {
 662                watcher.add(parent).log_err();
 663            }
 664        }
 665
 666        (
 667            Box::pin(rx.filter_map({
 668                let watcher = watcher.clone();
 669                move |_| {
 670                    let _ = watcher.clone();
 671                    let pending_paths = pending_paths.clone();
 672                    async move {
 673                        smol::Timer::after(latency).await;
 674                        let paths = std::mem::take(&mut *pending_paths.lock());
 675                        (!paths.is_empty()).then_some(paths)
 676                    }
 677                }
 678            })),
 679            watcher,
 680        )
 681    }
 682
 683    #[cfg(target_os = "windows")]
 684    async fn watch(
 685        &self,
 686        path: &Path,
 687        _latency: Duration,
 688    ) -> (
 689        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 690        Arc<dyn Watcher>,
 691    ) {
 692        use notify::{EventKind, Watcher};
 693
 694        let (tx, rx) = smol::channel::unbounded();
 695
 696        let mut file_watcher = notify::recommended_watcher({
 697            let tx = tx.clone();
 698            move |event: Result<notify::Event, _>| {
 699                if let Some(event) = event.log_err() {
 700                    let kind = match event.kind {
 701                        EventKind::Create(_) => Some(PathEventKind::Created),
 702                        EventKind::Modify(_) => Some(PathEventKind::Changed),
 703                        EventKind::Remove(_) => Some(PathEventKind::Removed),
 704                        _ => None,
 705                    };
 706
 707                    tx.try_send(
 708                        event
 709                            .paths
 710                            .into_iter()
 711                            .map(|path| PathEvent { path, kind })
 712                            .collect::<Vec<_>>(),
 713                    )
 714                    .ok();
 715                }
 716            }
 717        })
 718        .expect("Could not start file watcher");
 719
 720        file_watcher
 721            .watch(path, notify::RecursiveMode::Recursive)
 722            .log_err();
 723
 724        (
 725            Box::pin(rx.chain(futures::stream::once(async move {
 726                drop(file_watcher);
 727                vec![]
 728            }))),
 729            Arc::new(RealWatcher {}),
 730        )
 731    }
 732
 733    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
 734        let repo = git2::Repository::open(dotgit_path).log_err()?;
 735        Some(Arc::new(RealGitRepository::new(
 736            repo,
 737            self.git_binary_path.clone(),
 738            self.git_hosting_provider_registry.clone(),
 739        )))
 740    }
 741
 742    fn is_fake(&self) -> bool {
 743        false
 744    }
 745
 746    /// Checks whether the file system is case sensitive by attempting to create two files
 747    /// that have the same name except for the casing.
 748    ///
 749    /// It creates both files in a temporary directory it removes at the end.
 750    async fn is_case_sensitive(&self) -> Result<bool> {
 751        let temp_dir = TempDir::new()?;
 752        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 753        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 754
 755        let create_opts = CreateOptions {
 756            overwrite: false,
 757            ignore_if_exists: false,
 758        };
 759
 760        // Create file1
 761        self.create_file(&test_file_1, create_opts).await?;
 762
 763        // Now check whether it's possible to create file2
 764        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 765            Ok(_) => Ok(true),
 766            Err(e) => {
 767                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 768                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 769                        Ok(false)
 770                    } else {
 771                        Err(e)
 772                    }
 773                } else {
 774                    Err(e)
 775                }
 776            }
 777        };
 778
 779        temp_dir.close()?;
 780        case_sensitive
 781    }
 782}
 783
 784#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
 785impl Watcher for RealWatcher {
 786    fn add(&self, _: &Path) -> Result<()> {
 787        Ok(())
 788    }
 789
 790    fn remove(&self, _: &Path) -> Result<()> {
 791        Ok(())
 792    }
 793}
 794
 795#[cfg(any(test, feature = "test-support"))]
 796pub struct FakeFs {
 797    // Use an unfair lock to ensure tests are deterministic.
 798    state: Mutex<FakeFsState>,
 799    executor: gpui::BackgroundExecutor,
 800}
 801
 802#[cfg(any(test, feature = "test-support"))]
 803struct FakeFsState {
 804    root: Arc<Mutex<FakeFsEntry>>,
 805    next_inode: u64,
 806    next_mtime: SystemTime,
 807    git_event_tx: smol::channel::Sender<PathBuf>,
 808    event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
 809    events_paused: bool,
 810    buffered_events: Vec<PathEvent>,
 811    metadata_call_count: usize,
 812    read_dir_call_count: usize,
 813    moves: std::collections::HashMap<u64, PathBuf>,
 814}
 815
 816#[cfg(any(test, feature = "test-support"))]
 817#[derive(Debug)]
 818enum FakeFsEntry {
 819    File {
 820        inode: u64,
 821        mtime: SystemTime,
 822        len: u64,
 823        content: Vec<u8>,
 824    },
 825    Dir {
 826        inode: u64,
 827        mtime: SystemTime,
 828        len: u64,
 829        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 830        git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
 831    },
 832    Symlink {
 833        target: PathBuf,
 834    },
 835}
 836
 837#[cfg(any(test, feature = "test-support"))]
 838impl FakeFsState {
 839    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 840        Ok(self
 841            .try_read_path(target, true)
 842            .ok_or_else(|| {
 843                anyhow!(io::Error::new(
 844                    io::ErrorKind::NotFound,
 845                    format!("not found: {}", target.display())
 846                ))
 847            })?
 848            .0)
 849    }
 850
 851    fn try_read_path(
 852        &self,
 853        target: &Path,
 854        follow_symlink: bool,
 855    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 856        let mut path = target.to_path_buf();
 857        let mut canonical_path = PathBuf::new();
 858        let mut entry_stack = Vec::new();
 859        'outer: loop {
 860            let mut path_components = path.components().peekable();
 861            let mut prefix = None;
 862            while let Some(component) = path_components.next() {
 863                match component {
 864                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
 865                    Component::RootDir => {
 866                        entry_stack.clear();
 867                        entry_stack.push(self.root.clone());
 868                        canonical_path.clear();
 869                        match prefix {
 870                            Some(prefix_component) => {
 871                                canonical_path = PathBuf::from(prefix_component.as_os_str());
 872                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
 873                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
 874                            }
 875                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
 876                        }
 877                    }
 878                    Component::CurDir => {}
 879                    Component::ParentDir => {
 880                        entry_stack.pop()?;
 881                        canonical_path.pop();
 882                    }
 883                    Component::Normal(name) => {
 884                        let current_entry = entry_stack.last().cloned()?;
 885                        let current_entry = current_entry.lock();
 886                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 887                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 888                            if path_components.peek().is_some() || follow_symlink {
 889                                let entry = entry.lock();
 890                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 891                                    let mut target = target.clone();
 892                                    target.extend(path_components);
 893                                    path = target;
 894                                    continue 'outer;
 895                                }
 896                            }
 897                            entry_stack.push(entry.clone());
 898                            canonical_path = canonical_path.join(name);
 899                        } else {
 900                            return None;
 901                        }
 902                    }
 903                }
 904            }
 905            break;
 906        }
 907        Some((entry_stack.pop()?, canonical_path))
 908    }
 909
 910    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 911    where
 912        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 913    {
 914        let path = normalize_path(path);
 915        let filename = path
 916            .file_name()
 917            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 918        let parent_path = path.parent().unwrap();
 919
 920        let parent = self.read_path(parent_path)?;
 921        let mut parent = parent.lock();
 922        let new_entry = parent
 923            .dir_entries(parent_path)?
 924            .entry(filename.to_str().unwrap().into());
 925        callback(new_entry)
 926    }
 927
 928    fn emit_event<I, T>(&mut self, paths: I)
 929    where
 930        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
 931        T: Into<PathBuf>,
 932    {
 933        self.buffered_events
 934            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
 935                path: path.into(),
 936                kind,
 937            }));
 938
 939        if !self.events_paused {
 940            self.flush_events(self.buffered_events.len());
 941        }
 942    }
 943
 944    fn flush_events(&mut self, mut count: usize) {
 945        count = count.min(self.buffered_events.len());
 946        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 947        self.event_txs.retain(|tx| {
 948            let _ = tx.try_send(events.clone());
 949            !tx.is_closed()
 950        });
 951    }
 952}
 953
 954#[cfg(any(test, feature = "test-support"))]
 955pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
 956    std::sync::LazyLock::new(|| OsStr::new(".git"));
 957
 958#[cfg(any(test, feature = "test-support"))]
 959impl FakeFs {
 960    /// We need to use something large enough for Windows and Unix to consider this a new file.
 961    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
 962    const SYSTEMTIME_INTERVAL: u64 = 100;
 963
 964    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
 965        let (tx, mut rx) = smol::channel::bounded::<PathBuf>(10);
 966
 967        let this = Arc::new(Self {
 968            executor: executor.clone(),
 969            state: Mutex::new(FakeFsState {
 970                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 971                    inode: 0,
 972                    mtime: SystemTime::UNIX_EPOCH,
 973                    len: 0,
 974                    entries: Default::default(),
 975                    git_repo_state: None,
 976                })),
 977                git_event_tx: tx,
 978                next_mtime: SystemTime::UNIX_EPOCH,
 979                next_inode: 1,
 980                event_txs: Default::default(),
 981                buffered_events: Vec::new(),
 982                events_paused: false,
 983                read_dir_call_count: 0,
 984                metadata_call_count: 0,
 985                moves: Default::default(),
 986            }),
 987        });
 988
 989        executor.spawn({
 990            let this = this.clone();
 991            async move {
 992                while let Some(git_event) = rx.next().await {
 993                    if let Some(mut state) = this.state.try_lock() {
 994                        state.emit_event([(git_event, None)]);
 995                    } else {
 996                        panic!("Failed to lock file system state, this execution would have caused a test hang");
 997                    }
 998                }
 999            }
1000        }).detach();
1001
1002        this
1003    }
1004
1005    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1006        let mut state = self.state.lock();
1007        state.next_mtime = next_mtime;
1008    }
1009
1010    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1011        let mut state = self.state.lock();
1012        let path = path.as_ref();
1013        let new_mtime = state.next_mtime;
1014        let new_inode = state.next_inode;
1015        state.next_inode += 1;
1016        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1017        state
1018            .write_path(path, move |entry| {
1019                match entry {
1020                    btree_map::Entry::Vacant(e) => {
1021                        e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1022                            inode: new_inode,
1023                            mtime: new_mtime,
1024                            content: Vec::new(),
1025                            len: 0,
1026                        })));
1027                    }
1028                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1029                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1030                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1031                        FakeFsEntry::Symlink { .. } => {}
1032                    },
1033                }
1034                Ok(())
1035            })
1036            .unwrap();
1037        state.emit_event([(path.to_path_buf(), None)]);
1038    }
1039
1040    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1041        self.write_file_internal(path, content).unwrap()
1042    }
1043
1044    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1045        let mut state = self.state.lock();
1046        let path = path.as_ref();
1047        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1048        state
1049            .write_path(path.as_ref(), move |e| match e {
1050                btree_map::Entry::Vacant(e) => {
1051                    e.insert(file);
1052                    Ok(())
1053                }
1054                btree_map::Entry::Occupied(mut e) => {
1055                    *e.get_mut() = file;
1056                    Ok(())
1057                }
1058            })
1059            .unwrap();
1060        state.emit_event([(path, None)]);
1061    }
1062
1063    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1064        let mut state = self.state.lock();
1065        let path = path.as_ref();
1066        let inode = state.next_inode;
1067        let mtime = state.next_mtime;
1068        state.next_inode += 1;
1069        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1070        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1071            inode,
1072            mtime,
1073            len: content.len() as u64,
1074            content,
1075        }));
1076        let mut kind = None;
1077        state.write_path(path, {
1078            let kind = &mut kind;
1079            move |entry| {
1080                match entry {
1081                    btree_map::Entry::Vacant(e) => {
1082                        *kind = Some(PathEventKind::Created);
1083                        e.insert(file);
1084                    }
1085                    btree_map::Entry::Occupied(mut e) => {
1086                        *kind = Some(PathEventKind::Changed);
1087                        *e.get_mut() = file;
1088                    }
1089                }
1090                Ok(())
1091            }
1092        })?;
1093        state.emit_event([(path, kind)]);
1094        Ok(())
1095    }
1096
1097    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1098        let path = path.as_ref();
1099        let path = normalize_path(path);
1100        let state = self.state.lock();
1101        let entry = state.read_path(&path)?;
1102        let entry = entry.lock();
1103        entry.file_content(&path).cloned()
1104    }
1105
1106    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1107        let path = path.as_ref();
1108        let path = normalize_path(path);
1109        self.simulate_random_delay().await;
1110        let state = self.state.lock();
1111        let entry = state.read_path(&path)?;
1112        let entry = entry.lock();
1113        entry.file_content(&path).cloned()
1114    }
1115
1116    pub fn pause_events(&self) {
1117        self.state.lock().events_paused = true;
1118    }
1119
1120    pub fn buffered_event_count(&self) -> usize {
1121        self.state.lock().buffered_events.len()
1122    }
1123
1124    pub fn flush_events(&self, count: usize) {
1125        self.state.lock().flush_events(count);
1126    }
1127
1128    #[must_use]
1129    pub fn insert_tree<'a>(
1130        &'a self,
1131        path: impl 'a + AsRef<Path> + Send,
1132        tree: serde_json::Value,
1133    ) -> futures::future::BoxFuture<'a, ()> {
1134        use futures::FutureExt as _;
1135        use serde_json::Value::*;
1136
1137        async move {
1138            let path = path.as_ref();
1139
1140            match tree {
1141                Object(map) => {
1142                    self.create_dir(path).await.unwrap();
1143                    for (name, contents) in map {
1144                        let mut path = PathBuf::from(path);
1145                        path.push(name);
1146                        self.insert_tree(&path, contents).await;
1147                    }
1148                }
1149                Null => {
1150                    self.create_dir(path).await.unwrap();
1151                }
1152                String(contents) => {
1153                    self.insert_file(&path, contents.into_bytes()).await;
1154                }
1155                _ => {
1156                    panic!("JSON object must contain only objects, strings, or null");
1157                }
1158            }
1159        }
1160        .boxed()
1161    }
1162
1163    pub fn insert_tree_from_real_fs<'a>(
1164        &'a self,
1165        path: impl 'a + AsRef<Path> + Send,
1166        src_path: impl 'a + AsRef<Path> + Send,
1167    ) -> futures::future::BoxFuture<'a, ()> {
1168        use futures::FutureExt as _;
1169
1170        async move {
1171            let path = path.as_ref();
1172            if std::fs::metadata(&src_path).unwrap().is_file() {
1173                let contents = std::fs::read(src_path).unwrap();
1174                self.insert_file(path, contents).await;
1175            } else {
1176                self.create_dir(path).await.unwrap();
1177                for entry in std::fs::read_dir(&src_path).unwrap() {
1178                    let entry = entry.unwrap();
1179                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1180                        .await;
1181                }
1182            }
1183        }
1184        .boxed()
1185    }
1186
1187    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1188    where
1189        F: FnOnce(&mut FakeGitRepositoryState),
1190    {
1191        let mut state = self.state.lock();
1192        let entry = state.read_path(dot_git).unwrap();
1193        let mut entry = entry.lock();
1194
1195        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1196            let repo_state = git_repo_state.get_or_insert_with(|| {
1197                Arc::new(Mutex::new(FakeGitRepositoryState::new(
1198                    dot_git.to_path_buf(),
1199                    state.git_event_tx.clone(),
1200                )))
1201            });
1202            let mut repo_state = repo_state.lock();
1203
1204            f(&mut repo_state);
1205
1206            if emit_git_event {
1207                state.emit_event([(dot_git, None)]);
1208            }
1209        } else {
1210            panic!("not a directory");
1211        }
1212    }
1213
1214    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1215        self.with_git_state(dot_git, true, |state| {
1216            let branch = branch.map(Into::into);
1217            state.branches.extend(branch.clone());
1218            state.current_branch_name = branch.map(Into::into)
1219        })
1220    }
1221
1222    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1223        self.with_git_state(dot_git, true, |state| {
1224            if let Some(first) = branches.first() {
1225                if state.current_branch_name.is_none() {
1226                    state.current_branch_name = Some(first.to_string())
1227                }
1228            }
1229            state
1230                .branches
1231                .extend(branches.iter().map(ToString::to_string));
1232        })
1233    }
1234
1235    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1236        self.with_git_state(dot_git, true, |state| {
1237            state.index_contents.clear();
1238            state.index_contents.extend(
1239                head_state
1240                    .iter()
1241                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
1242            );
1243        });
1244    }
1245
1246    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1247        self.with_git_state(dot_git, true, |state| {
1248            state.blames.clear();
1249            state.blames.extend(
1250                blames
1251                    .into_iter()
1252                    .map(|(path, blame)| (path.to_path_buf(), blame)),
1253            );
1254        });
1255    }
1256
1257    pub fn set_status_for_repo_via_working_copy_change(
1258        &self,
1259        dot_git: &Path,
1260        statuses: &[(&Path, GitFileStatus)],
1261    ) {
1262        self.with_git_state(dot_git, false, |state| {
1263            state.worktree_statuses.clear();
1264            state.worktree_statuses.extend(
1265                statuses
1266                    .iter()
1267                    .map(|(path, content)| ((**path).into(), *content)),
1268            );
1269        });
1270        self.state.lock().emit_event(
1271            statuses
1272                .iter()
1273                .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1274        );
1275    }
1276
1277    pub fn set_status_for_repo_via_git_operation(
1278        &self,
1279        dot_git: &Path,
1280        statuses: &[(&Path, GitFileStatus)],
1281    ) {
1282        self.with_git_state(dot_git, true, |state| {
1283            state.worktree_statuses.clear();
1284            state.worktree_statuses.extend(
1285                statuses
1286                    .iter()
1287                    .map(|(path, content)| ((**path).into(), *content)),
1288            );
1289        });
1290    }
1291
1292    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1293        let mut result = Vec::new();
1294        let mut queue = collections::VecDeque::new();
1295        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1296        while let Some((path, entry)) = queue.pop_front() {
1297            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1298                for (name, entry) in entries {
1299                    queue.push_back((path.join(name), entry.clone()));
1300                }
1301            }
1302            if include_dot_git
1303                || !path
1304                    .components()
1305                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1306            {
1307                result.push(path);
1308            }
1309        }
1310        result
1311    }
1312
1313    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1314        let mut result = Vec::new();
1315        let mut queue = collections::VecDeque::new();
1316        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1317        while let Some((path, entry)) = queue.pop_front() {
1318            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1319                for (name, entry) in entries {
1320                    queue.push_back((path.join(name), entry.clone()));
1321                }
1322                if include_dot_git
1323                    || !path
1324                        .components()
1325                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1326                {
1327                    result.push(path);
1328                }
1329            }
1330        }
1331        result
1332    }
1333
1334    pub fn files(&self) -> Vec<PathBuf> {
1335        let mut result = Vec::new();
1336        let mut queue = collections::VecDeque::new();
1337        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1338        while let Some((path, entry)) = queue.pop_front() {
1339            let e = entry.lock();
1340            match &*e {
1341                FakeFsEntry::File { .. } => result.push(path),
1342                FakeFsEntry::Dir { entries, .. } => {
1343                    for (name, entry) in entries {
1344                        queue.push_back((path.join(name), entry.clone()));
1345                    }
1346                }
1347                FakeFsEntry::Symlink { .. } => {}
1348            }
1349        }
1350        result
1351    }
1352
1353    /// How many `read_dir` calls have been issued.
1354    pub fn read_dir_call_count(&self) -> usize {
1355        self.state.lock().read_dir_call_count
1356    }
1357
1358    /// How many `metadata` calls have been issued.
1359    pub fn metadata_call_count(&self) -> usize {
1360        self.state.lock().metadata_call_count
1361    }
1362
1363    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1364        self.executor.simulate_random_delay()
1365    }
1366}
1367
1368#[cfg(any(test, feature = "test-support"))]
1369impl FakeFsEntry {
1370    fn is_file(&self) -> bool {
1371        matches!(self, Self::File { .. })
1372    }
1373
1374    fn is_symlink(&self) -> bool {
1375        matches!(self, Self::Symlink { .. })
1376    }
1377
1378    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1379        if let Self::File { content, .. } = self {
1380            Ok(content)
1381        } else {
1382            Err(anyhow!("not a file: {}", path.display()))
1383        }
1384    }
1385
1386    fn set_file_content(&mut self, path: &Path, new_content: Vec<u8>) -> Result<()> {
1387        if let Self::File { content, mtime, .. } = self {
1388            *mtime = SystemTime::now();
1389            *content = new_content;
1390            Ok(())
1391        } else {
1392            Err(anyhow!("not a file: {}", path.display()))
1393        }
1394    }
1395
1396    fn dir_entries(
1397        &mut self,
1398        path: &Path,
1399    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1400        if let Self::Dir { entries, .. } = self {
1401            Ok(entries)
1402        } else {
1403            Err(anyhow!("not a directory: {}", path.display()))
1404        }
1405    }
1406}
1407
1408#[cfg(any(test, feature = "test-support"))]
1409struct FakeWatcher {}
1410
1411#[cfg(any(test, feature = "test-support"))]
1412impl Watcher for FakeWatcher {
1413    fn add(&self, _: &Path) -> Result<()> {
1414        Ok(())
1415    }
1416
1417    fn remove(&self, _: &Path) -> Result<()> {
1418        Ok(())
1419    }
1420}
1421
1422#[cfg(any(test, feature = "test-support"))]
1423#[derive(Debug)]
1424struct FakeHandle {
1425    inode: u64,
1426}
1427
1428#[cfg(any(test, feature = "test-support"))]
1429impl FileHandle for FakeHandle {
1430    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1431        let state = fs.as_fake().state.lock();
1432        let Some(target) = state.moves.get(&self.inode) else {
1433            anyhow::bail!("fake fd not moved")
1434        };
1435
1436        if state.try_read_path(&target, false).is_some() {
1437            return Ok(target.clone());
1438        }
1439        anyhow::bail!("fake fd target not found")
1440    }
1441}
1442
1443#[cfg(any(test, feature = "test-support"))]
1444#[async_trait::async_trait]
1445impl Fs for FakeFs {
1446    async fn create_dir(&self, path: &Path) -> Result<()> {
1447        self.simulate_random_delay().await;
1448
1449        let mut created_dirs = Vec::new();
1450        let mut cur_path = PathBuf::new();
1451        for component in path.components() {
1452            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1453            cur_path.push(component);
1454            if should_skip {
1455                continue;
1456            }
1457            let mut state = self.state.lock();
1458
1459            let inode = state.next_inode;
1460            let mtime = state.next_mtime;
1461            state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1462            state.next_inode += 1;
1463            state.write_path(&cur_path, |entry| {
1464                entry.or_insert_with(|| {
1465                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1466                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1467                        inode,
1468                        mtime,
1469                        len: 0,
1470                        entries: Default::default(),
1471                        git_repo_state: None,
1472                    }))
1473                });
1474                Ok(())
1475            })?
1476        }
1477
1478        self.state.lock().emit_event(created_dirs);
1479        Ok(())
1480    }
1481
1482    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1483        self.simulate_random_delay().await;
1484        let mut state = self.state.lock();
1485        let inode = state.next_inode;
1486        let mtime = state.next_mtime;
1487        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1488        state.next_inode += 1;
1489        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1490            inode,
1491            mtime,
1492            len: 0,
1493            content: Vec::new(),
1494        }));
1495        let mut kind = Some(PathEventKind::Created);
1496        state.write_path(path, |entry| {
1497            match entry {
1498                btree_map::Entry::Occupied(mut e) => {
1499                    if options.overwrite {
1500                        kind = Some(PathEventKind::Changed);
1501                        *e.get_mut() = file;
1502                    } else if !options.ignore_if_exists {
1503                        return Err(anyhow!("path already exists: {}", path.display()));
1504                    }
1505                }
1506                btree_map::Entry::Vacant(e) => {
1507                    e.insert(file);
1508                }
1509            }
1510            Ok(())
1511        })?;
1512        state.emit_event([(path, kind)]);
1513        Ok(())
1514    }
1515
1516    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1517        let mut state = self.state.lock();
1518        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1519        state
1520            .write_path(path.as_ref(), move |e| match e {
1521                btree_map::Entry::Vacant(e) => {
1522                    e.insert(file);
1523                    Ok(())
1524                }
1525                btree_map::Entry::Occupied(mut e) => {
1526                    *e.get_mut() = file;
1527                    Ok(())
1528                }
1529            })
1530            .unwrap();
1531        state.emit_event([(path, None)]);
1532
1533        Ok(())
1534    }
1535
1536    async fn create_file_with(
1537        &self,
1538        path: &Path,
1539        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1540    ) -> Result<()> {
1541        let mut bytes = Vec::new();
1542        content.read_to_end(&mut bytes).await?;
1543        self.write_file_internal(path, bytes)?;
1544        Ok(())
1545    }
1546
1547    async fn extract_tar_file(
1548        &self,
1549        path: &Path,
1550        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1551    ) -> Result<()> {
1552        let mut entries = content.entries()?;
1553        while let Some(entry) = entries.next().await {
1554            let mut entry = entry?;
1555            if entry.header().entry_type().is_file() {
1556                let path = path.join(entry.path()?.as_ref());
1557                let mut bytes = Vec::new();
1558                entry.read_to_end(&mut bytes).await?;
1559                self.create_dir(path.parent().unwrap()).await?;
1560                self.write_file_internal(&path, bytes)?;
1561            }
1562        }
1563        Ok(())
1564    }
1565
1566    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1567        self.simulate_random_delay().await;
1568
1569        let old_path = normalize_path(old_path);
1570        let new_path = normalize_path(new_path);
1571
1572        let mut state = self.state.lock();
1573        let moved_entry = state.write_path(&old_path, |e| {
1574            if let btree_map::Entry::Occupied(e) = e {
1575                Ok(e.get().clone())
1576            } else {
1577                Err(anyhow!("path does not exist: {}", &old_path.display()))
1578            }
1579        })?;
1580
1581        let inode = match *moved_entry.lock() {
1582            FakeFsEntry::File { inode, .. } => inode,
1583            FakeFsEntry::Dir { inode, .. } => inode,
1584            _ => 0,
1585        };
1586
1587        state.moves.insert(inode, new_path.clone());
1588
1589        state.write_path(&new_path, |e| {
1590            match e {
1591                btree_map::Entry::Occupied(mut e) => {
1592                    if options.overwrite {
1593                        *e.get_mut() = moved_entry;
1594                    } else if !options.ignore_if_exists {
1595                        return Err(anyhow!("path already exists: {}", new_path.display()));
1596                    }
1597                }
1598                btree_map::Entry::Vacant(e) => {
1599                    e.insert(moved_entry);
1600                }
1601            }
1602            Ok(())
1603        })?;
1604
1605        state
1606            .write_path(&old_path, |e| {
1607                if let btree_map::Entry::Occupied(e) = e {
1608                    Ok(e.remove())
1609                } else {
1610                    unreachable!()
1611                }
1612            })
1613            .unwrap();
1614
1615        state.emit_event([
1616            (old_path, Some(PathEventKind::Removed)),
1617            (new_path, Some(PathEventKind::Created)),
1618        ]);
1619        Ok(())
1620    }
1621
1622    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1623        self.simulate_random_delay().await;
1624
1625        let source = normalize_path(source);
1626        let target = normalize_path(target);
1627        let mut state = self.state.lock();
1628        let mtime = state.next_mtime;
1629        let inode = util::post_inc(&mut state.next_inode);
1630        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1631        let source_entry = state.read_path(&source)?;
1632        let content = source_entry.lock().file_content(&source)?.clone();
1633        let mut kind = Some(PathEventKind::Created);
1634        let entry = state.write_path(&target, |e| match e {
1635            btree_map::Entry::Occupied(e) => {
1636                if options.overwrite {
1637                    kind = Some(PathEventKind::Changed);
1638                    Ok(Some(e.get().clone()))
1639                } else if !options.ignore_if_exists {
1640                    return Err(anyhow!("{target:?} already exists"));
1641                } else {
1642                    Ok(None)
1643                }
1644            }
1645            btree_map::Entry::Vacant(e) => Ok(Some(
1646                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1647                    inode,
1648                    mtime,
1649                    len: content.len() as u64,
1650                    content: Vec::new(),
1651                })))
1652                .clone(),
1653            )),
1654        })?;
1655        if let Some(entry) = entry {
1656            entry.lock().set_file_content(&target, content)?;
1657        }
1658        state.emit_event([(target, kind)]);
1659        Ok(())
1660    }
1661
1662    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1663        self.simulate_random_delay().await;
1664
1665        let path = normalize_path(path);
1666        let parent_path = path
1667            .parent()
1668            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1669        let base_name = path.file_name().unwrap();
1670
1671        let mut state = self.state.lock();
1672        let parent_entry = state.read_path(parent_path)?;
1673        let mut parent_entry = parent_entry.lock();
1674        let entry = parent_entry
1675            .dir_entries(parent_path)?
1676            .entry(base_name.to_str().unwrap().into());
1677
1678        match entry {
1679            btree_map::Entry::Vacant(_) => {
1680                if !options.ignore_if_not_exists {
1681                    return Err(anyhow!("{path:?} does not exist"));
1682                }
1683            }
1684            btree_map::Entry::Occupied(e) => {
1685                {
1686                    let mut entry = e.get().lock();
1687                    let children = entry.dir_entries(&path)?;
1688                    if !options.recursive && !children.is_empty() {
1689                        return Err(anyhow!("{path:?} is not empty"));
1690                    }
1691                }
1692                e.remove();
1693            }
1694        }
1695        state.emit_event([(path, Some(PathEventKind::Removed))]);
1696        Ok(())
1697    }
1698
1699    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1700        self.simulate_random_delay().await;
1701
1702        let path = normalize_path(path);
1703        let parent_path = path
1704            .parent()
1705            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1706        let base_name = path.file_name().unwrap();
1707        let mut state = self.state.lock();
1708        let parent_entry = state.read_path(parent_path)?;
1709        let mut parent_entry = parent_entry.lock();
1710        let entry = parent_entry
1711            .dir_entries(parent_path)?
1712            .entry(base_name.to_str().unwrap().into());
1713        match entry {
1714            btree_map::Entry::Vacant(_) => {
1715                if !options.ignore_if_not_exists {
1716                    return Err(anyhow!("{path:?} does not exist"));
1717                }
1718            }
1719            btree_map::Entry::Occupied(e) => {
1720                e.get().lock().file_content(&path)?;
1721                e.remove();
1722            }
1723        }
1724        state.emit_event([(path, Some(PathEventKind::Removed))]);
1725        Ok(())
1726    }
1727
1728    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1729        let bytes = self.load_internal(path).await?;
1730        Ok(Box::new(io::Cursor::new(bytes)))
1731    }
1732
1733    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1734        self.simulate_random_delay().await;
1735        let state = self.state.lock();
1736        let entry = state.read_path(&path)?;
1737        let entry = entry.lock();
1738        let inode = match *entry {
1739            FakeFsEntry::File { inode, .. } => inode,
1740            FakeFsEntry::Dir { inode, .. } => inode,
1741            _ => unreachable!(),
1742        };
1743        Ok(Arc::new(FakeHandle { inode }))
1744    }
1745
1746    async fn load(&self, path: &Path) -> Result<String> {
1747        let content = self.load_internal(path).await?;
1748        Ok(String::from_utf8(content.clone())?)
1749    }
1750
1751    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1752        self.load_internal(path).await
1753    }
1754
1755    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1756        self.simulate_random_delay().await;
1757        let path = normalize_path(path.as_path());
1758        self.write_file_internal(path, data.into_bytes())?;
1759        Ok(())
1760    }
1761
1762    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1763        self.simulate_random_delay().await;
1764        let path = normalize_path(path);
1765        let content = chunks(text, line_ending).collect::<String>();
1766        if let Some(path) = path.parent() {
1767            self.create_dir(path).await?;
1768        }
1769        self.write_file_internal(path, content.into_bytes())?;
1770        Ok(())
1771    }
1772
1773    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1774        let path = normalize_path(path);
1775        self.simulate_random_delay().await;
1776        let state = self.state.lock();
1777        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1778            Ok(canonical_path)
1779        } else {
1780            Err(anyhow!("path does not exist: {}", path.display()))
1781        }
1782    }
1783
1784    async fn is_file(&self, path: &Path) -> bool {
1785        let path = normalize_path(path);
1786        self.simulate_random_delay().await;
1787        let state = self.state.lock();
1788        if let Some((entry, _)) = state.try_read_path(&path, true) {
1789            entry.lock().is_file()
1790        } else {
1791            false
1792        }
1793    }
1794
1795    async fn is_dir(&self, path: &Path) -> bool {
1796        self.metadata(path)
1797            .await
1798            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1799    }
1800
1801    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1802        self.simulate_random_delay().await;
1803        let path = normalize_path(path);
1804        let mut state = self.state.lock();
1805        state.metadata_call_count += 1;
1806        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1807            let is_symlink = entry.lock().is_symlink();
1808            if is_symlink {
1809                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1810                    entry = e;
1811                } else {
1812                    return Ok(None);
1813                }
1814            }
1815
1816            let entry = entry.lock();
1817            Ok(Some(match &*entry {
1818                FakeFsEntry::File {
1819                    inode, mtime, len, ..
1820                } => Metadata {
1821                    inode: *inode,
1822                    mtime: *mtime,
1823                    len: *len,
1824                    is_dir: false,
1825                    is_symlink,
1826                    is_fifo: false,
1827                },
1828                FakeFsEntry::Dir {
1829                    inode, mtime, len, ..
1830                } => Metadata {
1831                    inode: *inode,
1832                    mtime: *mtime,
1833                    len: *len,
1834                    is_dir: true,
1835                    is_symlink,
1836                    is_fifo: false,
1837                },
1838                FakeFsEntry::Symlink { .. } => unreachable!(),
1839            }))
1840        } else {
1841            Ok(None)
1842        }
1843    }
1844
1845    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1846        self.simulate_random_delay().await;
1847        let path = normalize_path(path);
1848        let state = self.state.lock();
1849        if let Some((entry, _)) = state.try_read_path(&path, false) {
1850            let entry = entry.lock();
1851            if let FakeFsEntry::Symlink { target } = &*entry {
1852                Ok(target.clone())
1853            } else {
1854                Err(anyhow!("not a symlink: {}", path.display()))
1855            }
1856        } else {
1857            Err(anyhow!("path does not exist: {}", path.display()))
1858        }
1859    }
1860
1861    async fn read_dir(
1862        &self,
1863        path: &Path,
1864    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1865        self.simulate_random_delay().await;
1866        let path = normalize_path(path);
1867        let mut state = self.state.lock();
1868        state.read_dir_call_count += 1;
1869        let entry = state.read_path(&path)?;
1870        let mut entry = entry.lock();
1871        let children = entry.dir_entries(&path)?;
1872        let paths = children
1873            .keys()
1874            .map(|file_name| Ok(path.join(file_name)))
1875            .collect::<Vec<_>>();
1876        Ok(Box::pin(futures::stream::iter(paths)))
1877    }
1878
1879    async fn watch(
1880        &self,
1881        path: &Path,
1882        _: Duration,
1883    ) -> (
1884        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1885        Arc<dyn Watcher>,
1886    ) {
1887        self.simulate_random_delay().await;
1888        let (tx, rx) = smol::channel::unbounded();
1889        self.state.lock().event_txs.push(tx);
1890        let path = path.to_path_buf();
1891        let executor = self.executor.clone();
1892        (
1893            Box::pin(futures::StreamExt::filter(rx, move |events| {
1894                let result = events
1895                    .iter()
1896                    .any(|evt_path| evt_path.path.starts_with(&path));
1897                let executor = executor.clone();
1898                async move {
1899                    executor.simulate_random_delay().await;
1900                    result
1901                }
1902            })),
1903            Arc::new(FakeWatcher {}),
1904        )
1905    }
1906
1907    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1908        let state = self.state.lock();
1909        let entry = state.read_path(abs_dot_git).unwrap();
1910        let mut entry = entry.lock();
1911        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1912            let state = git_repo_state
1913                .get_or_insert_with(|| {
1914                    Arc::new(Mutex::new(FakeGitRepositoryState::new(
1915                        abs_dot_git.to_path_buf(),
1916                        state.git_event_tx.clone(),
1917                    )))
1918                })
1919                .clone();
1920            Some(git::repository::FakeGitRepository::open(state))
1921        } else {
1922            None
1923        }
1924    }
1925
1926    fn is_fake(&self) -> bool {
1927        true
1928    }
1929
1930    async fn is_case_sensitive(&self) -> Result<bool> {
1931        Ok(true)
1932    }
1933
1934    #[cfg(any(test, feature = "test-support"))]
1935    fn as_fake(&self) -> &FakeFs {
1936        self
1937    }
1938}
1939
1940fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1941    rope.chunks().flat_map(move |chunk| {
1942        let mut newline = false;
1943        chunk.split('\n').flat_map(move |line| {
1944            let ending = if newline {
1945                Some(line_ending.as_str())
1946            } else {
1947                None
1948            };
1949            newline = true;
1950            ending.into_iter().chain([line])
1951        })
1952    })
1953}
1954
1955pub fn normalize_path(path: &Path) -> PathBuf {
1956    let mut components = path.components().peekable();
1957    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1958        components.next();
1959        PathBuf::from(c.as_os_str())
1960    } else {
1961        PathBuf::new()
1962    };
1963
1964    for component in components {
1965        match component {
1966            Component::Prefix(..) => unreachable!(),
1967            Component::RootDir => {
1968                ret.push(component.as_os_str());
1969            }
1970            Component::CurDir => {}
1971            Component::ParentDir => {
1972                ret.pop();
1973            }
1974            Component::Normal(c) => {
1975                ret.push(c);
1976            }
1977        }
1978    }
1979    ret
1980}
1981
1982pub fn copy_recursive<'a>(
1983    fs: &'a dyn Fs,
1984    source: &'a Path,
1985    target: &'a Path,
1986    options: CopyOptions,
1987) -> BoxFuture<'a, Result<()>> {
1988    use futures::future::FutureExt;
1989
1990    async move {
1991        let metadata = fs
1992            .metadata(source)
1993            .await?
1994            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1995        if metadata.is_dir {
1996            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1997                if options.ignore_if_exists {
1998                    return Ok(());
1999                } else {
2000                    return Err(anyhow!("{target:?} already exists"));
2001                }
2002            }
2003
2004            let _ = fs
2005                .remove_dir(
2006                    target,
2007                    RemoveOptions {
2008                        recursive: true,
2009                        ignore_if_not_exists: true,
2010                    },
2011                )
2012                .await;
2013            fs.create_dir(target).await?;
2014            let mut children = fs.read_dir(source).await?;
2015            while let Some(child_path) = children.next().await {
2016                if let Ok(child_path) = child_path {
2017                    if let Some(file_name) = child_path.file_name() {
2018                        let child_target_path = target.join(file_name);
2019                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
2020                    }
2021                }
2022            }
2023
2024            Ok(())
2025        } else {
2026            fs.copy_file(source, target, options).await
2027        }
2028    }
2029    .boxed()
2030}
2031
2032// todo(windows)
2033// can we get file id not open the file twice?
2034// https://github.com/rust-lang/rust/issues/63010
2035#[cfg(target_os = "windows")]
2036async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2037    use std::os::windows::io::AsRawHandle;
2038
2039    use smol::fs::windows::OpenOptionsExt;
2040    use windows::Win32::{
2041        Foundation::HANDLE,
2042        Storage::FileSystem::{
2043            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2044        },
2045    };
2046
2047    let file = smol::fs::OpenOptions::new()
2048        .read(true)
2049        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2050        .open(path)
2051        .await?;
2052
2053    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2054    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2055    // This function supports Windows XP+
2056    smol::unblock(move || {
2057        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2058
2059        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2060    })
2061    .await
2062}
2063
2064#[cfg(test)]
2065mod tests {
2066    use super::*;
2067    use gpui::BackgroundExecutor;
2068    use serde_json::json;
2069
2070    #[gpui::test]
2071    async fn test_fake_fs(executor: BackgroundExecutor) {
2072        let fs = FakeFs::new(executor.clone());
2073        fs.insert_tree(
2074            "/root",
2075            json!({
2076                "dir1": {
2077                    "a": "A",
2078                    "b": "B"
2079                },
2080                "dir2": {
2081                    "c": "C",
2082                    "dir3": {
2083                        "d": "D"
2084                    }
2085                }
2086            }),
2087        )
2088        .await;
2089
2090        assert_eq!(
2091            fs.files(),
2092            vec![
2093                PathBuf::from("/root/dir1/a"),
2094                PathBuf::from("/root/dir1/b"),
2095                PathBuf::from("/root/dir2/c"),
2096                PathBuf::from("/root/dir2/dir3/d"),
2097            ]
2098        );
2099
2100        fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2101            .await
2102            .unwrap();
2103
2104        assert_eq!(
2105            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2106                .await
2107                .unwrap(),
2108            PathBuf::from("/root/dir2/dir3"),
2109        );
2110        assert_eq!(
2111            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2112                .await
2113                .unwrap(),
2114            PathBuf::from("/root/dir2/dir3/d"),
2115        );
2116        assert_eq!(
2117            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2118            "D",
2119        );
2120    }
2121}