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