fs.rs

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