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