fs.rs

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