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