fs.rs

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