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