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                return Err(anyhow!("{target:?} already exists"));
 364            }
 365        }
 366
 367        smol::fs::copy(source, target).await?;
 368        Ok(())
 369    }
 370
 371    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 372        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 373            if options.ignore_if_exists {
 374                return Ok(());
 375            } else {
 376                return Err(anyhow!("{target:?} already exists"));
 377            }
 378        }
 379
 380        smol::fs::rename(source, target).await?;
 381        Ok(())
 382    }
 383
 384    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 385        let result = if options.recursive {
 386            smol::fs::remove_dir_all(path).await
 387        } else {
 388            smol::fs::remove_dir(path).await
 389        };
 390        match result {
 391            Ok(()) => Ok(()),
 392            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 393                Ok(())
 394            }
 395            Err(err) => Err(err)?,
 396        }
 397    }
 398
 399    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 400        #[cfg(windows)]
 401        if let Ok(Some(metadata)) = self.metadata(path).await {
 402            if metadata.is_symlink && metadata.is_dir {
 403                self.remove_dir(
 404                    path,
 405                    RemoveOptions {
 406                        recursive: false,
 407                        ignore_if_not_exists: true,
 408                    },
 409                )
 410                .await?;
 411                return Ok(());
 412            }
 413        }
 414
 415        match smol::fs::remove_file(path).await {
 416            Ok(()) => Ok(()),
 417            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 418                Ok(())
 419            }
 420            Err(err) => Err(err)?,
 421        }
 422    }
 423
 424    #[cfg(target_os = "macos")]
 425    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 426        use cocoa::{
 427            base::{id, nil},
 428            foundation::{NSAutoreleasePool, NSString},
 429        };
 430        use objc::{class, msg_send, sel, sel_impl};
 431
 432        unsafe {
 433            unsafe fn ns_string(string: &str) -> id {
 434                unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 435            }
 436
 437            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 438            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 439            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 440
 441            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 442        }
 443        Ok(())
 444    }
 445
 446    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 447    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 448        if let Ok(Some(metadata)) = self.metadata(path).await {
 449            if metadata.is_symlink {
 450                // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
 451                return self.remove_file(path, RemoveOptions::default()).await;
 452            }
 453        }
 454        let file = smol::fs::File::open(path).await?;
 455        match trash::trash_file(&file.as_fd()).await {
 456            Ok(_) => Ok(()),
 457            Err(err) => {
 458                log::error!("Failed to trash file: {}", err);
 459                // Trashing files can fail if you don't have a trashing dbus service configured.
 460                // In that case, delete the file directly instead.
 461                return self.remove_file(path, RemoveOptions::default()).await;
 462            }
 463        }
 464    }
 465
 466    #[cfg(target_os = "windows")]
 467    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 468        use util::paths::SanitizedPath;
 469        use windows::{
 470            Storage::{StorageDeleteOption, StorageFile},
 471            core::HSTRING,
 472        };
 473        // todo(windows)
 474        // When new version of `windows-rs` release, make this operation `async`
 475        let path = SanitizedPath::from(path.canonicalize()?);
 476        let path_string = path.to_string();
 477        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 478        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 479        Ok(())
 480    }
 481
 482    #[cfg(target_os = "macos")]
 483    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 484        self.trash_file(path, options).await
 485    }
 486
 487    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 488    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 489        self.trash_file(path, options).await
 490    }
 491
 492    #[cfg(target_os = "windows")]
 493    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 494        use util::paths::SanitizedPath;
 495        use windows::{
 496            Storage::{StorageDeleteOption, StorageFolder},
 497            core::HSTRING,
 498        };
 499
 500        // todo(windows)
 501        // When new version of `windows-rs` release, make this operation `async`
 502        let path = SanitizedPath::from(path.canonicalize()?);
 503        let path_string = path.to_string();
 504        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 505        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 506        Ok(())
 507    }
 508
 509    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
 510        Ok(Box::new(std::fs::File::open(path)?))
 511    }
 512
 513    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 514        Ok(Arc::new(std::fs::File::open(path)?))
 515    }
 516
 517    async fn load(&self, path: &Path) -> Result<String> {
 518        let path = path.to_path_buf();
 519        let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
 520        Ok(text)
 521    }
 522    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 523        let path = path.to_path_buf();
 524        let bytes = smol::unblock(|| std::fs::read(path)).await?;
 525        Ok(bytes)
 526    }
 527
 528    #[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            Ok::<(), anyhow::Error>(())
 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            Ok::<(), anyhow::Error>(())
 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).await?)
 601    }
 602
 603    async fn is_file(&self, path: &Path) -> bool {
 604        smol::fs::metadata(path)
 605            .await
 606            .map_or(false, |metadata| metadata.is_file())
 607    }
 608
 609    async fn is_dir(&self, path: &Path) -> bool {
 610        smol::fs::metadata(path)
 611            .await
 612            .map_or(false, |metadata| metadata.is_dir())
 613    }
 614
 615    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 616        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 617            Ok(metadata) => metadata,
 618            Err(err) => {
 619                return match (err.kind(), err.raw_os_error()) {
 620                    (io::ErrorKind::NotFound, _) => Ok(None),
 621                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 622                    _ => Err(anyhow::Error::new(err)),
 623                };
 624            }
 625        };
 626
 627        let path_buf = path.to_path_buf();
 628        let path_exists = smol::unblock(move || {
 629            path_buf
 630                .try_exists()
 631                .with_context(|| format!("checking existence for path {path_buf:?}"))
 632        })
 633        .await?;
 634        let is_symlink = symlink_metadata.file_type().is_symlink();
 635        let metadata = match (is_symlink, path_exists) {
 636            (true, true) => smol::fs::metadata(path)
 637                .await
 638                .with_context(|| "accessing symlink for path {path}")?,
 639            _ => symlink_metadata,
 640        };
 641
 642        #[cfg(unix)]
 643        let inode = metadata.ino();
 644
 645        #[cfg(windows)]
 646        let inode = file_id(path).await?;
 647
 648        #[cfg(windows)]
 649        let is_fifo = false;
 650
 651        #[cfg(unix)]
 652        let is_fifo = metadata.file_type().is_fifo();
 653
 654        Ok(Some(Metadata {
 655            inode,
 656            mtime: MTime(metadata.modified().unwrap()),
 657            len: metadata.len(),
 658            is_symlink,
 659            is_dir: metadata.file_type().is_dir(),
 660            is_fifo,
 661        }))
 662    }
 663
 664    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 665        let path = smol::fs::read_link(path).await?;
 666        Ok(path)
 667    }
 668
 669    async fn read_dir(
 670        &self,
 671        path: &Path,
 672    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 673        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 674            Ok(entry) => Ok(entry.path()),
 675            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 676        });
 677        Ok(Box::pin(result))
 678    }
 679
 680    #[cfg(target_os = "macos")]
 681    async fn watch(
 682        &self,
 683        path: &Path,
 684        latency: Duration,
 685    ) -> (
 686        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 687        Arc<dyn Watcher>,
 688    ) {
 689        use fsevent::StreamFlags;
 690
 691        let (events_tx, events_rx) = smol::channel::unbounded();
 692        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 693        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 694            events_tx,
 695            Arc::downgrade(&handles),
 696            latency,
 697        ));
 698        watcher.add(path).expect("handles can't be dropped");
 699
 700        (
 701            Box::pin(
 702                events_rx
 703                    .map(|events| {
 704                        events
 705                            .into_iter()
 706                            .map(|event| {
 707                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 708                                    Some(PathEventKind::Removed)
 709                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 710                                    Some(PathEventKind::Created)
 711                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
 712                                    Some(PathEventKind::Changed)
 713                                } else {
 714                                    None
 715                                };
 716                                PathEvent {
 717                                    path: event.path,
 718                                    kind,
 719                                }
 720                            })
 721                            .collect()
 722                    })
 723                    .chain(futures::stream::once(async move {
 724                        drop(handles);
 725                        vec![]
 726                    })),
 727            ),
 728            watcher,
 729        )
 730    }
 731
 732    #[cfg(not(target_os = "macos"))]
 733    async fn watch(
 734        &self,
 735        path: &Path,
 736        latency: Duration,
 737    ) -> (
 738        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 739        Arc<dyn Watcher>,
 740    ) {
 741        use parking_lot::Mutex;
 742        use util::{ResultExt as _, paths::SanitizedPath};
 743
 744        let (tx, rx) = smol::channel::unbounded();
 745        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 746        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 747
 748        if watcher.add(path).is_err() {
 749            // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 750            if let Some(parent) = path.parent() {
 751                if let Err(e) = watcher.add(parent) {
 752                    log::warn!("Failed to watch: {e}");
 753                }
 754            }
 755        }
 756
 757        // Check if path is a symlink and follow the target parent
 758        if let Some(mut target) = self.read_link(&path).await.ok() {
 759            // Check if symlink target is relative path, if so make it absolute
 760            if target.is_relative() {
 761                if let Some(parent) = path.parent() {
 762                    target = parent.join(target);
 763                    if let Ok(canonical) = self.canonicalize(&target).await {
 764                        target = SanitizedPath::from(canonical).as_path().to_path_buf();
 765                    }
 766                }
 767            }
 768            watcher.add(&target).ok();
 769            if let Some(parent) = target.parent() {
 770                watcher.add(parent).log_err();
 771            }
 772        }
 773
 774        (
 775            Box::pin(rx.filter_map({
 776                let watcher = watcher.clone();
 777                move |_| {
 778                    let _ = watcher.clone();
 779                    let pending_paths = pending_paths.clone();
 780                    async move {
 781                        smol::Timer::after(latency).await;
 782                        let paths = std::mem::take(&mut *pending_paths.lock());
 783                        (!paths.is_empty()).then_some(paths)
 784                    }
 785                }
 786            })),
 787            watcher,
 788        )
 789    }
 790
 791    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
 792        Some(Arc::new(RealGitRepository::new(
 793            dotgit_path,
 794            self.git_binary_path.clone(),
 795            self.executor.clone(),
 796        )?))
 797    }
 798
 799    fn git_init(&self, abs_work_directory_path: &Path, fallback_branch_name: String) -> Result<()> {
 800        let config = new_std_command("git")
 801            .current_dir(abs_work_directory_path)
 802            .args(&["config", "--global", "--get", "init.defaultBranch"])
 803            .output()?;
 804
 805        let branch_name;
 806
 807        if config.status.success() && !config.stdout.is_empty() {
 808            branch_name = String::from_utf8_lossy(&config.stdout);
 809        } else {
 810            branch_name = Cow::Borrowed(fallback_branch_name.as_str());
 811        }
 812
 813        new_std_command("git")
 814            .current_dir(abs_work_directory_path)
 815            .args(&["init", "-b"])
 816            .arg(branch_name.trim())
 817            .output()?;
 818
 819        Ok(())
 820    }
 821
 822    fn is_fake(&self) -> bool {
 823        false
 824    }
 825
 826    /// Checks whether the file system is case sensitive by attempting to create two files
 827    /// that have the same name except for the casing.
 828    ///
 829    /// It creates both files in a temporary directory it removes at the end.
 830    async fn is_case_sensitive(&self) -> Result<bool> {
 831        let temp_dir = TempDir::new()?;
 832        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 833        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 834
 835        let create_opts = CreateOptions {
 836            overwrite: false,
 837            ignore_if_exists: false,
 838        };
 839
 840        // Create file1
 841        self.create_file(&test_file_1, create_opts).await?;
 842
 843        // Now check whether it's possible to create file2
 844        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 845            Ok(_) => Ok(true),
 846            Err(e) => {
 847                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 848                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 849                        Ok(false)
 850                    } else {
 851                        Err(e)
 852                    }
 853                } else {
 854                    Err(e)
 855                }
 856            }
 857        };
 858
 859        temp_dir.close()?;
 860        case_sensitive
 861    }
 862
 863    fn home_dir(&self) -> Option<PathBuf> {
 864        Some(paths::home_dir().clone())
 865    }
 866}
 867
 868#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
 869impl Watcher for RealWatcher {
 870    fn add(&self, _: &Path) -> Result<()> {
 871        Ok(())
 872    }
 873
 874    fn remove(&self, _: &Path) -> Result<()> {
 875        Ok(())
 876    }
 877}
 878
 879#[cfg(any(test, feature = "test-support"))]
 880pub struct FakeFs {
 881    this: std::sync::Weak<Self>,
 882    // Use an unfair lock to ensure tests are deterministic.
 883    state: Arc<Mutex<FakeFsState>>,
 884    executor: gpui::BackgroundExecutor,
 885}
 886
 887#[cfg(any(test, feature = "test-support"))]
 888struct FakeFsState {
 889    root: Arc<Mutex<FakeFsEntry>>,
 890    next_inode: u64,
 891    next_mtime: SystemTime,
 892    git_event_tx: smol::channel::Sender<PathBuf>,
 893    event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
 894    events_paused: bool,
 895    buffered_events: Vec<PathEvent>,
 896    metadata_call_count: usize,
 897    read_dir_call_count: usize,
 898    moves: std::collections::HashMap<u64, PathBuf>,
 899    home_dir: Option<PathBuf>,
 900}
 901
 902#[cfg(any(test, feature = "test-support"))]
 903#[derive(Debug)]
 904enum FakeFsEntry {
 905    File {
 906        inode: u64,
 907        mtime: MTime,
 908        len: u64,
 909        content: Vec<u8>,
 910        // The path to the repository state directory, if this is a gitfile.
 911        git_dir_path: Option<PathBuf>,
 912    },
 913    Dir {
 914        inode: u64,
 915        mtime: MTime,
 916        len: u64,
 917        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 918        git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
 919    },
 920    Symlink {
 921        target: PathBuf,
 922    },
 923}
 924
 925#[cfg(any(test, feature = "test-support"))]
 926impl FakeFsState {
 927    fn get_and_increment_mtime(&mut self) -> MTime {
 928        let mtime = self.next_mtime;
 929        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
 930        MTime(mtime)
 931    }
 932
 933    fn get_and_increment_inode(&mut self) -> u64 {
 934        let inode = self.next_inode;
 935        self.next_inode += 1;
 936        inode
 937    }
 938
 939    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 940        Ok(self
 941            .try_read_path(target, true)
 942            .ok_or_else(|| {
 943                anyhow!(io::Error::new(
 944                    io::ErrorKind::NotFound,
 945                    format!("not found: {}", target.display())
 946                ))
 947            })?
 948            .0)
 949    }
 950
 951    fn try_read_path(
 952        &self,
 953        target: &Path,
 954        follow_symlink: bool,
 955    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 956        let mut path = target.to_path_buf();
 957        let mut canonical_path = PathBuf::new();
 958        let mut entry_stack = Vec::new();
 959        'outer: loop {
 960            let mut path_components = path.components().peekable();
 961            let mut prefix = None;
 962            while let Some(component) = path_components.next() {
 963                match component {
 964                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
 965                    Component::RootDir => {
 966                        entry_stack.clear();
 967                        entry_stack.push(self.root.clone());
 968                        canonical_path.clear();
 969                        match prefix {
 970                            Some(prefix_component) => {
 971                                canonical_path = PathBuf::from(prefix_component.as_os_str());
 972                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
 973                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
 974                            }
 975                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
 976                        }
 977                    }
 978                    Component::CurDir => {}
 979                    Component::ParentDir => {
 980                        entry_stack.pop()?;
 981                        canonical_path.pop();
 982                    }
 983                    Component::Normal(name) => {
 984                        let current_entry = entry_stack.last().cloned()?;
 985                        let current_entry = current_entry.lock();
 986                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 987                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 988                            if path_components.peek().is_some() || follow_symlink {
 989                                let entry = entry.lock();
 990                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 991                                    let mut target = target.clone();
 992                                    target.extend(path_components);
 993                                    path = target;
 994                                    continue 'outer;
 995                                }
 996                            }
 997                            entry_stack.push(entry.clone());
 998                            canonical_path = canonical_path.join(name);
 999                        } else {
1000                            return None;
1001                        }
1002                    }
1003                }
1004            }
1005            break;
1006        }
1007        Some((entry_stack.pop()?, canonical_path))
1008    }
1009
1010    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
1011    where
1012        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
1013    {
1014        let path = normalize_path(path);
1015        let filename = path
1016            .file_name()
1017            .ok_or_else(|| anyhow!("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                        .ok_or_else(|| anyhow!("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            Err(anyhow!("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(&self, dot_git: &Path, head_state: &[(RepoPath, String)]) {
1460        self.with_git_state(dot_git, true, |state| {
1461            state.head_contents.clear();
1462            state.head_contents.extend(
1463                head_state
1464                    .iter()
1465                    .map(|(path, content)| (path.clone(), content.clone())),
1466            );
1467        })
1468        .unwrap();
1469    }
1470
1471    pub fn set_git_content_for_repo(
1472        &self,
1473        dot_git: &Path,
1474        head_state: &[(RepoPath, String, Option<String>)],
1475    ) {
1476        self.with_git_state(dot_git, true, |state| {
1477            state.head_contents.clear();
1478            state.head_contents.extend(
1479                head_state
1480                    .iter()
1481                    .map(|(path, head_content, _)| (path.clone(), head_content.clone())),
1482            );
1483            state.index_contents.clear();
1484            state.index_contents.extend(head_state.iter().map(
1485                |(path, head_content, index_content)| {
1486                    (
1487                        path.clone(),
1488                        index_content.as_ref().unwrap_or(head_content).clone(),
1489                    )
1490                },
1491            ));
1492        })
1493        .unwrap();
1494    }
1495
1496    pub fn set_head_and_index_for_repo(
1497        &self,
1498        dot_git: &Path,
1499        contents_by_path: &[(RepoPath, String)],
1500    ) {
1501        self.with_git_state(dot_git, true, |state| {
1502            state.head_contents.clear();
1503            state.index_contents.clear();
1504            state.head_contents.extend(contents_by_path.iter().cloned());
1505            state
1506                .index_contents
1507                .extend(contents_by_path.iter().cloned());
1508        })
1509        .unwrap();
1510    }
1511
1512    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1513        self.with_git_state(dot_git, true, |state| {
1514            state.blames.clear();
1515            state.blames.extend(blames);
1516        })
1517        .unwrap();
1518    }
1519
1520    /// Put the given git repository into a state with the given status,
1521    /// by mutating the head, index, and unmerged state.
1522    pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&Path, FileStatus)]) {
1523        let workdir_path = dot_git.parent().unwrap();
1524        let workdir_contents = self.files_with_contents(&workdir_path);
1525        self.with_git_state(dot_git, true, |state| {
1526            state.index_contents.clear();
1527            state.head_contents.clear();
1528            state.unmerged_paths.clear();
1529            for (path, content) in workdir_contents {
1530                let repo_path: RepoPath = path.strip_prefix(&workdir_path).unwrap().into();
1531                let status = statuses
1532                    .iter()
1533                    .find_map(|(p, status)| (**p == *repo_path.0).then_some(status));
1534                let mut content = String::from_utf8_lossy(&content).to_string();
1535
1536                let mut index_content = None;
1537                let mut head_content = None;
1538                match status {
1539                    None => {
1540                        index_content = Some(content.clone());
1541                        head_content = Some(content);
1542                    }
1543                    Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1544                    Some(FileStatus::Unmerged(unmerged_status)) => {
1545                        state
1546                            .unmerged_paths
1547                            .insert(repo_path.clone(), *unmerged_status);
1548                        content.push_str(" (unmerged)");
1549                        index_content = Some(content.clone());
1550                        head_content = Some(content);
1551                    }
1552                    Some(FileStatus::Tracked(TrackedStatus {
1553                        index_status,
1554                        worktree_status,
1555                    })) => {
1556                        match worktree_status {
1557                            StatusCode::Modified => {
1558                                let mut content = content.clone();
1559                                content.push_str(" (modified in working copy)");
1560                                index_content = Some(content);
1561                            }
1562                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1563                                index_content = Some(content.clone());
1564                            }
1565                            StatusCode::Added => {}
1566                            StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1567                                panic!("cannot create these statuses for an existing file");
1568                            }
1569                        };
1570                        match index_status {
1571                            StatusCode::Modified => {
1572                                let mut content = index_content.clone().expect(
1573                                    "file cannot be both modified in index and created in working copy",
1574                                );
1575                                content.push_str(" (modified in index)");
1576                                head_content = Some(content);
1577                            }
1578                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1579                                head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1580                            }
1581                            StatusCode::Added => {}
1582                            StatusCode::Deleted  => {
1583                                head_content = Some("".into());
1584                            }
1585                            StatusCode::Renamed | StatusCode::Copied => {
1586                                panic!("cannot create these statuses for an existing file");
1587                            }
1588                        };
1589                    }
1590                };
1591
1592                if let Some(content) = index_content {
1593                    state.index_contents.insert(repo_path.clone(), content);
1594                }
1595                if let Some(content) = head_content {
1596                    state.head_contents.insert(repo_path.clone(), content);
1597                }
1598            }
1599        }).unwrap();
1600    }
1601
1602    pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1603        self.with_git_state(dot_git, true, |state| {
1604            state.simulated_index_write_error_message = message;
1605        })
1606        .unwrap();
1607    }
1608
1609    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1610        let mut result = Vec::new();
1611        let mut queue = collections::VecDeque::new();
1612        queue.push_back((
1613            PathBuf::from(util::path!("/")),
1614            self.state.lock().root.clone(),
1615        ));
1616        while let Some((path, entry)) = queue.pop_front() {
1617            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1618                for (name, entry) in entries {
1619                    queue.push_back((path.join(name), entry.clone()));
1620                }
1621            }
1622            if include_dot_git
1623                || !path
1624                    .components()
1625                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1626            {
1627                result.push(path);
1628            }
1629        }
1630        result
1631    }
1632
1633    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1634        let mut result = Vec::new();
1635        let mut queue = collections::VecDeque::new();
1636        queue.push_back((
1637            PathBuf::from(util::path!("/")),
1638            self.state.lock().root.clone(),
1639        ));
1640        while let Some((path, entry)) = queue.pop_front() {
1641            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1642                for (name, entry) in entries {
1643                    queue.push_back((path.join(name), entry.clone()));
1644                }
1645                if include_dot_git
1646                    || !path
1647                        .components()
1648                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1649                {
1650                    result.push(path);
1651                }
1652            }
1653        }
1654        result
1655    }
1656
1657    pub fn files(&self) -> Vec<PathBuf> {
1658        let mut result = Vec::new();
1659        let mut queue = collections::VecDeque::new();
1660        queue.push_back((
1661            PathBuf::from(util::path!("/")),
1662            self.state.lock().root.clone(),
1663        ));
1664        while let Some((path, entry)) = queue.pop_front() {
1665            let e = entry.lock();
1666            match &*e {
1667                FakeFsEntry::File { .. } => result.push(path),
1668                FakeFsEntry::Dir { entries, .. } => {
1669                    for (name, entry) in entries {
1670                        queue.push_back((path.join(name), entry.clone()));
1671                    }
1672                }
1673                FakeFsEntry::Symlink { .. } => {}
1674            }
1675        }
1676        result
1677    }
1678
1679    pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1680        let mut result = Vec::new();
1681        let mut queue = collections::VecDeque::new();
1682        queue.push_back((
1683            PathBuf::from(util::path!("/")),
1684            self.state.lock().root.clone(),
1685        ));
1686        while let Some((path, entry)) = queue.pop_front() {
1687            let e = entry.lock();
1688            match &*e {
1689                FakeFsEntry::File { content, .. } => {
1690                    if path.starts_with(prefix) {
1691                        result.push((path, content.clone()));
1692                    }
1693                }
1694                FakeFsEntry::Dir { entries, .. } => {
1695                    for (name, entry) in entries {
1696                        queue.push_back((path.join(name), entry.clone()));
1697                    }
1698                }
1699                FakeFsEntry::Symlink { .. } => {}
1700            }
1701        }
1702        result
1703    }
1704
1705    /// How many `read_dir` calls have been issued.
1706    pub fn read_dir_call_count(&self) -> usize {
1707        self.state.lock().read_dir_call_count
1708    }
1709
1710    pub fn watched_paths(&self) -> Vec<PathBuf> {
1711        let state = self.state.lock();
1712        state
1713            .event_txs
1714            .iter()
1715            .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
1716            .collect()
1717    }
1718
1719    /// How many `metadata` calls have been issued.
1720    pub fn metadata_call_count(&self) -> usize {
1721        self.state.lock().metadata_call_count
1722    }
1723
1724    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1725        self.executor.simulate_random_delay()
1726    }
1727
1728    pub fn set_home_dir(&self, home_dir: PathBuf) {
1729        self.state.lock().home_dir = Some(home_dir);
1730    }
1731}
1732
1733#[cfg(any(test, feature = "test-support"))]
1734impl FakeFsEntry {
1735    fn is_file(&self) -> bool {
1736        matches!(self, Self::File { .. })
1737    }
1738
1739    fn is_symlink(&self) -> bool {
1740        matches!(self, Self::Symlink { .. })
1741    }
1742
1743    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1744        if let Self::File { content, .. } = self {
1745            Ok(content)
1746        } else {
1747            Err(anyhow!("not a file: {}", path.display()))
1748        }
1749    }
1750
1751    fn dir_entries(
1752        &mut self,
1753        path: &Path,
1754    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1755        if let Self::Dir { entries, .. } = self {
1756            Ok(entries)
1757        } else {
1758            Err(anyhow!("not a directory: {}", path.display()))
1759        }
1760    }
1761}
1762
1763#[cfg(any(test, feature = "test-support"))]
1764struct FakeWatcher {
1765    tx: smol::channel::Sender<Vec<PathEvent>>,
1766    original_path: PathBuf,
1767    fs_state: Arc<Mutex<FakeFsState>>,
1768    prefixes: Mutex<Vec<PathBuf>>,
1769}
1770
1771#[cfg(any(test, feature = "test-support"))]
1772impl Watcher for FakeWatcher {
1773    fn add(&self, path: &Path) -> Result<()> {
1774        if path.starts_with(&self.original_path) {
1775            return Ok(());
1776        }
1777        self.fs_state
1778            .try_lock()
1779            .unwrap()
1780            .event_txs
1781            .push((path.to_owned(), self.tx.clone()));
1782        self.prefixes.lock().push(path.to_owned());
1783        Ok(())
1784    }
1785
1786    fn remove(&self, _: &Path) -> Result<()> {
1787        Ok(())
1788    }
1789}
1790
1791#[cfg(any(test, feature = "test-support"))]
1792#[derive(Debug)]
1793struct FakeHandle {
1794    inode: u64,
1795}
1796
1797#[cfg(any(test, feature = "test-support"))]
1798impl FileHandle for FakeHandle {
1799    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1800        let fs = fs.as_fake();
1801        let state = fs.state.lock();
1802        let Some(target) = state.moves.get(&self.inode) else {
1803            anyhow::bail!("fake fd not moved")
1804        };
1805
1806        if state.try_read_path(&target, false).is_some() {
1807            return Ok(target.clone());
1808        }
1809        anyhow::bail!("fake fd target not found")
1810    }
1811}
1812
1813#[cfg(any(test, feature = "test-support"))]
1814#[async_trait::async_trait]
1815impl Fs for FakeFs {
1816    async fn create_dir(&self, path: &Path) -> Result<()> {
1817        self.simulate_random_delay().await;
1818
1819        let mut created_dirs = Vec::new();
1820        let mut cur_path = PathBuf::new();
1821        for component in path.components() {
1822            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1823            cur_path.push(component);
1824            if should_skip {
1825                continue;
1826            }
1827            let mut state = self.state.lock();
1828
1829            let inode = state.get_and_increment_inode();
1830            let mtime = state.get_and_increment_mtime();
1831            state.write_path(&cur_path, |entry| {
1832                entry.or_insert_with(|| {
1833                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1834                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1835                        inode,
1836                        mtime,
1837                        len: 0,
1838                        entries: Default::default(),
1839                        git_repo_state: None,
1840                    }))
1841                });
1842                Ok(())
1843            })?
1844        }
1845
1846        self.state.lock().emit_event(created_dirs);
1847        Ok(())
1848    }
1849
1850    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1851        self.simulate_random_delay().await;
1852        let mut state = self.state.lock();
1853        let inode = state.get_and_increment_inode();
1854        let mtime = state.get_and_increment_mtime();
1855        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1856            inode,
1857            mtime,
1858            len: 0,
1859            content: Vec::new(),
1860            git_dir_path: None,
1861        }));
1862        let mut kind = Some(PathEventKind::Created);
1863        state.write_path(path, |entry| {
1864            match entry {
1865                btree_map::Entry::Occupied(mut e) => {
1866                    if options.overwrite {
1867                        kind = Some(PathEventKind::Changed);
1868                        *e.get_mut() = file;
1869                    } else if !options.ignore_if_exists {
1870                        return Err(anyhow!("path already exists: {}", path.display()));
1871                    }
1872                }
1873                btree_map::Entry::Vacant(e) => {
1874                    e.insert(file);
1875                }
1876            }
1877            Ok(())
1878        })?;
1879        state.emit_event([(path, kind)]);
1880        Ok(())
1881    }
1882
1883    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1884        let mut state = self.state.lock();
1885        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1886        state
1887            .write_path(path.as_ref(), move |e| match e {
1888                btree_map::Entry::Vacant(e) => {
1889                    e.insert(file);
1890                    Ok(())
1891                }
1892                btree_map::Entry::Occupied(mut e) => {
1893                    *e.get_mut() = file;
1894                    Ok(())
1895                }
1896            })
1897            .unwrap();
1898        state.emit_event([(path, None)]);
1899
1900        Ok(())
1901    }
1902
1903    async fn create_file_with(
1904        &self,
1905        path: &Path,
1906        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1907    ) -> Result<()> {
1908        let mut bytes = Vec::new();
1909        content.read_to_end(&mut bytes).await?;
1910        self.write_file_internal(path, bytes, true)?;
1911        Ok(())
1912    }
1913
1914    async fn extract_tar_file(
1915        &self,
1916        path: &Path,
1917        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1918    ) -> Result<()> {
1919        let mut entries = content.entries()?;
1920        while let Some(entry) = entries.next().await {
1921            let mut entry = entry?;
1922            if entry.header().entry_type().is_file() {
1923                let path = path.join(entry.path()?.as_ref());
1924                let mut bytes = Vec::new();
1925                entry.read_to_end(&mut bytes).await?;
1926                self.create_dir(path.parent().unwrap()).await?;
1927                self.write_file_internal(&path, bytes, true)?;
1928            }
1929        }
1930        Ok(())
1931    }
1932
1933    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1934        self.simulate_random_delay().await;
1935
1936        let old_path = normalize_path(old_path);
1937        let new_path = normalize_path(new_path);
1938
1939        let mut state = self.state.lock();
1940        let moved_entry = state.write_path(&old_path, |e| {
1941            if let btree_map::Entry::Occupied(e) = e {
1942                Ok(e.get().clone())
1943            } else {
1944                Err(anyhow!("path does not exist: {}", &old_path.display()))
1945            }
1946        })?;
1947
1948        let inode = match *moved_entry.lock() {
1949            FakeFsEntry::File { inode, .. } => inode,
1950            FakeFsEntry::Dir { inode, .. } => inode,
1951            _ => 0,
1952        };
1953
1954        state.moves.insert(inode, new_path.clone());
1955
1956        state.write_path(&new_path, |e| {
1957            match e {
1958                btree_map::Entry::Occupied(mut e) => {
1959                    if options.overwrite {
1960                        *e.get_mut() = moved_entry;
1961                    } else if !options.ignore_if_exists {
1962                        return Err(anyhow!("path already exists: {}", new_path.display()));
1963                    }
1964                }
1965                btree_map::Entry::Vacant(e) => {
1966                    e.insert(moved_entry);
1967                }
1968            }
1969            Ok(())
1970        })?;
1971
1972        state
1973            .write_path(&old_path, |e| {
1974                if let btree_map::Entry::Occupied(e) = e {
1975                    Ok(e.remove())
1976                } else {
1977                    unreachable!()
1978                }
1979            })
1980            .unwrap();
1981
1982        state.emit_event([
1983            (old_path, Some(PathEventKind::Removed)),
1984            (new_path, Some(PathEventKind::Created)),
1985        ]);
1986        Ok(())
1987    }
1988
1989    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1990        self.simulate_random_delay().await;
1991
1992        let source = normalize_path(source);
1993        let target = normalize_path(target);
1994        let mut state = self.state.lock();
1995        let mtime = state.get_and_increment_mtime();
1996        let inode = state.get_and_increment_inode();
1997        let source_entry = state.read_path(&source)?;
1998        let content = source_entry.lock().file_content(&source)?.clone();
1999        let mut kind = Some(PathEventKind::Created);
2000        state.write_path(&target, |e| match e {
2001            btree_map::Entry::Occupied(e) => {
2002                if options.overwrite {
2003                    kind = Some(PathEventKind::Changed);
2004                    Ok(Some(e.get().clone()))
2005                } else if !options.ignore_if_exists {
2006                    return Err(anyhow!("{target:?} already exists"));
2007                } else {
2008                    Ok(None)
2009                }
2010            }
2011            btree_map::Entry::Vacant(e) => Ok(Some(
2012                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
2013                    inode,
2014                    mtime,
2015                    len: content.len() as u64,
2016                    content,
2017                    git_dir_path: None,
2018                })))
2019                .clone(),
2020            )),
2021        })?;
2022        state.emit_event([(target, kind)]);
2023        Ok(())
2024    }
2025
2026    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2027        self.simulate_random_delay().await;
2028
2029        let path = normalize_path(path);
2030        let parent_path = path
2031            .parent()
2032            .ok_or_else(|| anyhow!("cannot remove the root"))?;
2033        let base_name = path.file_name().unwrap();
2034
2035        let mut state = self.state.lock();
2036        let parent_entry = state.read_path(parent_path)?;
2037        let mut parent_entry = parent_entry.lock();
2038        let entry = parent_entry
2039            .dir_entries(parent_path)?
2040            .entry(base_name.to_str().unwrap().into());
2041
2042        match entry {
2043            btree_map::Entry::Vacant(_) => {
2044                if !options.ignore_if_not_exists {
2045                    return Err(anyhow!("{path:?} does not exist"));
2046                }
2047            }
2048            btree_map::Entry::Occupied(e) => {
2049                {
2050                    let mut entry = e.get().lock();
2051                    let children = entry.dir_entries(&path)?;
2052                    if !options.recursive && !children.is_empty() {
2053                        return Err(anyhow!("{path:?} is not empty"));
2054                    }
2055                }
2056                e.remove();
2057            }
2058        }
2059        state.emit_event([(path, Some(PathEventKind::Removed))]);
2060        Ok(())
2061    }
2062
2063    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2064        self.simulate_random_delay().await;
2065
2066        let path = normalize_path(path);
2067        let parent_path = path
2068            .parent()
2069            .ok_or_else(|| anyhow!("cannot remove the root"))?;
2070        let base_name = path.file_name().unwrap();
2071        let mut state = self.state.lock();
2072        let parent_entry = state.read_path(parent_path)?;
2073        let mut parent_entry = parent_entry.lock();
2074        let entry = parent_entry
2075            .dir_entries(parent_path)?
2076            .entry(base_name.to_str().unwrap().into());
2077        match entry {
2078            btree_map::Entry::Vacant(_) => {
2079                if !options.ignore_if_not_exists {
2080                    return Err(anyhow!("{path:?} does not exist"));
2081                }
2082            }
2083            btree_map::Entry::Occupied(e) => {
2084                e.get().lock().file_content(&path)?;
2085                e.remove();
2086            }
2087        }
2088        state.emit_event([(path, Some(PathEventKind::Removed))]);
2089        Ok(())
2090    }
2091
2092    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2093        let bytes = self.load_internal(path).await?;
2094        Ok(Box::new(io::Cursor::new(bytes)))
2095    }
2096
2097    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2098        self.simulate_random_delay().await;
2099        let state = self.state.lock();
2100        let entry = state.read_path(&path)?;
2101        let entry = entry.lock();
2102        let inode = match *entry {
2103            FakeFsEntry::File { inode, .. } => inode,
2104            FakeFsEntry::Dir { inode, .. } => inode,
2105            _ => unreachable!(),
2106        };
2107        Ok(Arc::new(FakeHandle { inode }))
2108    }
2109
2110    async fn load(&self, path: &Path) -> Result<String> {
2111        let content = self.load_internal(path).await?;
2112        Ok(String::from_utf8(content.clone())?)
2113    }
2114
2115    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2116        self.load_internal(path).await
2117    }
2118
2119    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2120        self.simulate_random_delay().await;
2121        let path = normalize_path(path.as_path());
2122        self.write_file_internal(path, data.into_bytes(), true)?;
2123        Ok(())
2124    }
2125
2126    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2127        self.simulate_random_delay().await;
2128        let path = normalize_path(path);
2129        let content = chunks(text, line_ending).collect::<String>();
2130        if let Some(path) = path.parent() {
2131            self.create_dir(path).await?;
2132        }
2133        self.write_file_internal(path, content.into_bytes(), false)?;
2134        Ok(())
2135    }
2136
2137    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2138        self.simulate_random_delay().await;
2139        let path = normalize_path(path);
2140        if let Some(path) = path.parent() {
2141            self.create_dir(path).await?;
2142        }
2143        self.write_file_internal(path, content.to_vec(), false)?;
2144        Ok(())
2145    }
2146
2147    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2148        let path = normalize_path(path);
2149        self.simulate_random_delay().await;
2150        let state = self.state.lock();
2151        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
2152            Ok(canonical_path)
2153        } else {
2154            Err(anyhow!("path does not exist: {}", path.display()))
2155        }
2156    }
2157
2158    async fn is_file(&self, path: &Path) -> bool {
2159        let path = normalize_path(path);
2160        self.simulate_random_delay().await;
2161        let state = self.state.lock();
2162        if let Some((entry, _)) = state.try_read_path(&path, true) {
2163            entry.lock().is_file()
2164        } else {
2165            false
2166        }
2167    }
2168
2169    async fn is_dir(&self, path: &Path) -> bool {
2170        self.metadata(path)
2171            .await
2172            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2173    }
2174
2175    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2176        self.simulate_random_delay().await;
2177        let path = normalize_path(path);
2178        let mut state = self.state.lock();
2179        state.metadata_call_count += 1;
2180        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
2181            let is_symlink = entry.lock().is_symlink();
2182            if is_symlink {
2183                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
2184                    entry = e;
2185                } else {
2186                    return Ok(None);
2187                }
2188            }
2189
2190            let entry = entry.lock();
2191            Ok(Some(match &*entry {
2192                FakeFsEntry::File {
2193                    inode, mtime, len, ..
2194                } => Metadata {
2195                    inode: *inode,
2196                    mtime: *mtime,
2197                    len: *len,
2198                    is_dir: false,
2199                    is_symlink,
2200                    is_fifo: false,
2201                },
2202                FakeFsEntry::Dir {
2203                    inode, mtime, len, ..
2204                } => Metadata {
2205                    inode: *inode,
2206                    mtime: *mtime,
2207                    len: *len,
2208                    is_dir: true,
2209                    is_symlink,
2210                    is_fifo: false,
2211                },
2212                FakeFsEntry::Symlink { .. } => unreachable!(),
2213            }))
2214        } else {
2215            Ok(None)
2216        }
2217    }
2218
2219    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2220        self.simulate_random_delay().await;
2221        let path = normalize_path(path);
2222        let state = self.state.lock();
2223        if let Some((entry, _)) = state.try_read_path(&path, false) {
2224            let entry = entry.lock();
2225            if let FakeFsEntry::Symlink { target } = &*entry {
2226                Ok(target.clone())
2227            } else {
2228                Err(anyhow!("not a symlink: {}", path.display()))
2229            }
2230        } else {
2231            Err(anyhow!("path does not exist: {}", path.display()))
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        chunk.split('\n').flat_map(move |line| {
2344            let ending = if newline {
2345                Some(line_ending.as_str())
2346            } else {
2347                None
2348            };
2349            newline = true;
2350            ending.into_iter().chain([line])
2351        })
2352    })
2353}
2354
2355pub fn normalize_path(path: &Path) -> PathBuf {
2356    let mut components = path.components().peekable();
2357    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2358        components.next();
2359        PathBuf::from(c.as_os_str())
2360    } else {
2361        PathBuf::new()
2362    };
2363
2364    for component in components {
2365        match component {
2366            Component::Prefix(..) => unreachable!(),
2367            Component::RootDir => {
2368                ret.push(component.as_os_str());
2369            }
2370            Component::CurDir => {}
2371            Component::ParentDir => {
2372                ret.pop();
2373            }
2374            Component::Normal(c) => {
2375                ret.push(c);
2376            }
2377        }
2378    }
2379    ret
2380}
2381
2382pub async fn copy_recursive<'a>(
2383    fs: &'a dyn Fs,
2384    source: &'a Path,
2385    target: &'a Path,
2386    options: CopyOptions,
2387) -> Result<()> {
2388    for (item, is_dir) in read_dir_items(fs, source).await? {
2389        let Ok(item_relative_path) = item.strip_prefix(source) else {
2390            continue;
2391        };
2392        let target_item = if item_relative_path == Path::new("") {
2393            target.to_path_buf()
2394        } else {
2395            target.join(item_relative_path)
2396        };
2397        if is_dir {
2398            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2399                if options.ignore_if_exists {
2400                    continue;
2401                } else {
2402                    return Err(anyhow!("{target_item:?} already exists"));
2403                }
2404            }
2405            let _ = fs
2406                .remove_dir(
2407                    &target_item,
2408                    RemoveOptions {
2409                        recursive: true,
2410                        ignore_if_not_exists: true,
2411                    },
2412                )
2413                .await;
2414            fs.create_dir(&target_item).await?;
2415        } else {
2416            fs.copy_file(&item, &target_item, options).await?;
2417        }
2418    }
2419    Ok(())
2420}
2421
2422/// Recursively reads all of the paths in the given directory.
2423///
2424/// Returns a vector of tuples of (path, is_dir).
2425pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2426    let mut items = Vec::new();
2427    read_recursive(fs, source, &mut items).await?;
2428    Ok(items)
2429}
2430
2431fn read_recursive<'a>(
2432    fs: &'a dyn Fs,
2433    source: &'a Path,
2434    output: &'a mut Vec<(PathBuf, bool)>,
2435) -> BoxFuture<'a, Result<()>> {
2436    use futures::future::FutureExt;
2437
2438    async move {
2439        let metadata = fs
2440            .metadata(source)
2441            .await?
2442            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2443
2444        if metadata.is_dir {
2445            output.push((source.to_path_buf(), true));
2446            let mut children = fs.read_dir(source).await?;
2447            while let Some(child_path) = children.next().await {
2448                if let Ok(child_path) = child_path {
2449                    read_recursive(fs, &child_path, output).await?;
2450                }
2451            }
2452        } else {
2453            output.push((source.to_path_buf(), false));
2454        }
2455        Ok(())
2456    }
2457    .boxed()
2458}
2459
2460// todo(windows)
2461// can we get file id not open the file twice?
2462// https://github.com/rust-lang/rust/issues/63010
2463#[cfg(target_os = "windows")]
2464async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2465    use std::os::windows::io::AsRawHandle;
2466
2467    use smol::fs::windows::OpenOptionsExt;
2468    use windows::Win32::{
2469        Foundation::HANDLE,
2470        Storage::FileSystem::{
2471            BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2472        },
2473    };
2474
2475    let file = smol::fs::OpenOptions::new()
2476        .read(true)
2477        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2478        .open(path)
2479        .await?;
2480
2481    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2482    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2483    // This function supports Windows XP+
2484    smol::unblock(move || {
2485        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2486
2487        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2488    })
2489    .await
2490}
2491
2492#[cfg(target_os = "windows")]
2493fn atomic_replace<P: AsRef<Path>>(
2494    replaced_file: P,
2495    replacement_file: P,
2496) -> windows::core::Result<()> {
2497    use windows::{
2498        Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2499        core::HSTRING,
2500    };
2501
2502    // If the file does not exist, create it.
2503    let _ = std::fs::File::create_new(replaced_file.as_ref());
2504
2505    unsafe {
2506        ReplaceFileW(
2507            &HSTRING::from(replaced_file.as_ref().to_string_lossy().to_string()),
2508            &HSTRING::from(replacement_file.as_ref().to_string_lossy().to_string()),
2509            None,
2510            REPLACE_FILE_FLAGS::default(),
2511            None,
2512            None,
2513        )
2514    }
2515}
2516
2517#[cfg(test)]
2518mod tests {
2519    use super::*;
2520    use gpui::BackgroundExecutor;
2521    use serde_json::json;
2522    use util::path;
2523
2524    #[gpui::test]
2525    async fn test_fake_fs(executor: BackgroundExecutor) {
2526        let fs = FakeFs::new(executor.clone());
2527        fs.insert_tree(
2528            path!("/root"),
2529            json!({
2530                "dir1": {
2531                    "a": "A",
2532                    "b": "B"
2533                },
2534                "dir2": {
2535                    "c": "C",
2536                    "dir3": {
2537                        "d": "D"
2538                    }
2539                }
2540            }),
2541        )
2542        .await;
2543
2544        assert_eq!(
2545            fs.files(),
2546            vec![
2547                PathBuf::from(path!("/root/dir1/a")),
2548                PathBuf::from(path!("/root/dir1/b")),
2549                PathBuf::from(path!("/root/dir2/c")),
2550                PathBuf::from(path!("/root/dir2/dir3/d")),
2551            ]
2552        );
2553
2554        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2555            .await
2556            .unwrap();
2557
2558        assert_eq!(
2559            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2560                .await
2561                .unwrap(),
2562            PathBuf::from(path!("/root/dir2/dir3")),
2563        );
2564        assert_eq!(
2565            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2566                .await
2567                .unwrap(),
2568            PathBuf::from(path!("/root/dir2/dir3/d")),
2569        );
2570        assert_eq!(
2571            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2572                .await
2573                .unwrap(),
2574            "D",
2575        );
2576    }
2577
2578    #[gpui::test]
2579    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2580        let fs = FakeFs::new(executor.clone());
2581        fs.insert_tree(
2582            path!("/outer"),
2583            json!({
2584                "a": "A",
2585                "b": "B",
2586                "inner": {}
2587            }),
2588        )
2589        .await;
2590
2591        assert_eq!(
2592            fs.files(),
2593            vec![
2594                PathBuf::from(path!("/outer/a")),
2595                PathBuf::from(path!("/outer/b")),
2596            ]
2597        );
2598
2599        let source = Path::new(path!("/outer/a"));
2600        let target = Path::new(path!("/outer/a copy"));
2601        copy_recursive(fs.as_ref(), source, target, Default::default())
2602            .await
2603            .unwrap();
2604
2605        assert_eq!(
2606            fs.files(),
2607            vec![
2608                PathBuf::from(path!("/outer/a")),
2609                PathBuf::from(path!("/outer/a copy")),
2610                PathBuf::from(path!("/outer/b")),
2611            ]
2612        );
2613
2614        let source = Path::new(path!("/outer/a"));
2615        let target = Path::new(path!("/outer/inner/a copy"));
2616        copy_recursive(fs.as_ref(), source, target, Default::default())
2617            .await
2618            .unwrap();
2619
2620        assert_eq!(
2621            fs.files(),
2622            vec![
2623                PathBuf::from(path!("/outer/a")),
2624                PathBuf::from(path!("/outer/a copy")),
2625                PathBuf::from(path!("/outer/b")),
2626                PathBuf::from(path!("/outer/inner/a copy")),
2627            ]
2628        );
2629    }
2630
2631    #[gpui::test]
2632    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2633        let fs = FakeFs::new(executor.clone());
2634        fs.insert_tree(
2635            path!("/outer"),
2636            json!({
2637                "a": "A",
2638                "empty": {},
2639                "non-empty": {
2640                    "b": "B",
2641                }
2642            }),
2643        )
2644        .await;
2645
2646        assert_eq!(
2647            fs.files(),
2648            vec![
2649                PathBuf::from(path!("/outer/a")),
2650                PathBuf::from(path!("/outer/non-empty/b")),
2651            ]
2652        );
2653        assert_eq!(
2654            fs.directories(false),
2655            vec![
2656                PathBuf::from(path!("/")),
2657                PathBuf::from(path!("/outer")),
2658                PathBuf::from(path!("/outer/empty")),
2659                PathBuf::from(path!("/outer/non-empty")),
2660            ]
2661        );
2662
2663        let source = Path::new(path!("/outer/empty"));
2664        let target = Path::new(path!("/outer/empty copy"));
2665        copy_recursive(fs.as_ref(), source, target, Default::default())
2666            .await
2667            .unwrap();
2668
2669        assert_eq!(
2670            fs.files(),
2671            vec![
2672                PathBuf::from(path!("/outer/a")),
2673                PathBuf::from(path!("/outer/non-empty/b")),
2674            ]
2675        );
2676        assert_eq!(
2677            fs.directories(false),
2678            vec![
2679                PathBuf::from(path!("/")),
2680                PathBuf::from(path!("/outer")),
2681                PathBuf::from(path!("/outer/empty")),
2682                PathBuf::from(path!("/outer/empty copy")),
2683                PathBuf::from(path!("/outer/non-empty")),
2684            ]
2685        );
2686
2687        let source = Path::new(path!("/outer/non-empty"));
2688        let target = Path::new(path!("/outer/non-empty copy"));
2689        copy_recursive(fs.as_ref(), source, target, Default::default())
2690            .await
2691            .unwrap();
2692
2693        assert_eq!(
2694            fs.files(),
2695            vec![
2696                PathBuf::from(path!("/outer/a")),
2697                PathBuf::from(path!("/outer/non-empty/b")),
2698                PathBuf::from(path!("/outer/non-empty copy/b")),
2699            ]
2700        );
2701        assert_eq!(
2702            fs.directories(false),
2703            vec![
2704                PathBuf::from(path!("/")),
2705                PathBuf::from(path!("/outer")),
2706                PathBuf::from(path!("/outer/empty")),
2707                PathBuf::from(path!("/outer/empty copy")),
2708                PathBuf::from(path!("/outer/non-empty")),
2709                PathBuf::from(path!("/outer/non-empty copy")),
2710            ]
2711        );
2712    }
2713
2714    #[gpui::test]
2715    async fn test_copy_recursive(executor: BackgroundExecutor) {
2716        let fs = FakeFs::new(executor.clone());
2717        fs.insert_tree(
2718            path!("/outer"),
2719            json!({
2720                "inner1": {
2721                    "a": "A",
2722                    "b": "B",
2723                    "inner3": {
2724                        "d": "D",
2725                    },
2726                    "inner4": {}
2727                },
2728                "inner2": {
2729                    "c": "C",
2730                }
2731            }),
2732        )
2733        .await;
2734
2735        assert_eq!(
2736            fs.files(),
2737            vec![
2738                PathBuf::from(path!("/outer/inner1/a")),
2739                PathBuf::from(path!("/outer/inner1/b")),
2740                PathBuf::from(path!("/outer/inner2/c")),
2741                PathBuf::from(path!("/outer/inner1/inner3/d")),
2742            ]
2743        );
2744        assert_eq!(
2745            fs.directories(false),
2746            vec![
2747                PathBuf::from(path!("/")),
2748                PathBuf::from(path!("/outer")),
2749                PathBuf::from(path!("/outer/inner1")),
2750                PathBuf::from(path!("/outer/inner2")),
2751                PathBuf::from(path!("/outer/inner1/inner3")),
2752                PathBuf::from(path!("/outer/inner1/inner4")),
2753            ]
2754        );
2755
2756        let source = Path::new(path!("/outer"));
2757        let target = Path::new(path!("/outer/inner1/outer"));
2758        copy_recursive(fs.as_ref(), source, target, Default::default())
2759            .await
2760            .unwrap();
2761
2762        assert_eq!(
2763            fs.files(),
2764            vec![
2765                PathBuf::from(path!("/outer/inner1/a")),
2766                PathBuf::from(path!("/outer/inner1/b")),
2767                PathBuf::from(path!("/outer/inner2/c")),
2768                PathBuf::from(path!("/outer/inner1/inner3/d")),
2769                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2770                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2771                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2772                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2773            ]
2774        );
2775        assert_eq!(
2776            fs.directories(false),
2777            vec![
2778                PathBuf::from(path!("/")),
2779                PathBuf::from(path!("/outer")),
2780                PathBuf::from(path!("/outer/inner1")),
2781                PathBuf::from(path!("/outer/inner2")),
2782                PathBuf::from(path!("/outer/inner1/inner3")),
2783                PathBuf::from(path!("/outer/inner1/inner4")),
2784                PathBuf::from(path!("/outer/inner1/outer")),
2785                PathBuf::from(path!("/outer/inner1/outer/inner1")),
2786                PathBuf::from(path!("/outer/inner1/outer/inner2")),
2787                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
2788                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
2789            ]
2790        );
2791    }
2792
2793    #[gpui::test]
2794    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2795        let fs = FakeFs::new(executor.clone());
2796        fs.insert_tree(
2797            path!("/outer"),
2798            json!({
2799                "inner1": {
2800                    "a": "A",
2801                    "b": "B",
2802                    "outer": {
2803                        "inner1": {
2804                            "a": "B"
2805                        }
2806                    }
2807                },
2808                "inner2": {
2809                    "c": "C",
2810                }
2811            }),
2812        )
2813        .await;
2814
2815        assert_eq!(
2816            fs.files(),
2817            vec![
2818                PathBuf::from(path!("/outer/inner1/a")),
2819                PathBuf::from(path!("/outer/inner1/b")),
2820                PathBuf::from(path!("/outer/inner2/c")),
2821                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2822            ]
2823        );
2824        assert_eq!(
2825            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2826                .await
2827                .unwrap(),
2828            "B",
2829        );
2830
2831        let source = Path::new(path!("/outer"));
2832        let target = Path::new(path!("/outer/inner1/outer"));
2833        copy_recursive(
2834            fs.as_ref(),
2835            source,
2836            target,
2837            CopyOptions {
2838                overwrite: true,
2839                ..Default::default()
2840            },
2841        )
2842        .await
2843        .unwrap();
2844
2845        assert_eq!(
2846            fs.files(),
2847            vec![
2848                PathBuf::from(path!("/outer/inner1/a")),
2849                PathBuf::from(path!("/outer/inner1/b")),
2850                PathBuf::from(path!("/outer/inner2/c")),
2851                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2852                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2853                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2854                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2855            ]
2856        );
2857        assert_eq!(
2858            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2859                .await
2860                .unwrap(),
2861            "A"
2862        );
2863    }
2864
2865    #[gpui::test]
2866    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
2867        let fs = FakeFs::new(executor.clone());
2868        fs.insert_tree(
2869            path!("/outer"),
2870            json!({
2871                "inner1": {
2872                    "a": "A",
2873                    "b": "B",
2874                    "outer": {
2875                        "inner1": {
2876                            "a": "B"
2877                        }
2878                    }
2879                },
2880                "inner2": {
2881                    "c": "C",
2882                }
2883            }),
2884        )
2885        .await;
2886
2887        assert_eq!(
2888            fs.files(),
2889            vec![
2890                PathBuf::from(path!("/outer/inner1/a")),
2891                PathBuf::from(path!("/outer/inner1/b")),
2892                PathBuf::from(path!("/outer/inner2/c")),
2893                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2894            ]
2895        );
2896        assert_eq!(
2897            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2898                .await
2899                .unwrap(),
2900            "B",
2901        );
2902
2903        let source = Path::new(path!("/outer"));
2904        let target = Path::new(path!("/outer/inner1/outer"));
2905        copy_recursive(
2906            fs.as_ref(),
2907            source,
2908            target,
2909            CopyOptions {
2910                ignore_if_exists: true,
2911                ..Default::default()
2912            },
2913        )
2914        .await
2915        .unwrap();
2916
2917        assert_eq!(
2918            fs.files(),
2919            vec![
2920                PathBuf::from(path!("/outer/inner1/a")),
2921                PathBuf::from(path!("/outer/inner1/b")),
2922                PathBuf::from(path!("/outer/inner2/c")),
2923                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2924                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2925                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2926                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2927            ]
2928        );
2929        assert_eq!(
2930            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2931                .await
2932                .unwrap(),
2933            "B"
2934        );
2935    }
2936
2937    #[gpui::test]
2938    async fn test_realfs_atomic_write(executor: BackgroundExecutor) {
2939        // With the file handle still open, the file should be replaced
2940        // https://github.com/zed-industries/zed/issues/30054
2941        let fs = RealFs {
2942            git_binary_path: None,
2943            executor,
2944        };
2945        let temp_dir = TempDir::new().unwrap();
2946        let file_to_be_replaced = temp_dir.path().join("file.txt");
2947        let mut file = std::fs::File::create_new(&file_to_be_replaced).unwrap();
2948        file.write_all(b"Hello").unwrap();
2949        // drop(file);  // We still hold the file handle here
2950        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
2951        assert_eq!(content, "Hello");
2952        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "World".into())).unwrap();
2953        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
2954        assert_eq!(content, "World");
2955    }
2956
2957    #[gpui::test]
2958    async fn test_realfs_atomic_write_non_existing_file(executor: BackgroundExecutor) {
2959        let fs = RealFs {
2960            git_binary_path: None,
2961            executor,
2962        };
2963        let temp_dir = TempDir::new().unwrap();
2964        let file_to_be_replaced = temp_dir.path().join("file.txt");
2965        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "Hello".into())).unwrap();
2966        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
2967        assert_eq!(content, "Hello");
2968    }
2969}