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