fs.rs

   1#[cfg(target_os = "macos")]
   2mod mac_watcher;
   3
   4#[cfg(not(target_os = "macos"))]
   5pub mod fs_watcher;
   6
   7use anyhow::{Context as _, Result, anyhow};
   8#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   9use ashpd::desktop::trash;
  10use futures::stream::iter;
  11use encodings::Encoding;
  12use gpui::App;
  13use gpui::BackgroundExecutor;
  14use gpui::Global;
  15use gpui::ReadGlobal as _;
  16use std::borrow::Cow;
  17use util::command::new_smol_command;
  18
  19#[cfg(unix)]
  20use std::os::fd::{AsFd, AsRawFd};
  21
  22#[cfg(unix)]
  23use std::os::unix::fs::{FileTypeExt, MetadataExt};
  24
  25#[cfg(any(target_os = "macos", target_os = "freebsd"))]
  26use std::mem::MaybeUninit;
  27
  28use async_tar::Archive;
  29use futures::{AsyncRead, Stream, StreamExt, future::BoxFuture};
  30use git::repository::{GitRepository, RealGitRepository};
  31use rope::Rope;
  32use serde::{Deserialize, Serialize};
  33use smol::io::AsyncWriteExt;
  34use std::{
  35    io::{self, Write},
  36    path::{Component, Path, PathBuf},
  37    pin::Pin,
  38    sync::Arc,
  39    time::{Duration, SystemTime, UNIX_EPOCH},
  40};
  41use tempfile::TempDir;
  42use text::LineEnding;
  43
  44#[cfg(any(test, feature = "test-support"))]
  45mod fake_git_repo;
  46#[cfg(any(test, feature = "test-support"))]
  47use collections::{BTreeMap, btree_map};
  48#[cfg(any(test, feature = "test-support"))]
  49use fake_git_repo::FakeGitRepositoryState;
  50#[cfg(any(test, feature = "test-support"))]
  51use git::{
  52    repository::{RepoPath, repo_path},
  53    status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus},
  54};
  55#[cfg(any(test, feature = "test-support"))]
  56use parking_lot::Mutex;
  57#[cfg(any(test, feature = "test-support"))]
  58use smol::io::AsyncReadExt;
  59#[cfg(any(test, feature = "test-support"))]
  60use std::ffi::OsStr;
  61
  62#[cfg(any(test, feature = "test-support"))]
  63pub use fake_git_repo::{LOAD_HEAD_TEXT_TASK, LOAD_INDEX_TEXT_TASK};
  64use encodings::Encoding;
  65use encodings::from_utf8;
  66use encodings::to_utf8;
  67
  68pub trait Watcher: Send + Sync {
  69    fn add(&self, path: &Path) -> Result<()>;
  70    fn remove(&self, path: &Path) -> Result<()>;
  71}
  72
  73#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  74pub enum PathEventKind {
  75    Removed,
  76    Created,
  77    Changed,
  78}
  79
  80#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  81pub struct PathEvent {
  82    pub path: PathBuf,
  83    pub kind: Option<PathEventKind>,
  84}
  85
  86impl From<PathEvent> for PathBuf {
  87    fn from(event: PathEvent) -> Self {
  88        event.path
  89    }
  90}
  91
  92#[async_trait::async_trait]
  93pub trait Fs: Send + Sync {
  94    async fn create_dir(&self, path: &Path) -> Result<()>;
  95    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  96    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  97    async fn create_file_with(
  98        &self,
  99        path: &Path,
 100        content: Pin<&mut (dyn AsyncRead + Send)>,
 101    ) -> Result<()>;
 102    async fn extract_tar_file(
 103        &self,
 104        path: &Path,
 105        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 106    ) -> Result<()>;
 107    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
 108    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
 109    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 110    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 111        self.remove_dir(path, options).await
 112    }
 113    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 114    async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 115        self.remove_file(path, options).await
 116    }
 117    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
 118    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>>;
 119    async fn load(&self, path: &Path) -> Result<String> {
 120        Ok(String::from_utf8(self.load_bytes(path).await?)?)
 121    }
 122
 123    async fn load_with_encoding(
 124        &self,
 125        path: &Path,
 126        encoding: Encoding,
 127        force: bool,
 128        detect_utf16: bool,
 129        buffer_encoding: Option<Arc<Encoding>>,
 130    ) -> Result<String> {
 131        Ok(to_utf8(
 132            self.load_bytes(path).await?,
 133            encoding,
 134            force,
 135            detect_utf16,
 136            buffer_encoding,
 137        )
 138        .await?)
 139    }
 140
 141    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
 142    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 143    async fn save(
 144        &self,
 145        path: &Path,
 146        text: &Rope,
 147        line_ending: LineEnding,
 148        encoding: Encoding,
 149    ) -> Result<()>;
 150    async fn write(&self, path: &Path, content: &[u8]) -> Result<()>;
 151    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 152    async fn is_file(&self, path: &Path) -> bool;
 153    async fn is_dir(&self, path: &Path) -> bool;
 154    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 155    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 156    async fn read_dir(
 157        &self,
 158        path: &Path,
 159    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 160
 161    async fn watch(
 162        &self,
 163        path: &Path,
 164        latency: Duration,
 165    ) -> (
 166        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 167        Arc<dyn Watcher>,
 168    );
 169
 170    fn open_repo(
 171        &self,
 172        abs_dot_git: &Path,
 173        system_git_binary_path: Option<&Path>,
 174    ) -> Option<Arc<dyn GitRepository>>;
 175    async fn git_init(&self, abs_work_directory: &Path, fallback_branch_name: String)
 176    -> Result<()>;
 177    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()>;
 178    fn is_fake(&self) -> bool;
 179    async fn is_case_sensitive(&self) -> Result<bool>;
 180
 181    #[cfg(any(test, feature = "test-support"))]
 182    fn as_fake(&self) -> Arc<FakeFs> {
 183        panic!("called as_fake on a real fs");
 184    }
 185}
 186
 187struct GlobalFs(Arc<dyn Fs>);
 188
 189impl Global for GlobalFs {}
 190
 191impl dyn Fs {
 192    /// Returns the global [`Fs`].
 193    pub fn global(cx: &App) -> Arc<Self> {
 194        GlobalFs::global(cx).0.clone()
 195    }
 196
 197    /// Sets the global [`Fs`].
 198    pub fn set_global(fs: Arc<Self>, cx: &mut App) {
 199        cx.set_global(GlobalFs(fs));
 200    }
 201}
 202
 203#[derive(Copy, Clone, Default)]
 204pub struct CreateOptions {
 205    pub overwrite: bool,
 206    pub ignore_if_exists: bool,
 207}
 208
 209#[derive(Copy, Clone, Default)]
 210pub struct CopyOptions {
 211    pub overwrite: bool,
 212    pub ignore_if_exists: bool,
 213}
 214
 215#[derive(Copy, Clone, Default)]
 216pub struct RenameOptions {
 217    pub overwrite: bool,
 218    pub ignore_if_exists: bool,
 219}
 220
 221#[derive(Copy, Clone, Default)]
 222pub struct RemoveOptions {
 223    pub recursive: bool,
 224    pub ignore_if_not_exists: bool,
 225}
 226
 227#[derive(Copy, Clone, Debug)]
 228pub struct Metadata {
 229    pub inode: u64,
 230    pub mtime: MTime,
 231    pub is_symlink: bool,
 232    pub is_dir: bool,
 233    pub len: u64,
 234    pub is_fifo: bool,
 235}
 236
 237/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
 238/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
 239/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
 240/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
 241///
 242/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
 243#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
 244#[serde(transparent)]
 245pub struct MTime(SystemTime);
 246
 247impl MTime {
 248    /// Conversion intended for persistence and testing.
 249    pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
 250        MTime(UNIX_EPOCH + Duration::new(secs, nanos))
 251    }
 252
 253    /// Conversion intended for persistence.
 254    pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
 255        self.0
 256            .duration_since(UNIX_EPOCH)
 257            .ok()
 258            .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
 259    }
 260
 261    /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
 262    /// "_for_user" is to discourage misuse - this method should not be used when making decisions
 263    /// about file dirtiness.
 264    pub fn timestamp_for_user(self) -> SystemTime {
 265        self.0
 266    }
 267
 268    /// Temporary method to split out the behavior changes from introduction of this newtype.
 269    pub fn bad_is_greater_than(self, other: MTime) -> bool {
 270        self.0 > other.0
 271    }
 272}
 273
 274impl From<proto::Timestamp> for MTime {
 275    fn from(timestamp: proto::Timestamp) -> Self {
 276        MTime(timestamp.into())
 277    }
 278}
 279
 280impl From<MTime> for proto::Timestamp {
 281    fn from(mtime: MTime) -> Self {
 282        mtime.0.into()
 283    }
 284}
 285
 286pub struct RealFs {
 287    bundled_git_binary_path: Option<PathBuf>,
 288    executor: BackgroundExecutor,
 289}
 290
 291pub trait FileHandle: Send + Sync + std::fmt::Debug {
 292    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
 293}
 294
 295impl FileHandle for std::fs::File {
 296    #[cfg(target_os = "macos")]
 297    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 298        use std::{
 299            ffi::{CStr, OsStr},
 300            os::unix::ffi::OsStrExt,
 301        };
 302
 303        let fd = self.as_fd();
 304        let mut path_buf = MaybeUninit::<[u8; libc::PATH_MAX as usize]>::uninit();
 305
 306        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
 307        if result == -1 {
 308            anyhow::bail!("fcntl returned -1".to_string());
 309        }
 310
 311        // SAFETY: `fcntl` will initialize the path buffer.
 312        let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr().cast()) };
 313        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 314        Ok(path)
 315    }
 316
 317    #[cfg(target_os = "linux")]
 318    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 319        let fd = self.as_fd();
 320        let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
 321        let new_path = std::fs::read_link(fd_path)?;
 322        if new_path
 323            .file_name()
 324            .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
 325        {
 326            anyhow::bail!("file was deleted")
 327        };
 328
 329        Ok(new_path)
 330    }
 331
 332    #[cfg(target_os = "freebsd")]
 333    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 334        use std::{
 335            ffi::{CStr, OsStr},
 336            os::unix::ffi::OsStrExt,
 337        };
 338
 339        let fd = self.as_fd();
 340        let mut kif = MaybeUninit::<libc::kinfo_file>::uninit();
 341        kif.kf_structsize = libc::KINFO_FILE_SIZE;
 342
 343        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_KINFO, kif.as_mut_ptr()) };
 344        if result == -1 {
 345            anyhow::bail!("fcntl returned -1".to_string());
 346        }
 347
 348        // SAFETY: `fcntl` will initialize the kif.
 349        let c_str = unsafe { CStr::from_ptr(kif.assume_init().kf_path.as_ptr()) };
 350        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 351        Ok(path)
 352    }
 353
 354    #[cfg(target_os = "windows")]
 355    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 356        use std::ffi::OsString;
 357        use std::os::windows::ffi::OsStringExt;
 358        use std::os::windows::io::AsRawHandle;
 359
 360        use windows::Win32::Foundation::HANDLE;
 361        use windows::Win32::Storage::FileSystem::{
 362            FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW,
 363        };
 364
 365        let handle = HANDLE(self.as_raw_handle() as _);
 366
 367        // Query required buffer size (in wide chars)
 368        let required_len =
 369            unsafe { GetFinalPathNameByHandleW(handle, &mut [], FILE_NAME_NORMALIZED) };
 370        if required_len == 0 {
 371            anyhow::bail!("GetFinalPathNameByHandleW returned 0 length");
 372        }
 373
 374        // Allocate buffer and retrieve the path
 375        let mut buf: Vec<u16> = vec![0u16; required_len as usize + 1];
 376        let written = unsafe { GetFinalPathNameByHandleW(handle, &mut buf, FILE_NAME_NORMALIZED) };
 377        if written == 0 {
 378            anyhow::bail!("GetFinalPathNameByHandleW failed to write path");
 379        }
 380
 381        let os_str: OsString = OsString::from_wide(&buf[..written as usize]);
 382        Ok(PathBuf::from(os_str))
 383    }
 384}
 385
 386pub struct RealWatcher {}
 387
 388impl RealFs {
 389    pub fn new(git_binary_path: Option<PathBuf>, executor: BackgroundExecutor) -> Self {
 390        Self {
 391            bundled_git_binary_path: git_binary_path,
 392            executor,
 393        }
 394    }
 395}
 396
 397#[async_trait::async_trait]
 398impl Fs for RealFs {
 399    async fn create_dir(&self, path: &Path) -> Result<()> {
 400        Ok(smol::fs::create_dir_all(path).await?)
 401    }
 402
 403    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 404        #[cfg(unix)]
 405        smol::fs::unix::symlink(target, path).await?;
 406
 407        #[cfg(windows)]
 408        if smol::fs::metadata(&target).await?.is_dir() {
 409            let status = smol::process::Command::new("cmd")
 410                .args(["/C", "mklink", "/J"])
 411                .args([path, target.as_path()])
 412                .status()
 413                .await?;
 414
 415            if !status.success() {
 416                return Err(anyhow::anyhow!(
 417                    "Failed to create junction from {:?} to {:?}",
 418                    path,
 419                    target
 420                ));
 421            }
 422        } else {
 423            smol::fs::windows::symlink_file(target, path).await?
 424        }
 425
 426        Ok(())
 427    }
 428
 429    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 430        let mut open_options = smol::fs::OpenOptions::new();
 431        open_options.write(true).create(true);
 432        if options.overwrite {
 433            open_options.truncate(true);
 434        } else if !options.ignore_if_exists {
 435            open_options.create_new(true);
 436        }
 437        open_options.open(path).await?;
 438        Ok(())
 439    }
 440
 441    async fn create_file_with(
 442        &self,
 443        path: &Path,
 444        content: Pin<&mut (dyn AsyncRead + Send)>,
 445    ) -> Result<()> {
 446        let mut file = smol::fs::File::create(&path).await?;
 447        futures::io::copy(content, &mut file).await?;
 448        Ok(())
 449    }
 450
 451    async fn extract_tar_file(
 452        &self,
 453        path: &Path,
 454        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 455    ) -> Result<()> {
 456        content.unpack(path).await?;
 457        Ok(())
 458    }
 459
 460    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 461        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 462            if options.ignore_if_exists {
 463                return Ok(());
 464            } else {
 465                anyhow::bail!("{target:?} already exists");
 466            }
 467        }
 468
 469        smol::fs::copy(source, target).await?;
 470        Ok(())
 471    }
 472
 473    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 474        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 475            if options.ignore_if_exists {
 476                return Ok(());
 477            } else {
 478                anyhow::bail!("{target:?} already exists");
 479            }
 480        }
 481
 482        smol::fs::rename(source, target).await?;
 483        Ok(())
 484    }
 485
 486    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 487        let result = if options.recursive {
 488            smol::fs::remove_dir_all(path).await
 489        } else {
 490            smol::fs::remove_dir(path).await
 491        };
 492        match result {
 493            Ok(()) => Ok(()),
 494            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 495                Ok(())
 496            }
 497            Err(err) => Err(err)?,
 498        }
 499    }
 500
 501    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 502        #[cfg(windows)]
 503        if let Ok(Some(metadata)) = self.metadata(path).await
 504            && metadata.is_symlink
 505            && metadata.is_dir
 506        {
 507            self.remove_dir(
 508                path,
 509                RemoveOptions {
 510                    recursive: false,
 511                    ignore_if_not_exists: true,
 512                },
 513            )
 514            .await?;
 515            return Ok(());
 516        }
 517
 518        match smol::fs::remove_file(path).await {
 519            Ok(()) => Ok(()),
 520            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 521                Ok(())
 522            }
 523            Err(err) => Err(err)?,
 524        }
 525    }
 526
 527    #[cfg(target_os = "macos")]
 528    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 529        use cocoa::{
 530            base::{id, nil},
 531            foundation::{NSAutoreleasePool, NSString},
 532        };
 533        use objc::{class, msg_send, sel, sel_impl};
 534
 535        unsafe {
 536            unsafe fn ns_string(string: &str) -> id {
 537                unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 538            }
 539
 540            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 541            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 542            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 543
 544            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 545        }
 546        Ok(())
 547    }
 548
 549    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 550    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 551        if let Ok(Some(metadata)) = self.metadata(path).await
 552            && metadata.is_symlink
 553        {
 554            // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
 555            return self.remove_file(path, RemoveOptions::default()).await;
 556        }
 557        let file = smol::fs::File::open(path).await?;
 558        match trash::trash_file(&file.as_fd()).await {
 559            Ok(_) => Ok(()),
 560            Err(err) => {
 561                log::error!("Failed to trash file: {}", err);
 562                // Trashing files can fail if you don't have a trashing dbus service configured.
 563                // In that case, delete the file directly instead.
 564                return self.remove_file(path, RemoveOptions::default()).await;
 565            }
 566        }
 567    }
 568
 569    #[cfg(target_os = "windows")]
 570    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 571        use util::paths::SanitizedPath;
 572        use windows::{
 573            Storage::{StorageDeleteOption, StorageFile},
 574            core::HSTRING,
 575        };
 576        // todo(windows)
 577        // When new version of `windows-rs` release, make this operation `async`
 578        let path = path.canonicalize()?;
 579        let path = SanitizedPath::new(&path);
 580        let path_string = path.to_string();
 581        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 582        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 583        Ok(())
 584    }
 585
 586    #[cfg(target_os = "macos")]
 587    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 588        self.trash_file(path, options).await
 589    }
 590
 591    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 592    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 593        self.trash_file(path, options).await
 594    }
 595
 596    #[cfg(target_os = "windows")]
 597    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 598        use util::paths::SanitizedPath;
 599        use windows::{
 600            Storage::{StorageDeleteOption, StorageFolder},
 601            core::HSTRING,
 602        };
 603
 604        // todo(windows)
 605        // When new version of `windows-rs` release, make this operation `async`
 606        let path = path.canonicalize()?;
 607        let path = SanitizedPath::new(&path);
 608        let path_string = path.to_string();
 609        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 610        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 611        Ok(())
 612    }
 613
 614    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
 615        Ok(Box::new(std::fs::File::open(path)?))
 616    }
 617
 618    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 619        let mut options = std::fs::OpenOptions::new();
 620        options.read(true);
 621        #[cfg(windows)]
 622        {
 623            use std::os::windows::fs::OpenOptionsExt;
 624            options.custom_flags(windows::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS.0);
 625        }
 626        Ok(Arc::new(options.open(path)?))
 627    }
 628
 629    async fn load(&self, path: &Path) -> Result<String> {
 630        let path = path.to_path_buf();
 631        let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
 632        Ok(text)
 633    }
 634
 635    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 636        let path = path.to_path_buf();
 637        let bytes = self
 638            .executor
 639            .spawn(async move { std::fs::read(path) })
 640            .await?;
 641        Ok(bytes)
 642    }
 643
 644    #[cfg(not(target_os = "windows"))]
 645    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 646        smol::unblock(move || {
 647            // Use the directory of the destination as temp dir to avoid
 648            // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 649            // See https://github.com/zed-industries/zed/pull/8437 for more details.
 650            let mut tmp_file =
 651                tempfile::NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 652            tmp_file.write_all(data.as_bytes())?;
 653            tmp_file.persist(path)?;
 654            anyhow::Ok(())
 655        })
 656        .await?;
 657
 658        Ok(())
 659    }
 660
 661    #[cfg(target_os = "windows")]
 662    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 663        smol::unblock(move || {
 664            // If temp dir is set to a different drive than the destination,
 665            // we receive error:
 666            //
 667            // failed to persist temporary file:
 668            // The system cannot move the file to a different disk drive. (os error 17)
 669            //
 670            // This is because `ReplaceFileW` does not support cross volume moves.
 671            // See the remark section: "The backup file, replaced file, and replacement file must all reside on the same volume."
 672            // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew#remarks
 673            //
 674            // So we use the directory of the destination as a temp dir to avoid it.
 675            // https://github.com/zed-industries/zed/issues/16571
 676            let temp_dir = TempDir::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 677            let temp_file = {
 678                let temp_file_path = temp_dir.path().join("temp_file");
 679                let mut file = std::fs::File::create_new(&temp_file_path)?;
 680                file.write_all(data.as_bytes())?;
 681                temp_file_path
 682            };
 683            atomic_replace(path.as_path(), temp_file.as_path())?;
 684            anyhow::Ok(())
 685        })
 686        .await?;
 687        Ok(())
 688    }
 689
 690    async fn save(
 691        &self,
 692        path: &Path,
 693        text: &Rope,
 694        line_ending: LineEnding,
 695        encoding: Encoding,
 696    ) -> Result<()> {
 697        let buffer_size = text.summary().len.min(10 * 1024);
 698        if let Some(path) = path.parent() {
 699            self.create_dir(path).await?;
 700        }
 701        let file = smol::fs::File::create(path).await?;
 702        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 703
 704        // BOM for UTF-16 is written at the start of the file here because
 705        // if BOM is written in the `encode` function of `fs::encodings`, it would be written
 706        // twice. Hence, it is written only here.
 707        if encoding.get() == encodings::UTF_16BE {
 708            // Write BOM for UTF-16BE
 709            writer.write_all(&[0xFE, 0xFF]).await?;
 710        } else if encoding.get() == encodings::UTF_16LE {
 711            // Write BOM for UTF-16LE
 712            writer.write_all(&[0xFF, 0xFE]).await?;
 713        }
 714
 715        for chunk in chunks(text, line_ending) {
 716            writer
 717                .write_all(&from_utf8(chunk.to_string(), Encoding::new(encoding.get())).await?)
 718                .await?
 719        }
 720
 721        writer.flush().await?;
 722        Ok(())
 723    }
 724
 725    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
 726        if let Some(path) = path.parent() {
 727            self.create_dir(path).await?;
 728        }
 729        let path = path.to_owned();
 730        let contents = content.to_owned();
 731        self.executor
 732            .spawn(async move {
 733                std::fs::write(path, contents)?;
 734                Ok(())
 735            })
 736            .await
 737    }
 738
 739    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 740        let path = path.to_owned();
 741        self.executor
 742            .spawn(async move {
 743                std::fs::canonicalize(&path).with_context(|| format!("canonicalizing {path:?}"))
 744            })
 745            .await
 746    }
 747
 748    async fn is_file(&self, path: &Path) -> bool {
 749        let path = path.to_owned();
 750        self.executor
 751            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) })
 752            .await
 753    }
 754
 755    async fn is_dir(&self, path: &Path) -> bool {
 756        let path = path.to_owned();
 757        self.executor
 758            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_dir()) })
 759            .await
 760    }
 761
 762    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 763        let path_buf = path.to_owned();
 764        let symlink_metadata = match self
 765            .executor
 766            .spawn(async move { std::fs::symlink_metadata(&path_buf) })
 767            .await
 768        {
 769            Ok(metadata) => metadata,
 770            Err(err) => {
 771                return match (err.kind(), err.raw_os_error()) {
 772                    (io::ErrorKind::NotFound, _) => Ok(None),
 773                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 774                    _ => Err(anyhow::Error::new(err)),
 775                };
 776            }
 777        };
 778
 779        let is_symlink = symlink_metadata.file_type().is_symlink();
 780        let metadata = if is_symlink {
 781            let path_buf = path.to_path_buf();
 782            let path_exists = self
 783                .executor
 784                .spawn(async move {
 785                    path_buf
 786                        .try_exists()
 787                        .with_context(|| format!("checking existence for path {path_buf:?}"))
 788                })
 789                .await?;
 790            if path_exists {
 791                let path_buf = path.to_path_buf();
 792                self.executor
 793                    .spawn(async move { std::fs::metadata(path_buf) })
 794                    .await
 795                    .with_context(|| "accessing symlink for path {path}")?
 796            } else {
 797                symlink_metadata
 798            }
 799        } else {
 800            symlink_metadata
 801        };
 802
 803        #[cfg(unix)]
 804        let inode = metadata.ino();
 805
 806        #[cfg(windows)]
 807        let inode = file_id(path).await?;
 808
 809        #[cfg(windows)]
 810        let is_fifo = false;
 811
 812        #[cfg(unix)]
 813        let is_fifo = metadata.file_type().is_fifo();
 814
 815        Ok(Some(Metadata {
 816            inode,
 817            mtime: MTime(metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH)),
 818            len: metadata.len(),
 819            is_symlink,
 820            is_dir: metadata.file_type().is_dir(),
 821            is_fifo,
 822        }))
 823    }
 824
 825    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 826        let path = path.to_owned();
 827        let path = self
 828            .executor
 829            .spawn(async move { std::fs::read_link(&path) })
 830            .await?;
 831        Ok(path)
 832    }
 833
 834    async fn read_dir(
 835        &self,
 836        path: &Path,
 837    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 838        let path = path.to_owned();
 839        let result = iter(
 840            self.executor
 841                .spawn(async move { std::fs::read_dir(path) })
 842                .await?,
 843        )
 844        .map(|entry| match entry {
 845            Ok(entry) => Ok(entry.path()),
 846            Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
 847        });
 848        Ok(Box::pin(result))
 849    }
 850
 851    #[cfg(target_os = "macos")]
 852    async fn watch(
 853        &self,
 854        path: &Path,
 855        latency: Duration,
 856    ) -> (
 857        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 858        Arc<dyn Watcher>,
 859    ) {
 860        use fsevent::StreamFlags;
 861
 862        let (events_tx, events_rx) = smol::channel::unbounded();
 863        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 864        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 865            events_tx,
 866            Arc::downgrade(&handles),
 867            latency,
 868        ));
 869        watcher.add(path).expect("handles can't be dropped");
 870
 871        (
 872            Box::pin(
 873                events_rx
 874                    .map(|events| {
 875                        events
 876                            .into_iter()
 877                            .map(|event| {
 878                                log::trace!("fs path event: {event:?}");
 879                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 880                                    Some(PathEventKind::Removed)
 881                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 882                                    Some(PathEventKind::Created)
 883                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED)
 884                                    | event.flags.contains(StreamFlags::ITEM_RENAMED)
 885                                {
 886                                    Some(PathEventKind::Changed)
 887                                } else {
 888                                    None
 889                                };
 890                                PathEvent {
 891                                    path: event.path,
 892                                    kind,
 893                                }
 894                            })
 895                            .collect()
 896                    })
 897                    .chain(futures::stream::once(async move {
 898                        drop(handles);
 899                        vec![]
 900                    })),
 901            ),
 902            watcher,
 903        )
 904    }
 905
 906    #[cfg(not(target_os = "macos"))]
 907    async fn watch(
 908        &self,
 909        path: &Path,
 910        latency: Duration,
 911    ) -> (
 912        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 913        Arc<dyn Watcher>,
 914    ) {
 915        use parking_lot::Mutex;
 916        use util::{ResultExt as _, paths::SanitizedPath};
 917
 918        let (tx, rx) = smol::channel::unbounded();
 919        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 920        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 921
 922        // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 923        if let Err(e) = watcher.add(path)
 924            && let Some(parent) = path.parent()
 925            && let Err(parent_e) = watcher.add(parent)
 926        {
 927            log::warn!(
 928                "Failed to watch {} and its parent directory {}:\n{e}\n{parent_e}",
 929                path.display(),
 930                parent.display()
 931            );
 932        }
 933
 934        // Check if path is a symlink and follow the target parent
 935        if let Some(mut target) = self.read_link(path).await.ok() {
 936            log::trace!("watch symlink {path:?} -> {target:?}");
 937            // Check if symlink target is relative path, if so make it absolute
 938            if target.is_relative()
 939                && let Some(parent) = path.parent()
 940            {
 941                target = parent.join(target);
 942                if let Ok(canonical) = self.canonicalize(&target).await {
 943                    target = SanitizedPath::new(&canonical).as_path().to_path_buf();
 944                }
 945            }
 946            watcher.add(&target).ok();
 947            if let Some(parent) = target.parent() {
 948                watcher.add(parent).log_err();
 949            }
 950        }
 951
 952        (
 953            Box::pin(rx.filter_map({
 954                let watcher = watcher.clone();
 955                move |_| {
 956                    let _ = watcher.clone();
 957                    let pending_paths = pending_paths.clone();
 958                    async move {
 959                        smol::Timer::after(latency).await;
 960                        let paths = std::mem::take(&mut *pending_paths.lock());
 961                        (!paths.is_empty()).then_some(paths)
 962                    }
 963                }
 964            })),
 965            watcher,
 966        )
 967    }
 968
 969    fn open_repo(
 970        &self,
 971        dotgit_path: &Path,
 972        system_git_binary_path: Option<&Path>,
 973    ) -> Option<Arc<dyn GitRepository>> {
 974        Some(Arc::new(RealGitRepository::new(
 975            dotgit_path,
 976            self.bundled_git_binary_path.clone(),
 977            system_git_binary_path.map(|path| path.to_path_buf()),
 978            self.executor.clone(),
 979        )?))
 980    }
 981
 982    async fn git_init(
 983        &self,
 984        abs_work_directory_path: &Path,
 985        fallback_branch_name: String,
 986    ) -> Result<()> {
 987        let config = new_smol_command("git")
 988            .current_dir(abs_work_directory_path)
 989            .args(&["config", "--global", "--get", "init.defaultBranch"])
 990            .output()
 991            .await?;
 992
 993        let branch_name;
 994
 995        if config.status.success() && !config.stdout.is_empty() {
 996            branch_name = String::from_utf8_lossy(&config.stdout);
 997        } else {
 998            branch_name = Cow::Borrowed(fallback_branch_name.as_str());
 999        }
1000
1001        new_smol_command("git")
1002            .current_dir(abs_work_directory_path)
1003            .args(&["init", "-b"])
1004            .arg(branch_name.trim())
1005            .output()
1006            .await?;
1007
1008        Ok(())
1009    }
1010
1011    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
1012        let output = new_smol_command("git")
1013            .current_dir(abs_work_directory)
1014            .args(&["clone", repo_url])
1015            .output()
1016            .await?;
1017
1018        if !output.status.success() {
1019            anyhow::bail!(
1020                "git clone failed: {}",
1021                String::from_utf8_lossy(&output.stderr)
1022            );
1023        }
1024
1025        Ok(())
1026    }
1027
1028    fn is_fake(&self) -> bool {
1029        false
1030    }
1031
1032    /// Checks whether the file system is case sensitive by attempting to create two files
1033    /// that have the same name except for the casing.
1034    ///
1035    /// It creates both files in a temporary directory it removes at the end.
1036    async fn is_case_sensitive(&self) -> Result<bool> {
1037        let temp_dir = TempDir::new()?;
1038        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
1039        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
1040
1041        let create_opts = CreateOptions {
1042            overwrite: false,
1043            ignore_if_exists: false,
1044        };
1045
1046        // Create file1
1047        self.create_file(&test_file_1, create_opts).await?;
1048
1049        // Now check whether it's possible to create file2
1050        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
1051            Ok(_) => Ok(true),
1052            Err(e) => {
1053                if let Some(io_error) = e.downcast_ref::<io::Error>() {
1054                    if io_error.kind() == io::ErrorKind::AlreadyExists {
1055                        Ok(false)
1056                    } else {
1057                        Err(e)
1058                    }
1059                } else {
1060                    Err(e)
1061                }
1062            }
1063        };
1064
1065        temp_dir.close()?;
1066        case_sensitive
1067    }
1068}
1069
1070#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
1071impl Watcher for RealWatcher {
1072    fn add(&self, _: &Path) -> Result<()> {
1073        Ok(())
1074    }
1075
1076    fn remove(&self, _: &Path) -> Result<()> {
1077        Ok(())
1078    }
1079}
1080
1081#[cfg(any(test, feature = "test-support"))]
1082pub struct FakeFs {
1083    this: std::sync::Weak<Self>,
1084    // Use an unfair lock to ensure tests are deterministic.
1085    state: Arc<Mutex<FakeFsState>>,
1086    executor: gpui::BackgroundExecutor,
1087}
1088
1089#[cfg(any(test, feature = "test-support"))]
1090struct FakeFsState {
1091    root: FakeFsEntry,
1092    next_inode: u64,
1093    next_mtime: SystemTime,
1094    git_event_tx: smol::channel::Sender<PathBuf>,
1095    event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
1096    events_paused: bool,
1097    buffered_events: Vec<PathEvent>,
1098    metadata_call_count: usize,
1099    read_dir_call_count: usize,
1100    path_write_counts: std::collections::HashMap<PathBuf, usize>,
1101    moves: std::collections::HashMap<u64, PathBuf>,
1102}
1103
1104#[cfg(any(test, feature = "test-support"))]
1105#[derive(Clone, Debug)]
1106enum FakeFsEntry {
1107    File {
1108        inode: u64,
1109        mtime: MTime,
1110        len: u64,
1111        content: Vec<u8>,
1112        // The path to the repository state directory, if this is a gitfile.
1113        git_dir_path: Option<PathBuf>,
1114    },
1115    Dir {
1116        inode: u64,
1117        mtime: MTime,
1118        len: u64,
1119        entries: BTreeMap<String, FakeFsEntry>,
1120        git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
1121    },
1122    Symlink {
1123        target: PathBuf,
1124    },
1125}
1126
1127#[cfg(any(test, feature = "test-support"))]
1128impl PartialEq for FakeFsEntry {
1129    fn eq(&self, other: &Self) -> bool {
1130        match (self, other) {
1131            (
1132                Self::File {
1133                    inode: l_inode,
1134                    mtime: l_mtime,
1135                    len: l_len,
1136                    content: l_content,
1137                    git_dir_path: l_git_dir_path,
1138                },
1139                Self::File {
1140                    inode: r_inode,
1141                    mtime: r_mtime,
1142                    len: r_len,
1143                    content: r_content,
1144                    git_dir_path: r_git_dir_path,
1145                },
1146            ) => {
1147                l_inode == r_inode
1148                    && l_mtime == r_mtime
1149                    && l_len == r_len
1150                    && l_content == r_content
1151                    && l_git_dir_path == r_git_dir_path
1152            }
1153            (
1154                Self::Dir {
1155                    inode: l_inode,
1156                    mtime: l_mtime,
1157                    len: l_len,
1158                    entries: l_entries,
1159                    git_repo_state: l_git_repo_state,
1160                },
1161                Self::Dir {
1162                    inode: r_inode,
1163                    mtime: r_mtime,
1164                    len: r_len,
1165                    entries: r_entries,
1166                    git_repo_state: r_git_repo_state,
1167                },
1168            ) => {
1169                let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1170                    (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1171                    (None, None) => true,
1172                    _ => false,
1173                };
1174                l_inode == r_inode
1175                    && l_mtime == r_mtime
1176                    && l_len == r_len
1177                    && l_entries == r_entries
1178                    && same_repo_state
1179            }
1180            (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1181                l_target == r_target
1182            }
1183            _ => false,
1184        }
1185    }
1186}
1187
1188#[cfg(any(test, feature = "test-support"))]
1189impl FakeFsState {
1190    fn get_and_increment_mtime(&mut self) -> MTime {
1191        let mtime = self.next_mtime;
1192        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1193        MTime(mtime)
1194    }
1195
1196    fn get_and_increment_inode(&mut self) -> u64 {
1197        let inode = self.next_inode;
1198        self.next_inode += 1;
1199        inode
1200    }
1201
1202    fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1203        let mut canonical_path = PathBuf::new();
1204        let mut path = target.to_path_buf();
1205        let mut entry_stack = Vec::new();
1206        'outer: loop {
1207            let mut path_components = path.components().peekable();
1208            let mut prefix = None;
1209            while let Some(component) = path_components.next() {
1210                match component {
1211                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1212                    Component::RootDir => {
1213                        entry_stack.clear();
1214                        entry_stack.push(&self.root);
1215                        canonical_path.clear();
1216                        match prefix {
1217                            Some(prefix_component) => {
1218                                canonical_path = PathBuf::from(prefix_component.as_os_str());
1219                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1220                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1221                            }
1222                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1223                        }
1224                    }
1225                    Component::CurDir => {}
1226                    Component::ParentDir => {
1227                        entry_stack.pop()?;
1228                        canonical_path.pop();
1229                    }
1230                    Component::Normal(name) => {
1231                        let current_entry = *entry_stack.last()?;
1232                        if let FakeFsEntry::Dir { entries, .. } = current_entry {
1233                            let entry = entries.get(name.to_str().unwrap())?;
1234                            if (path_components.peek().is_some() || follow_symlink)
1235                                && let FakeFsEntry::Symlink { target, .. } = entry
1236                            {
1237                                let mut target = target.clone();
1238                                target.extend(path_components);
1239                                path = target;
1240                                continue 'outer;
1241                            }
1242                            entry_stack.push(entry);
1243                            canonical_path = canonical_path.join(name);
1244                        } else {
1245                            return None;
1246                        }
1247                    }
1248                }
1249            }
1250            break;
1251        }
1252
1253        if entry_stack.is_empty() {
1254            None
1255        } else {
1256            Some(canonical_path)
1257        }
1258    }
1259
1260    fn try_entry(
1261        &mut self,
1262        target: &Path,
1263        follow_symlink: bool,
1264    ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1265        let canonical_path = self.canonicalize(target, follow_symlink)?;
1266
1267        let mut components = canonical_path
1268            .components()
1269            .skip_while(|component| matches!(component, Component::Prefix(_)));
1270        let Some(Component::RootDir) = components.next() else {
1271            panic!(
1272                "the path {:?} was not canonicalized properly {:?}",
1273                target, canonical_path
1274            )
1275        };
1276
1277        let mut entry = &mut self.root;
1278        for component in components {
1279            match component {
1280                Component::Normal(name) => {
1281                    if let FakeFsEntry::Dir { entries, .. } = entry {
1282                        entry = entries.get_mut(name.to_str().unwrap())?;
1283                    } else {
1284                        return None;
1285                    }
1286                }
1287                _ => {
1288                    panic!(
1289                        "the path {:?} was not canonicalized properly {:?}",
1290                        target, canonical_path
1291                    )
1292                }
1293            }
1294        }
1295
1296        Some((entry, canonical_path))
1297    }
1298
1299    fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1300        Ok(self
1301            .try_entry(target, true)
1302            .ok_or_else(|| {
1303                anyhow!(io::Error::new(
1304                    io::ErrorKind::NotFound,
1305                    format!("not found: {target:?}")
1306                ))
1307            })?
1308            .0)
1309    }
1310
1311    fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1312    where
1313        Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1314    {
1315        let path = normalize_path(path);
1316        let filename = path.file_name().context("cannot overwrite the root")?;
1317        let parent_path = path.parent().unwrap();
1318
1319        let parent = self.entry(parent_path)?;
1320        let new_entry = parent
1321            .dir_entries(parent_path)?
1322            .entry(filename.to_str().unwrap().into());
1323        callback(new_entry)
1324    }
1325
1326    fn emit_event<I, T>(&mut self, paths: I)
1327    where
1328        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1329        T: Into<PathBuf>,
1330    {
1331        self.buffered_events
1332            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1333                path: path.into(),
1334                kind,
1335            }));
1336
1337        if !self.events_paused {
1338            self.flush_events(self.buffered_events.len());
1339        }
1340    }
1341
1342    fn flush_events(&mut self, mut count: usize) {
1343        count = count.min(self.buffered_events.len());
1344        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1345        self.event_txs.retain(|(_, tx)| {
1346            let _ = tx.try_send(events.clone());
1347            !tx.is_closed()
1348        });
1349    }
1350}
1351
1352#[cfg(any(test, feature = "test-support"))]
1353pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1354    std::sync::LazyLock::new(|| OsStr::new(".git"));
1355
1356#[cfg(any(test, feature = "test-support"))]
1357impl FakeFs {
1358    /// We need to use something large enough for Windows and Unix to consider this a new file.
1359    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1360    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1361
1362    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1363        let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1364
1365        let this = Arc::new_cyclic(|this| Self {
1366            this: this.clone(),
1367            executor: executor.clone(),
1368            state: Arc::new(Mutex::new(FakeFsState {
1369                root: FakeFsEntry::Dir {
1370                    inode: 0,
1371                    mtime: MTime(UNIX_EPOCH),
1372                    len: 0,
1373                    entries: Default::default(),
1374                    git_repo_state: None,
1375                },
1376                git_event_tx: tx,
1377                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1378                next_inode: 1,
1379                event_txs: Default::default(),
1380                buffered_events: Vec::new(),
1381                events_paused: false,
1382                read_dir_call_count: 0,
1383                metadata_call_count: 0,
1384                path_write_counts: Default::default(),
1385                moves: Default::default(),
1386            })),
1387        });
1388
1389        executor.spawn({
1390            let this = this.clone();
1391            async move {
1392                while let Ok(git_event) = rx.recv().await {
1393                    if let Some(mut state) = this.state.try_lock() {
1394                        state.emit_event([(git_event, Some(PathEventKind::Changed))]);
1395                    } else {
1396                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1397                    }
1398                }
1399            }
1400        }).detach();
1401
1402        this
1403    }
1404
1405    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1406        let mut state = self.state.lock();
1407        state.next_mtime = next_mtime;
1408    }
1409
1410    pub fn get_and_increment_mtime(&self) -> MTime {
1411        let mut state = self.state.lock();
1412        state.get_and_increment_mtime()
1413    }
1414
1415    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1416        let mut state = self.state.lock();
1417        let path = path.as_ref();
1418        let new_mtime = state.get_and_increment_mtime();
1419        let new_inode = state.get_and_increment_inode();
1420        state
1421            .write_path(path, move |entry| {
1422                match entry {
1423                    btree_map::Entry::Vacant(e) => {
1424                        e.insert(FakeFsEntry::File {
1425                            inode: new_inode,
1426                            mtime: new_mtime,
1427                            content: Vec::new(),
1428                            len: 0,
1429                            git_dir_path: None,
1430                        });
1431                    }
1432                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1433                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1434                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1435                        FakeFsEntry::Symlink { .. } => {}
1436                    },
1437                }
1438                Ok(())
1439            })
1440            .unwrap();
1441        state.emit_event([(path.to_path_buf(), Some(PathEventKind::Changed))]);
1442    }
1443
1444    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1445        self.write_file_internal(path, content, true).unwrap()
1446    }
1447
1448    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1449        let mut state = self.state.lock();
1450        let path = path.as_ref();
1451        let file = FakeFsEntry::Symlink { target };
1452        state
1453            .write_path(path.as_ref(), move |e| match e {
1454                btree_map::Entry::Vacant(e) => {
1455                    e.insert(file);
1456                    Ok(())
1457                }
1458                btree_map::Entry::Occupied(mut e) => {
1459                    *e.get_mut() = file;
1460                    Ok(())
1461                }
1462            })
1463            .unwrap();
1464        state.emit_event([(path, Some(PathEventKind::Created))]);
1465    }
1466
1467    fn write_file_internal(
1468        &self,
1469        path: impl AsRef<Path>,
1470        new_content: Vec<u8>,
1471        recreate_inode: bool,
1472    ) -> Result<()> {
1473        let mut state = self.state.lock();
1474        let path_buf = path.as_ref().to_path_buf();
1475        *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1476        let new_inode = state.get_and_increment_inode();
1477        let new_mtime = state.get_and_increment_mtime();
1478        let new_len = new_content.len() as u64;
1479        let mut kind = None;
1480        state.write_path(path.as_ref(), |entry| {
1481            match entry {
1482                btree_map::Entry::Vacant(e) => {
1483                    kind = Some(PathEventKind::Created);
1484                    e.insert(FakeFsEntry::File {
1485                        inode: new_inode,
1486                        mtime: new_mtime,
1487                        len: new_len,
1488                        content: new_content,
1489                        git_dir_path: None,
1490                    });
1491                }
1492                btree_map::Entry::Occupied(mut e) => {
1493                    kind = Some(PathEventKind::Changed);
1494                    if let FakeFsEntry::File {
1495                        inode,
1496                        mtime,
1497                        len,
1498                        content,
1499                        ..
1500                    } = e.get_mut()
1501                    {
1502                        *mtime = new_mtime;
1503                        *content = new_content;
1504                        *len = new_len;
1505                        if recreate_inode {
1506                            *inode = new_inode;
1507                        }
1508                    } else {
1509                        anyhow::bail!("not a file")
1510                    }
1511                }
1512            }
1513            Ok(())
1514        })?;
1515        state.emit_event([(path.as_ref(), kind)]);
1516        Ok(())
1517    }
1518
1519    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1520        let path = path.as_ref();
1521        let path = normalize_path(path);
1522        let mut state = self.state.lock();
1523        let entry = state.entry(&path)?;
1524        entry.file_content(&path).cloned()
1525    }
1526
1527    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1528        let path = path.as_ref();
1529        let path = normalize_path(path);
1530        self.simulate_random_delay().await;
1531        let mut state = self.state.lock();
1532        let entry = state.entry(&path)?;
1533        entry.file_content(&path).cloned()
1534    }
1535
1536    pub fn pause_events(&self) {
1537        self.state.lock().events_paused = true;
1538    }
1539
1540    pub fn unpause_events_and_flush(&self) {
1541        self.state.lock().events_paused = false;
1542        self.flush_events(usize::MAX);
1543    }
1544
1545    pub fn buffered_event_count(&self) -> usize {
1546        self.state.lock().buffered_events.len()
1547    }
1548
1549    pub fn flush_events(&self, count: usize) {
1550        self.state.lock().flush_events(count);
1551    }
1552
1553    pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1554        self.state.lock().entry(target).cloned()
1555    }
1556
1557    pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1558        let mut state = self.state.lock();
1559        state.write_path(target, |entry| {
1560            match entry {
1561                btree_map::Entry::Vacant(vacant_entry) => {
1562                    vacant_entry.insert(new_entry);
1563                }
1564                btree_map::Entry::Occupied(mut occupied_entry) => {
1565                    occupied_entry.insert(new_entry);
1566                }
1567            }
1568            Ok(())
1569        })
1570    }
1571
1572    #[must_use]
1573    pub fn insert_tree<'a>(
1574        &'a self,
1575        path: impl 'a + AsRef<Path> + Send,
1576        tree: serde_json::Value,
1577    ) -> futures::future::BoxFuture<'a, ()> {
1578        use futures::FutureExt as _;
1579        use serde_json::Value::*;
1580
1581        async move {
1582            let path = path.as_ref();
1583
1584            match tree {
1585                Object(map) => {
1586                    self.create_dir(path).await.unwrap();
1587                    for (name, contents) in map {
1588                        let mut path = PathBuf::from(path);
1589                        path.push(name);
1590                        self.insert_tree(&path, contents).await;
1591                    }
1592                }
1593                Null => {
1594                    self.create_dir(path).await.unwrap();
1595                }
1596                String(contents) => {
1597                    self.insert_file(&path, contents.into_bytes()).await;
1598                }
1599                _ => {
1600                    panic!("JSON object must contain only objects, strings, or null");
1601                }
1602            }
1603        }
1604        .boxed()
1605    }
1606
1607    pub fn insert_tree_from_real_fs<'a>(
1608        &'a self,
1609        path: impl 'a + AsRef<Path> + Send,
1610        src_path: impl 'a + AsRef<Path> + Send,
1611    ) -> futures::future::BoxFuture<'a, ()> {
1612        use futures::FutureExt as _;
1613
1614        async move {
1615            let path = path.as_ref();
1616            if std::fs::metadata(&src_path).unwrap().is_file() {
1617                let contents = std::fs::read(src_path).unwrap();
1618                self.insert_file(path, contents).await;
1619            } else {
1620                self.create_dir(path).await.unwrap();
1621                for entry in std::fs::read_dir(&src_path).unwrap() {
1622                    let entry = entry.unwrap();
1623                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1624                        .await;
1625                }
1626            }
1627        }
1628        .boxed()
1629    }
1630
1631    pub fn with_git_state_and_paths<T, F>(
1632        &self,
1633        dot_git: &Path,
1634        emit_git_event: bool,
1635        f: F,
1636    ) -> Result<T>
1637    where
1638        F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1639    {
1640        let mut state = self.state.lock();
1641        let git_event_tx = state.git_event_tx.clone();
1642        let entry = state.entry(dot_git).context("open .git")?;
1643
1644        if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1645            let repo_state = git_repo_state.get_or_insert_with(|| {
1646                log::debug!("insert git state for {dot_git:?}");
1647                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1648            });
1649            let mut repo_state = repo_state.lock();
1650
1651            let result = f(&mut repo_state, dot_git, dot_git);
1652
1653            drop(repo_state);
1654            if emit_git_event {
1655                state.emit_event([(dot_git, Some(PathEventKind::Changed))]);
1656            }
1657
1658            Ok(result)
1659        } else if let FakeFsEntry::File {
1660            content,
1661            git_dir_path,
1662            ..
1663        } = &mut *entry
1664        {
1665            let path = match git_dir_path {
1666                Some(path) => path,
1667                None => {
1668                    let path = std::str::from_utf8(content)
1669                        .ok()
1670                        .and_then(|content| content.strip_prefix("gitdir:"))
1671                        .context("not a valid gitfile")?
1672                        .trim();
1673                    git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1674                }
1675            }
1676            .clone();
1677            let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1678                anyhow::bail!("pointed-to git dir {path:?} not found")
1679            };
1680            let FakeFsEntry::Dir {
1681                git_repo_state,
1682                entries,
1683                ..
1684            } = git_dir_entry
1685            else {
1686                anyhow::bail!("gitfile points to a non-directory")
1687            };
1688            let common_dir = if let Some(child) = entries.get("commondir") {
1689                Path::new(
1690                    std::str::from_utf8(child.file_content("commondir".as_ref())?)
1691                        .context("commondir content")?,
1692                )
1693                .to_owned()
1694            } else {
1695                canonical_path.clone()
1696            };
1697            let repo_state = git_repo_state.get_or_insert_with(|| {
1698                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1699            });
1700            let mut repo_state = repo_state.lock();
1701
1702            let result = f(&mut repo_state, &canonical_path, &common_dir);
1703
1704            if emit_git_event {
1705                drop(repo_state);
1706                state.emit_event([(canonical_path, Some(PathEventKind::Changed))]);
1707            }
1708
1709            Ok(result)
1710        } else {
1711            anyhow::bail!("not a valid git repository");
1712        }
1713    }
1714
1715    pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1716    where
1717        F: FnOnce(&mut FakeGitRepositoryState) -> T,
1718    {
1719        self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1720    }
1721
1722    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1723        self.with_git_state(dot_git, true, |state| {
1724            let branch = branch.map(Into::into);
1725            state.branches.extend(branch.clone());
1726            state.current_branch_name = branch
1727        })
1728        .unwrap();
1729    }
1730
1731    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1732        self.with_git_state(dot_git, true, |state| {
1733            if let Some(first) = branches.first()
1734                && state.current_branch_name.is_none()
1735            {
1736                state.current_branch_name = Some(first.to_string())
1737            }
1738            state
1739                .branches
1740                .extend(branches.iter().map(ToString::to_string));
1741        })
1742        .unwrap();
1743    }
1744
1745    pub fn set_unmerged_paths_for_repo(
1746        &self,
1747        dot_git: &Path,
1748        unmerged_state: &[(RepoPath, UnmergedStatus)],
1749    ) {
1750        self.with_git_state(dot_git, true, |state| {
1751            state.unmerged_paths.clear();
1752            state.unmerged_paths.extend(
1753                unmerged_state
1754                    .iter()
1755                    .map(|(path, content)| (path.clone(), *content)),
1756            );
1757        })
1758        .unwrap();
1759    }
1760
1761    pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(&str, String)]) {
1762        self.with_git_state(dot_git, true, |state| {
1763            state.index_contents.clear();
1764            state.index_contents.extend(
1765                index_state
1766                    .iter()
1767                    .map(|(path, content)| (repo_path(path), content.clone())),
1768            );
1769        })
1770        .unwrap();
1771    }
1772
1773    pub fn set_head_for_repo(
1774        &self,
1775        dot_git: &Path,
1776        head_state: &[(&str, String)],
1777        sha: impl Into<String>,
1778    ) {
1779        self.with_git_state(dot_git, true, |state| {
1780            state.head_contents.clear();
1781            state.head_contents.extend(
1782                head_state
1783                    .iter()
1784                    .map(|(path, content)| (repo_path(path), content.clone())),
1785            );
1786            state.refs.insert("HEAD".into(), sha.into());
1787        })
1788        .unwrap();
1789    }
1790
1791    pub fn set_head_and_index_for_repo(&self, dot_git: &Path, contents_by_path: &[(&str, String)]) {
1792        self.with_git_state(dot_git, true, |state| {
1793            state.head_contents.clear();
1794            state.head_contents.extend(
1795                contents_by_path
1796                    .iter()
1797                    .map(|(path, contents)| (repo_path(path), contents.clone())),
1798            );
1799            state.index_contents = state.head_contents.clone();
1800        })
1801        .unwrap();
1802    }
1803
1804    pub fn set_merge_base_content_for_repo(
1805        &self,
1806        dot_git: &Path,
1807        contents_by_path: &[(&str, String)],
1808    ) {
1809        self.with_git_state(dot_git, true, |state| {
1810            use git::Oid;
1811
1812            state.merge_base_contents.clear();
1813            let oids = (1..)
1814                .map(|n| n.to_string())
1815                .map(|n| Oid::from_bytes(n.repeat(20).as_bytes()).unwrap());
1816            for ((path, content), oid) in contents_by_path.iter().zip(oids) {
1817                state.merge_base_contents.insert(repo_path(path), oid);
1818                state.oids.insert(oid, content.clone());
1819            }
1820        })
1821        .unwrap();
1822    }
1823
1824    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1825        self.with_git_state(dot_git, true, |state| {
1826            state.blames.clear();
1827            state.blames.extend(blames);
1828        })
1829        .unwrap();
1830    }
1831
1832    /// Put the given git repository into a state with the given status,
1833    /// by mutating the head, index, and unmerged state.
1834    pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&str, FileStatus)]) {
1835        let workdir_path = dot_git.parent().unwrap();
1836        let workdir_contents = self.files_with_contents(workdir_path);
1837        self.with_git_state(dot_git, true, |state| {
1838            state.index_contents.clear();
1839            state.head_contents.clear();
1840            state.unmerged_paths.clear();
1841            for (path, content) in workdir_contents {
1842                use util::{paths::PathStyle, rel_path::RelPath};
1843
1844                let repo_path: RepoPath = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap().into();
1845                let status = statuses
1846                    .iter()
1847                    .find_map(|(p, status)| (*p == repo_path.as_unix_str()).then_some(status));
1848                let mut content = String::from_utf8_lossy(&content).to_string();
1849
1850                let mut index_content = None;
1851                let mut head_content = None;
1852                match status {
1853                    None => {
1854                        index_content = Some(content.clone());
1855                        head_content = Some(content);
1856                    }
1857                    Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1858                    Some(FileStatus::Unmerged(unmerged_status)) => {
1859                        state
1860                            .unmerged_paths
1861                            .insert(repo_path.clone(), *unmerged_status);
1862                        content.push_str(" (unmerged)");
1863                        index_content = Some(content.clone());
1864                        head_content = Some(content);
1865                    }
1866                    Some(FileStatus::Tracked(TrackedStatus {
1867                        index_status,
1868                        worktree_status,
1869                    })) => {
1870                        match worktree_status {
1871                            StatusCode::Modified => {
1872                                let mut content = content.clone();
1873                                content.push_str(" (modified in working copy)");
1874                                index_content = Some(content);
1875                            }
1876                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1877                                index_content = Some(content.clone());
1878                            }
1879                            StatusCode::Added => {}
1880                            StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1881                                panic!("cannot create these statuses for an existing file");
1882                            }
1883                        };
1884                        match index_status {
1885                            StatusCode::Modified => {
1886                                let mut content = index_content.clone().expect(
1887                                    "file cannot be both modified in index and created in working copy",
1888                                );
1889                                content.push_str(" (modified in index)");
1890                                head_content = Some(content);
1891                            }
1892                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1893                                head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1894                            }
1895                            StatusCode::Added => {}
1896                            StatusCode::Deleted  => {
1897                                head_content = Some("".into());
1898                            }
1899                            StatusCode::Renamed | StatusCode::Copied => {
1900                                panic!("cannot create these statuses for an existing file");
1901                            }
1902                        };
1903                    }
1904                };
1905
1906                if let Some(content) = index_content {
1907                    state.index_contents.insert(repo_path.clone(), content);
1908                }
1909                if let Some(content) = head_content {
1910                    state.head_contents.insert(repo_path.clone(), content);
1911                }
1912            }
1913        }).unwrap();
1914    }
1915
1916    pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1917        self.with_git_state(dot_git, true, |state| {
1918            state.simulated_index_write_error_message = message;
1919        })
1920        .unwrap();
1921    }
1922
1923    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1924        let mut result = Vec::new();
1925        let mut queue = collections::VecDeque::new();
1926        let state = &*self.state.lock();
1927        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1928        while let Some((path, entry)) = queue.pop_front() {
1929            if let FakeFsEntry::Dir { entries, .. } = entry {
1930                for (name, entry) in entries {
1931                    queue.push_back((path.join(name), entry));
1932                }
1933            }
1934            if include_dot_git
1935                || !path
1936                    .components()
1937                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1938            {
1939                result.push(path);
1940            }
1941        }
1942        result
1943    }
1944
1945    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1946        let mut result = Vec::new();
1947        let mut queue = collections::VecDeque::new();
1948        let state = &*self.state.lock();
1949        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1950        while let Some((path, entry)) = queue.pop_front() {
1951            if let FakeFsEntry::Dir { entries, .. } = entry {
1952                for (name, entry) in entries {
1953                    queue.push_back((path.join(name), entry));
1954                }
1955                if include_dot_git
1956                    || !path
1957                        .components()
1958                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1959                {
1960                    result.push(path);
1961                }
1962            }
1963        }
1964        result
1965    }
1966
1967    pub fn files(&self) -> Vec<PathBuf> {
1968        let mut result = Vec::new();
1969        let mut queue = collections::VecDeque::new();
1970        let state = &*self.state.lock();
1971        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1972        while let Some((path, entry)) = queue.pop_front() {
1973            match entry {
1974                FakeFsEntry::File { .. } => result.push(path),
1975                FakeFsEntry::Dir { entries, .. } => {
1976                    for (name, entry) in entries {
1977                        queue.push_back((path.join(name), entry));
1978                    }
1979                }
1980                FakeFsEntry::Symlink { .. } => {}
1981            }
1982        }
1983        result
1984    }
1985
1986    pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1987        let mut result = Vec::new();
1988        let mut queue = collections::VecDeque::new();
1989        let state = &*self.state.lock();
1990        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1991        while let Some((path, entry)) = queue.pop_front() {
1992            match entry {
1993                FakeFsEntry::File { content, .. } => {
1994                    if path.starts_with(prefix) {
1995                        result.push((path, content.clone()));
1996                    }
1997                }
1998                FakeFsEntry::Dir { entries, .. } => {
1999                    for (name, entry) in entries {
2000                        queue.push_back((path.join(name), entry));
2001                    }
2002                }
2003                FakeFsEntry::Symlink { .. } => {}
2004            }
2005        }
2006        result
2007    }
2008
2009    /// How many `read_dir` calls have been issued.
2010    pub fn read_dir_call_count(&self) -> usize {
2011        self.state.lock().read_dir_call_count
2012    }
2013
2014    pub fn watched_paths(&self) -> Vec<PathBuf> {
2015        let state = self.state.lock();
2016        state
2017            .event_txs
2018            .iter()
2019            .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
2020            .collect()
2021    }
2022
2023    /// How many `metadata` calls have been issued.
2024    pub fn metadata_call_count(&self) -> usize {
2025        self.state.lock().metadata_call_count
2026    }
2027
2028    /// How many write operations have been issued for a specific path.
2029    pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
2030        let path = path.as_ref().to_path_buf();
2031        self.state
2032            .lock()
2033            .path_write_counts
2034            .get(&path)
2035            .copied()
2036            .unwrap_or(0)
2037    }
2038
2039    pub fn emit_fs_event(&self, path: impl Into<PathBuf>, event: Option<PathEventKind>) {
2040        self.state.lock().emit_event(std::iter::once((path, event)));
2041    }
2042
2043    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
2044        self.executor.simulate_random_delay()
2045    }
2046}
2047
2048#[cfg(any(test, feature = "test-support"))]
2049impl FakeFsEntry {
2050    fn is_file(&self) -> bool {
2051        matches!(self, Self::File { .. })
2052    }
2053
2054    fn is_symlink(&self) -> bool {
2055        matches!(self, Self::Symlink { .. })
2056    }
2057
2058    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
2059        if let Self::File { content, .. } = self {
2060            Ok(content)
2061        } else {
2062            anyhow::bail!("not a file: {path:?}");
2063        }
2064    }
2065
2066    fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
2067        if let Self::Dir { entries, .. } = self {
2068            Ok(entries)
2069        } else {
2070            anyhow::bail!("not a directory: {path:?}");
2071        }
2072    }
2073}
2074
2075#[cfg(any(test, feature = "test-support"))]
2076struct FakeWatcher {
2077    tx: smol::channel::Sender<Vec<PathEvent>>,
2078    original_path: PathBuf,
2079    fs_state: Arc<Mutex<FakeFsState>>,
2080    prefixes: Mutex<Vec<PathBuf>>,
2081}
2082
2083#[cfg(any(test, feature = "test-support"))]
2084impl Watcher for FakeWatcher {
2085    fn add(&self, path: &Path) -> Result<()> {
2086        if path.starts_with(&self.original_path) {
2087            return Ok(());
2088        }
2089        self.fs_state
2090            .try_lock()
2091            .unwrap()
2092            .event_txs
2093            .push((path.to_owned(), self.tx.clone()));
2094        self.prefixes.lock().push(path.to_owned());
2095        Ok(())
2096    }
2097
2098    fn remove(&self, _: &Path) -> Result<()> {
2099        Ok(())
2100    }
2101}
2102
2103#[cfg(any(test, feature = "test-support"))]
2104#[derive(Debug)]
2105struct FakeHandle {
2106    inode: u64,
2107}
2108
2109#[cfg(any(test, feature = "test-support"))]
2110impl FileHandle for FakeHandle {
2111    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
2112        let fs = fs.as_fake();
2113        let mut state = fs.state.lock();
2114        let Some(target) = state.moves.get(&self.inode).cloned() else {
2115            anyhow::bail!("fake fd not moved")
2116        };
2117
2118        if state.try_entry(&target, false).is_some() {
2119            return Ok(target);
2120        }
2121        anyhow::bail!("fake fd target not found")
2122    }
2123}
2124
2125#[cfg(any(test, feature = "test-support"))]
2126#[async_trait::async_trait]
2127impl Fs for FakeFs {
2128    async fn create_dir(&self, path: &Path) -> Result<()> {
2129        self.simulate_random_delay().await;
2130
2131        let mut created_dirs = Vec::new();
2132        let mut cur_path = PathBuf::new();
2133        for component in path.components() {
2134            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
2135            cur_path.push(component);
2136            if should_skip {
2137                continue;
2138            }
2139            let mut state = self.state.lock();
2140
2141            let inode = state.get_and_increment_inode();
2142            let mtime = state.get_and_increment_mtime();
2143            state.write_path(&cur_path, |entry| {
2144                entry.or_insert_with(|| {
2145                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
2146                    FakeFsEntry::Dir {
2147                        inode,
2148                        mtime,
2149                        len: 0,
2150                        entries: Default::default(),
2151                        git_repo_state: None,
2152                    }
2153                });
2154                Ok(())
2155            })?
2156        }
2157
2158        self.state.lock().emit_event(created_dirs);
2159        Ok(())
2160    }
2161
2162    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2163        self.simulate_random_delay().await;
2164        let mut state = self.state.lock();
2165        let inode = state.get_and_increment_inode();
2166        let mtime = state.get_and_increment_mtime();
2167        let file = FakeFsEntry::File {
2168            inode,
2169            mtime,
2170            len: 0,
2171            content: Vec::new(),
2172            git_dir_path: None,
2173        };
2174        let mut kind = Some(PathEventKind::Created);
2175        state.write_path(path, |entry| {
2176            match entry {
2177                btree_map::Entry::Occupied(mut e) => {
2178                    if options.overwrite {
2179                        kind = Some(PathEventKind::Changed);
2180                        *e.get_mut() = file;
2181                    } else if !options.ignore_if_exists {
2182                        anyhow::bail!("path already exists: {path:?}");
2183                    }
2184                }
2185                btree_map::Entry::Vacant(e) => {
2186                    e.insert(file);
2187                }
2188            }
2189            Ok(())
2190        })?;
2191        state.emit_event([(path, kind)]);
2192        Ok(())
2193    }
2194
2195    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2196        let mut state = self.state.lock();
2197        let file = FakeFsEntry::Symlink { target };
2198        state
2199            .write_path(path.as_ref(), move |e| match e {
2200                btree_map::Entry::Vacant(e) => {
2201                    e.insert(file);
2202                    Ok(())
2203                }
2204                btree_map::Entry::Occupied(mut e) => {
2205                    *e.get_mut() = file;
2206                    Ok(())
2207                }
2208            })
2209            .unwrap();
2210        state.emit_event([(path, Some(PathEventKind::Created))]);
2211
2212        Ok(())
2213    }
2214
2215    async fn create_file_with(
2216        &self,
2217        path: &Path,
2218        mut content: Pin<&mut (dyn AsyncRead + Send)>,
2219    ) -> Result<()> {
2220        let mut bytes = Vec::new();
2221        content.read_to_end(&mut bytes).await?;
2222        self.write_file_internal(path, bytes, true)?;
2223        Ok(())
2224    }
2225
2226    async fn extract_tar_file(
2227        &self,
2228        path: &Path,
2229        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2230    ) -> Result<()> {
2231        let mut entries = content.entries()?;
2232        while let Some(entry) = entries.next().await {
2233            let mut entry = entry?;
2234            if entry.header().entry_type().is_file() {
2235                let path = path.join(entry.path()?.as_ref());
2236                let mut bytes = Vec::new();
2237                entry.read_to_end(&mut bytes).await?;
2238                self.create_dir(path.parent().unwrap()).await?;
2239                self.write_file_internal(&path, bytes, true)?;
2240            }
2241        }
2242        Ok(())
2243    }
2244
2245    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2246        self.simulate_random_delay().await;
2247
2248        let old_path = normalize_path(old_path);
2249        let new_path = normalize_path(new_path);
2250
2251        let mut state = self.state.lock();
2252        let moved_entry = state.write_path(&old_path, |e| {
2253            if let btree_map::Entry::Occupied(e) = e {
2254                Ok(e.get().clone())
2255            } else {
2256                anyhow::bail!("path does not exist: {old_path:?}")
2257            }
2258        })?;
2259
2260        let inode = match moved_entry {
2261            FakeFsEntry::File { inode, .. } => inode,
2262            FakeFsEntry::Dir { inode, .. } => inode,
2263            _ => 0,
2264        };
2265
2266        state.moves.insert(inode, new_path.clone());
2267
2268        state.write_path(&new_path, |e| {
2269            match e {
2270                btree_map::Entry::Occupied(mut e) => {
2271                    if options.overwrite {
2272                        *e.get_mut() = moved_entry;
2273                    } else if !options.ignore_if_exists {
2274                        anyhow::bail!("path already exists: {new_path:?}");
2275                    }
2276                }
2277                btree_map::Entry::Vacant(e) => {
2278                    e.insert(moved_entry);
2279                }
2280            }
2281            Ok(())
2282        })?;
2283
2284        state
2285            .write_path(&old_path, |e| {
2286                if let btree_map::Entry::Occupied(e) = e {
2287                    Ok(e.remove())
2288                } else {
2289                    unreachable!()
2290                }
2291            })
2292            .unwrap();
2293
2294        state.emit_event([
2295            (old_path, Some(PathEventKind::Removed)),
2296            (new_path, Some(PathEventKind::Created)),
2297        ]);
2298        Ok(())
2299    }
2300
2301    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2302        self.simulate_random_delay().await;
2303
2304        let source = normalize_path(source);
2305        let target = normalize_path(target);
2306        let mut state = self.state.lock();
2307        let mtime = state.get_and_increment_mtime();
2308        let inode = state.get_and_increment_inode();
2309        let source_entry = state.entry(&source)?;
2310        let content = source_entry.file_content(&source)?.clone();
2311        let mut kind = Some(PathEventKind::Created);
2312        state.write_path(&target, |e| match e {
2313            btree_map::Entry::Occupied(e) => {
2314                if options.overwrite {
2315                    kind = Some(PathEventKind::Changed);
2316                    Ok(Some(e.get().clone()))
2317                } else if !options.ignore_if_exists {
2318                    anyhow::bail!("{target:?} already exists");
2319                } else {
2320                    Ok(None)
2321                }
2322            }
2323            btree_map::Entry::Vacant(e) => Ok(Some(
2324                e.insert(FakeFsEntry::File {
2325                    inode,
2326                    mtime,
2327                    len: content.len() as u64,
2328                    content,
2329                    git_dir_path: None,
2330                })
2331                .clone(),
2332            )),
2333        })?;
2334        state.emit_event([(target, kind)]);
2335        Ok(())
2336    }
2337
2338    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2339        self.simulate_random_delay().await;
2340
2341        let path = normalize_path(path);
2342        let parent_path = path.parent().context("cannot remove the root")?;
2343        let base_name = path.file_name().context("cannot remove the root")?;
2344
2345        let mut state = self.state.lock();
2346        let parent_entry = state.entry(parent_path)?;
2347        let entry = parent_entry
2348            .dir_entries(parent_path)?
2349            .entry(base_name.to_str().unwrap().into());
2350
2351        match entry {
2352            btree_map::Entry::Vacant(_) => {
2353                if !options.ignore_if_not_exists {
2354                    anyhow::bail!("{path:?} does not exist");
2355                }
2356            }
2357            btree_map::Entry::Occupied(mut entry) => {
2358                {
2359                    let children = entry.get_mut().dir_entries(&path)?;
2360                    if !options.recursive && !children.is_empty() {
2361                        anyhow::bail!("{path:?} is not empty");
2362                    }
2363                }
2364                entry.remove();
2365            }
2366        }
2367        state.emit_event([(path, Some(PathEventKind::Removed))]);
2368        Ok(())
2369    }
2370
2371    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2372        self.simulate_random_delay().await;
2373
2374        let path = normalize_path(path);
2375        let parent_path = path.parent().context("cannot remove the root")?;
2376        let base_name = path.file_name().unwrap();
2377        let mut state = self.state.lock();
2378        let parent_entry = state.entry(parent_path)?;
2379        let entry = parent_entry
2380            .dir_entries(parent_path)?
2381            .entry(base_name.to_str().unwrap().into());
2382        match entry {
2383            btree_map::Entry::Vacant(_) => {
2384                if !options.ignore_if_not_exists {
2385                    anyhow::bail!("{path:?} does not exist");
2386                }
2387            }
2388            btree_map::Entry::Occupied(mut entry) => {
2389                entry.get_mut().file_content(&path)?;
2390                entry.remove();
2391            }
2392        }
2393        state.emit_event([(path, Some(PathEventKind::Removed))]);
2394        Ok(())
2395    }
2396
2397    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2398        let bytes = self.load_internal(path).await?;
2399        Ok(Box::new(io::Cursor::new(bytes)))
2400    }
2401
2402    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2403        self.simulate_random_delay().await;
2404        let mut state = self.state.lock();
2405        let inode = match state.entry(path)? {
2406            FakeFsEntry::File { inode, .. } => *inode,
2407            FakeFsEntry::Dir { inode, .. } => *inode,
2408            _ => unreachable!(),
2409        };
2410        Ok(Arc::new(FakeHandle { inode }))
2411    }
2412
2413    async fn load(&self, path: &Path) -> Result<String> {
2414        let content = self.load_internal(path).await?;
2415        Ok(String::from_utf8(content)?)
2416    }
2417
2418    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2419        self.load_internal(path).await
2420    }
2421
2422    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2423        self.simulate_random_delay().await;
2424        let path = normalize_path(path.as_path());
2425        if let Some(path) = path.parent() {
2426            self.create_dir(path).await?;
2427        }
2428        self.write_file_internal(path, data.into_bytes(), true)?;
2429        Ok(())
2430    }
2431
2432    async fn save(
2433        &self,
2434        path: &Path,
2435        text: &Rope,
2436        line_ending: LineEnding,
2437        encoding: Encoding,
2438    ) -> Result<()> {
2439        use encodings::from_utf8;
2440
2441        self.simulate_random_delay().await;
2442        let path = normalize_path(path);
2443        let content = chunks(text, line_ending).collect::<String>();
2444        if let Some(path) = path.parent() {
2445            self.create_dir(path).await?;
2446        }
2447        self.write_file_internal(path, from_utf8(content, encoding).await?, false)?;
2448        Ok(())
2449    }
2450
2451    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2452        self.simulate_random_delay().await;
2453        let path = normalize_path(path);
2454        if let Some(path) = path.parent() {
2455            self.create_dir(path).await?;
2456        }
2457        self.write_file_internal(path, content.to_vec(), false)?;
2458        Ok(())
2459    }
2460
2461    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2462        let path = normalize_path(path);
2463        self.simulate_random_delay().await;
2464        let state = self.state.lock();
2465        let canonical_path = state
2466            .canonicalize(&path, true)
2467            .with_context(|| format!("path does not exist: {path:?}"))?;
2468        Ok(canonical_path)
2469    }
2470
2471    async fn is_file(&self, path: &Path) -> bool {
2472        let path = normalize_path(path);
2473        self.simulate_random_delay().await;
2474        let mut state = self.state.lock();
2475        if let Some((entry, _)) = state.try_entry(&path, true) {
2476            entry.is_file()
2477        } else {
2478            false
2479        }
2480    }
2481
2482    async fn is_dir(&self, path: &Path) -> bool {
2483        self.metadata(path)
2484            .await
2485            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2486    }
2487
2488    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2489        self.simulate_random_delay().await;
2490        let path = normalize_path(path);
2491        let mut state = self.state.lock();
2492        state.metadata_call_count += 1;
2493        if let Some((mut entry, _)) = state.try_entry(&path, false) {
2494            let is_symlink = entry.is_symlink();
2495            if is_symlink {
2496                if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2497                    entry = e;
2498                } else {
2499                    return Ok(None);
2500                }
2501            }
2502
2503            Ok(Some(match &*entry {
2504                FakeFsEntry::File {
2505                    inode, mtime, len, ..
2506                } => Metadata {
2507                    inode: *inode,
2508                    mtime: *mtime,
2509                    len: *len,
2510                    is_dir: false,
2511                    is_symlink,
2512                    is_fifo: false,
2513                },
2514                FakeFsEntry::Dir {
2515                    inode, mtime, len, ..
2516                } => Metadata {
2517                    inode: *inode,
2518                    mtime: *mtime,
2519                    len: *len,
2520                    is_dir: true,
2521                    is_symlink,
2522                    is_fifo: false,
2523                },
2524                FakeFsEntry::Symlink { .. } => unreachable!(),
2525            }))
2526        } else {
2527            Ok(None)
2528        }
2529    }
2530
2531    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2532        self.simulate_random_delay().await;
2533        let path = normalize_path(path);
2534        let mut state = self.state.lock();
2535        let (entry, _) = state
2536            .try_entry(&path, false)
2537            .with_context(|| format!("path does not exist: {path:?}"))?;
2538        if let FakeFsEntry::Symlink { target } = entry {
2539            Ok(target.clone())
2540        } else {
2541            anyhow::bail!("not a symlink: {path:?}")
2542        }
2543    }
2544
2545    async fn read_dir(
2546        &self,
2547        path: &Path,
2548    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2549        self.simulate_random_delay().await;
2550        let path = normalize_path(path);
2551        let mut state = self.state.lock();
2552        state.read_dir_call_count += 1;
2553        let entry = state.entry(&path)?;
2554        let children = entry.dir_entries(&path)?;
2555        let paths = children
2556            .keys()
2557            .map(|file_name| Ok(path.join(file_name)))
2558            .collect::<Vec<_>>();
2559        Ok(Box::pin(futures::stream::iter(paths)))
2560    }
2561
2562    async fn watch(
2563        &self,
2564        path: &Path,
2565        _: Duration,
2566    ) -> (
2567        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2568        Arc<dyn Watcher>,
2569    ) {
2570        self.simulate_random_delay().await;
2571        let (tx, rx) = smol::channel::unbounded();
2572        let path = path.to_path_buf();
2573        self.state.lock().event_txs.push((path.clone(), tx.clone()));
2574        let executor = self.executor.clone();
2575        let watcher = Arc::new(FakeWatcher {
2576            tx,
2577            original_path: path.to_owned(),
2578            fs_state: self.state.clone(),
2579            prefixes: Mutex::new(vec![path]),
2580        });
2581        (
2582            Box::pin(futures::StreamExt::filter(rx, {
2583                let watcher = watcher.clone();
2584                move |events| {
2585                    let result = events.iter().any(|evt_path| {
2586                        watcher
2587                            .prefixes
2588                            .lock()
2589                            .iter()
2590                            .any(|prefix| evt_path.path.starts_with(prefix))
2591                    });
2592                    let executor = executor.clone();
2593                    async move {
2594                        executor.simulate_random_delay().await;
2595                        result
2596                    }
2597                }
2598            })),
2599            watcher,
2600        )
2601    }
2602
2603    fn open_repo(
2604        &self,
2605        abs_dot_git: &Path,
2606        _system_git_binary: Option<&Path>,
2607    ) -> Option<Arc<dyn GitRepository>> {
2608        use util::ResultExt as _;
2609
2610        self.with_git_state_and_paths(
2611            abs_dot_git,
2612            false,
2613            |_, repository_dir_path, common_dir_path| {
2614                Arc::new(fake_git_repo::FakeGitRepository {
2615                    fs: self.this.upgrade().unwrap(),
2616                    executor: self.executor.clone(),
2617                    dot_git_path: abs_dot_git.to_path_buf(),
2618                    repository_dir_path: repository_dir_path.to_owned(),
2619                    common_dir_path: common_dir_path.to_owned(),
2620                    checkpoints: Arc::default(),
2621                }) as _
2622            },
2623        )
2624        .log_err()
2625    }
2626
2627    async fn git_init(
2628        &self,
2629        abs_work_directory_path: &Path,
2630        _fallback_branch_name: String,
2631    ) -> Result<()> {
2632        self.create_dir(&abs_work_directory_path.join(".git")).await
2633    }
2634
2635    async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2636        anyhow::bail!("Git clone is not supported in fake Fs")
2637    }
2638
2639    fn is_fake(&self) -> bool {
2640        true
2641    }
2642
2643    async fn is_case_sensitive(&self) -> Result<bool> {
2644        Ok(true)
2645    }
2646
2647    #[cfg(any(test, feature = "test-support"))]
2648    fn as_fake(&self) -> Arc<FakeFs> {
2649        self.this.upgrade().unwrap()
2650    }
2651}
2652
2653fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2654    rope.chunks().flat_map(move |chunk| {
2655        let mut newline = false;
2656        let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
2657        chunk
2658            .lines()
2659            .flat_map(move |line| {
2660                let ending = if newline {
2661                    Some(line_ending.as_str())
2662                } else {
2663                    None
2664                };
2665                newline = true;
2666                ending.into_iter().chain([line])
2667            })
2668            .chain(end_with_newline)
2669    })
2670}
2671
2672pub fn normalize_path(path: &Path) -> PathBuf {
2673    let mut components = path.components().peekable();
2674    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2675        components.next();
2676        PathBuf::from(c.as_os_str())
2677    } else {
2678        PathBuf::new()
2679    };
2680
2681    for component in components {
2682        match component {
2683            Component::Prefix(..) => unreachable!(),
2684            Component::RootDir => {
2685                ret.push(component.as_os_str());
2686            }
2687            Component::CurDir => {}
2688            Component::ParentDir => {
2689                ret.pop();
2690            }
2691            Component::Normal(c) => {
2692                ret.push(c);
2693            }
2694        }
2695    }
2696    ret
2697}
2698
2699pub async fn copy_recursive<'a>(
2700    fs: &'a dyn Fs,
2701    source: &'a Path,
2702    target: &'a Path,
2703    options: CopyOptions,
2704) -> Result<()> {
2705    for (item, is_dir) in read_dir_items(fs, source).await? {
2706        let Ok(item_relative_path) = item.strip_prefix(source) else {
2707            continue;
2708        };
2709        let target_item = if item_relative_path == Path::new("") {
2710            target.to_path_buf()
2711        } else {
2712            target.join(item_relative_path)
2713        };
2714        if is_dir {
2715            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2716                if options.ignore_if_exists {
2717                    continue;
2718                } else {
2719                    anyhow::bail!("{target_item:?} already exists");
2720                }
2721            }
2722            let _ = fs
2723                .remove_dir(
2724                    &target_item,
2725                    RemoveOptions {
2726                        recursive: true,
2727                        ignore_if_not_exists: true,
2728                    },
2729                )
2730                .await;
2731            fs.create_dir(&target_item).await?;
2732        } else {
2733            fs.copy_file(&item, &target_item, options).await?;
2734        }
2735    }
2736    Ok(())
2737}
2738
2739/// Recursively reads all of the paths in the given directory.
2740///
2741/// Returns a vector of tuples of (path, is_dir).
2742pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2743    let mut items = Vec::new();
2744    read_recursive(fs, source, &mut items).await?;
2745    Ok(items)
2746}
2747
2748fn read_recursive<'a>(
2749    fs: &'a dyn Fs,
2750    source: &'a Path,
2751    output: &'a mut Vec<(PathBuf, bool)>,
2752) -> BoxFuture<'a, Result<()>> {
2753    use futures::future::FutureExt;
2754
2755    async move {
2756        let metadata = fs
2757            .metadata(source)
2758            .await?
2759            .with_context(|| format!("path does not exist: {source:?}"))?;
2760
2761        if metadata.is_dir {
2762            output.push((source.to_path_buf(), true));
2763            let mut children = fs.read_dir(source).await?;
2764            while let Some(child_path) = children.next().await {
2765                if let Ok(child_path) = child_path {
2766                    read_recursive(fs, &child_path, output).await?;
2767                }
2768            }
2769        } else {
2770            output.push((source.to_path_buf(), false));
2771        }
2772        Ok(())
2773    }
2774    .boxed()
2775}
2776
2777// todo(windows)
2778// can we get file id not open the file twice?
2779// https://github.com/rust-lang/rust/issues/63010
2780#[cfg(target_os = "windows")]
2781async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2782    use std::os::windows::io::AsRawHandle;
2783
2784    use smol::fs::windows::OpenOptionsExt;
2785    use windows::Win32::{
2786        Foundation::HANDLE,
2787        Storage::FileSystem::{
2788            BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2789        },
2790    };
2791
2792    let file = smol::fs::OpenOptions::new()
2793        .read(true)
2794        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2795        .open(path)
2796        .await?;
2797
2798    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2799    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2800    // This function supports Windows XP+
2801    smol::unblock(move || {
2802        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2803
2804        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2805    })
2806    .await
2807}
2808
2809#[cfg(target_os = "windows")]
2810fn atomic_replace<P: AsRef<Path>>(
2811    replaced_file: P,
2812    replacement_file: P,
2813) -> windows::core::Result<()> {
2814    use windows::{
2815        Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2816        core::HSTRING,
2817    };
2818
2819    // If the file does not exist, create it.
2820    let _ = std::fs::File::create_new(replaced_file.as_ref());
2821
2822    unsafe {
2823        ReplaceFileW(
2824            &HSTRING::from(replaced_file.as_ref().to_string_lossy().into_owned()),
2825            &HSTRING::from(replacement_file.as_ref().to_string_lossy().into_owned()),
2826            None,
2827            REPLACE_FILE_FLAGS::default(),
2828            None,
2829            None,
2830        )
2831    }
2832}
2833
2834#[cfg(test)]
2835mod tests {
2836    use super::*;
2837    use gpui::BackgroundExecutor;
2838    use serde_json::json;
2839    use util::path;
2840
2841    #[gpui::test]
2842    async fn test_fake_fs(executor: BackgroundExecutor) {
2843        let fs = FakeFs::new(executor.clone());
2844        fs.insert_tree(
2845            path!("/root"),
2846            json!({
2847                "dir1": {
2848                    "a": "A",
2849                    "b": "B"
2850                },
2851                "dir2": {
2852                    "c": "C",
2853                    "dir3": {
2854                        "d": "D"
2855                    }
2856                }
2857            }),
2858        )
2859        .await;
2860
2861        assert_eq!(
2862            fs.files(),
2863            vec![
2864                PathBuf::from(path!("/root/dir1/a")),
2865                PathBuf::from(path!("/root/dir1/b")),
2866                PathBuf::from(path!("/root/dir2/c")),
2867                PathBuf::from(path!("/root/dir2/dir3/d")),
2868            ]
2869        );
2870
2871        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2872            .await
2873            .unwrap();
2874
2875        assert_eq!(
2876            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2877                .await
2878                .unwrap(),
2879            PathBuf::from(path!("/root/dir2/dir3")),
2880        );
2881        assert_eq!(
2882            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2883                .await
2884                .unwrap(),
2885            PathBuf::from(path!("/root/dir2/dir3/d")),
2886        );
2887        assert_eq!(
2888            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2889                .await
2890                .unwrap(),
2891            "D",
2892        );
2893    }
2894
2895    #[gpui::test]
2896    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2897        let fs = FakeFs::new(executor.clone());
2898        fs.insert_tree(
2899            path!("/outer"),
2900            json!({
2901                "a": "A",
2902                "b": "B",
2903                "inner": {}
2904            }),
2905        )
2906        .await;
2907
2908        assert_eq!(
2909            fs.files(),
2910            vec![
2911                PathBuf::from(path!("/outer/a")),
2912                PathBuf::from(path!("/outer/b")),
2913            ]
2914        );
2915
2916        let source = Path::new(path!("/outer/a"));
2917        let target = Path::new(path!("/outer/a copy"));
2918        copy_recursive(fs.as_ref(), source, target, Default::default())
2919            .await
2920            .unwrap();
2921
2922        assert_eq!(
2923            fs.files(),
2924            vec![
2925                PathBuf::from(path!("/outer/a")),
2926                PathBuf::from(path!("/outer/a copy")),
2927                PathBuf::from(path!("/outer/b")),
2928            ]
2929        );
2930
2931        let source = Path::new(path!("/outer/a"));
2932        let target = Path::new(path!("/outer/inner/a copy"));
2933        copy_recursive(fs.as_ref(), source, target, Default::default())
2934            .await
2935            .unwrap();
2936
2937        assert_eq!(
2938            fs.files(),
2939            vec![
2940                PathBuf::from(path!("/outer/a")),
2941                PathBuf::from(path!("/outer/a copy")),
2942                PathBuf::from(path!("/outer/b")),
2943                PathBuf::from(path!("/outer/inner/a copy")),
2944            ]
2945        );
2946    }
2947
2948    #[gpui::test]
2949    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2950        let fs = FakeFs::new(executor.clone());
2951        fs.insert_tree(
2952            path!("/outer"),
2953            json!({
2954                "a": "A",
2955                "empty": {},
2956                "non-empty": {
2957                    "b": "B",
2958                }
2959            }),
2960        )
2961        .await;
2962
2963        assert_eq!(
2964            fs.files(),
2965            vec![
2966                PathBuf::from(path!("/outer/a")),
2967                PathBuf::from(path!("/outer/non-empty/b")),
2968            ]
2969        );
2970        assert_eq!(
2971            fs.directories(false),
2972            vec![
2973                PathBuf::from(path!("/")),
2974                PathBuf::from(path!("/outer")),
2975                PathBuf::from(path!("/outer/empty")),
2976                PathBuf::from(path!("/outer/non-empty")),
2977            ]
2978        );
2979
2980        let source = Path::new(path!("/outer/empty"));
2981        let target = Path::new(path!("/outer/empty copy"));
2982        copy_recursive(fs.as_ref(), source, target, Default::default())
2983            .await
2984            .unwrap();
2985
2986        assert_eq!(
2987            fs.files(),
2988            vec![
2989                PathBuf::from(path!("/outer/a")),
2990                PathBuf::from(path!("/outer/non-empty/b")),
2991            ]
2992        );
2993        assert_eq!(
2994            fs.directories(false),
2995            vec![
2996                PathBuf::from(path!("/")),
2997                PathBuf::from(path!("/outer")),
2998                PathBuf::from(path!("/outer/empty")),
2999                PathBuf::from(path!("/outer/empty copy")),
3000                PathBuf::from(path!("/outer/non-empty")),
3001            ]
3002        );
3003
3004        let source = Path::new(path!("/outer/non-empty"));
3005        let target = Path::new(path!("/outer/non-empty copy"));
3006        copy_recursive(fs.as_ref(), source, target, Default::default())
3007            .await
3008            .unwrap();
3009
3010        assert_eq!(
3011            fs.files(),
3012            vec![
3013                PathBuf::from(path!("/outer/a")),
3014                PathBuf::from(path!("/outer/non-empty/b")),
3015                PathBuf::from(path!("/outer/non-empty copy/b")),
3016            ]
3017        );
3018        assert_eq!(
3019            fs.directories(false),
3020            vec![
3021                PathBuf::from(path!("/")),
3022                PathBuf::from(path!("/outer")),
3023                PathBuf::from(path!("/outer/empty")),
3024                PathBuf::from(path!("/outer/empty copy")),
3025                PathBuf::from(path!("/outer/non-empty")),
3026                PathBuf::from(path!("/outer/non-empty copy")),
3027            ]
3028        );
3029    }
3030
3031    #[gpui::test]
3032    async fn test_copy_recursive(executor: BackgroundExecutor) {
3033        let fs = FakeFs::new(executor.clone());
3034        fs.insert_tree(
3035            path!("/outer"),
3036            json!({
3037                "inner1": {
3038                    "a": "A",
3039                    "b": "B",
3040                    "inner3": {
3041                        "d": "D",
3042                    },
3043                    "inner4": {}
3044                },
3045                "inner2": {
3046                    "c": "C",
3047                }
3048            }),
3049        )
3050        .await;
3051
3052        assert_eq!(
3053            fs.files(),
3054            vec![
3055                PathBuf::from(path!("/outer/inner1/a")),
3056                PathBuf::from(path!("/outer/inner1/b")),
3057                PathBuf::from(path!("/outer/inner2/c")),
3058                PathBuf::from(path!("/outer/inner1/inner3/d")),
3059            ]
3060        );
3061        assert_eq!(
3062            fs.directories(false),
3063            vec![
3064                PathBuf::from(path!("/")),
3065                PathBuf::from(path!("/outer")),
3066                PathBuf::from(path!("/outer/inner1")),
3067                PathBuf::from(path!("/outer/inner2")),
3068                PathBuf::from(path!("/outer/inner1/inner3")),
3069                PathBuf::from(path!("/outer/inner1/inner4")),
3070            ]
3071        );
3072
3073        let source = Path::new(path!("/outer"));
3074        let target = Path::new(path!("/outer/inner1/outer"));
3075        copy_recursive(fs.as_ref(), source, target, Default::default())
3076            .await
3077            .unwrap();
3078
3079        assert_eq!(
3080            fs.files(),
3081            vec![
3082                PathBuf::from(path!("/outer/inner1/a")),
3083                PathBuf::from(path!("/outer/inner1/b")),
3084                PathBuf::from(path!("/outer/inner2/c")),
3085                PathBuf::from(path!("/outer/inner1/inner3/d")),
3086                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3087                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3088                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3089                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
3090            ]
3091        );
3092        assert_eq!(
3093            fs.directories(false),
3094            vec![
3095                PathBuf::from(path!("/")),
3096                PathBuf::from(path!("/outer")),
3097                PathBuf::from(path!("/outer/inner1")),
3098                PathBuf::from(path!("/outer/inner2")),
3099                PathBuf::from(path!("/outer/inner1/inner3")),
3100                PathBuf::from(path!("/outer/inner1/inner4")),
3101                PathBuf::from(path!("/outer/inner1/outer")),
3102                PathBuf::from(path!("/outer/inner1/outer/inner1")),
3103                PathBuf::from(path!("/outer/inner1/outer/inner2")),
3104                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
3105                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
3106            ]
3107        );
3108    }
3109
3110    #[gpui::test]
3111    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
3112        let fs = FakeFs::new(executor.clone());
3113        fs.insert_tree(
3114            path!("/outer"),
3115            json!({
3116                "inner1": {
3117                    "a": "A",
3118                    "b": "B",
3119                    "outer": {
3120                        "inner1": {
3121                            "a": "B"
3122                        }
3123                    }
3124                },
3125                "inner2": {
3126                    "c": "C",
3127                }
3128            }),
3129        )
3130        .await;
3131
3132        assert_eq!(
3133            fs.files(),
3134            vec![
3135                PathBuf::from(path!("/outer/inner1/a")),
3136                PathBuf::from(path!("/outer/inner1/b")),
3137                PathBuf::from(path!("/outer/inner2/c")),
3138                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3139            ]
3140        );
3141        assert_eq!(
3142            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3143                .await
3144                .unwrap(),
3145            "B",
3146        );
3147
3148        let source = Path::new(path!("/outer"));
3149        let target = Path::new(path!("/outer/inner1/outer"));
3150        copy_recursive(
3151            fs.as_ref(),
3152            source,
3153            target,
3154            CopyOptions {
3155                overwrite: true,
3156                ..Default::default()
3157            },
3158        )
3159        .await
3160        .unwrap();
3161
3162        assert_eq!(
3163            fs.files(),
3164            vec![
3165                PathBuf::from(path!("/outer/inner1/a")),
3166                PathBuf::from(path!("/outer/inner1/b")),
3167                PathBuf::from(path!("/outer/inner2/c")),
3168                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3169                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3170                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3171                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3172            ]
3173        );
3174        assert_eq!(
3175            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3176                .await
3177                .unwrap(),
3178            "A"
3179        );
3180    }
3181
3182    #[gpui::test]
3183    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
3184        let fs = FakeFs::new(executor.clone());
3185        fs.insert_tree(
3186            path!("/outer"),
3187            json!({
3188                "inner1": {
3189                    "a": "A",
3190                    "b": "B",
3191                    "outer": {
3192                        "inner1": {
3193                            "a": "B"
3194                        }
3195                    }
3196                },
3197                "inner2": {
3198                    "c": "C",
3199                }
3200            }),
3201        )
3202        .await;
3203
3204        assert_eq!(
3205            fs.files(),
3206            vec![
3207                PathBuf::from(path!("/outer/inner1/a")),
3208                PathBuf::from(path!("/outer/inner1/b")),
3209                PathBuf::from(path!("/outer/inner2/c")),
3210                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3211            ]
3212        );
3213        assert_eq!(
3214            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3215                .await
3216                .unwrap(),
3217            "B",
3218        );
3219
3220        let source = Path::new(path!("/outer"));
3221        let target = Path::new(path!("/outer/inner1/outer"));
3222        copy_recursive(
3223            fs.as_ref(),
3224            source,
3225            target,
3226            CopyOptions {
3227                ignore_if_exists: true,
3228                ..Default::default()
3229            },
3230        )
3231        .await
3232        .unwrap();
3233
3234        assert_eq!(
3235            fs.files(),
3236            vec![
3237                PathBuf::from(path!("/outer/inner1/a")),
3238                PathBuf::from(path!("/outer/inner1/b")),
3239                PathBuf::from(path!("/outer/inner2/c")),
3240                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3241                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3242                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3243                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3244            ]
3245        );
3246        assert_eq!(
3247            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3248                .await
3249                .unwrap(),
3250            "B"
3251        );
3252    }
3253
3254    #[gpui::test]
3255    async fn test_realfs_atomic_write(executor: BackgroundExecutor) {
3256        // With the file handle still open, the file should be replaced
3257        // https://github.com/zed-industries/zed/issues/30054
3258        let fs = RealFs {
3259            bundled_git_binary_path: None,
3260            executor,
3261        };
3262        let temp_dir = TempDir::new().unwrap();
3263        let file_to_be_replaced = temp_dir.path().join("file.txt");
3264        let mut file = std::fs::File::create_new(&file_to_be_replaced).unwrap();
3265        file.write_all(b"Hello").unwrap();
3266        // drop(file);  // We still hold the file handle here
3267        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3268        assert_eq!(content, "Hello");
3269        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "World".into())).unwrap();
3270        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3271        assert_eq!(content, "World");
3272    }
3273
3274    #[gpui::test]
3275    async fn test_realfs_atomic_write_non_existing_file(executor: BackgroundExecutor) {
3276        let fs = RealFs {
3277            bundled_git_binary_path: None,
3278            executor,
3279        };
3280        let temp_dir = TempDir::new().unwrap();
3281        let file_to_be_replaced = temp_dir.path().join("file.txt");
3282        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "Hello".into())).unwrap();
3283        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3284        assert_eq!(content, "Hello");
3285    }
3286}