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