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