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