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