fs.rs

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