fs.rs

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