fs.rs

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