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