fs.rs

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