fs.rs

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