fs.rs

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