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