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