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