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