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