fs.rs

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