fs.rs

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