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 paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1452        let mut result = Vec::new();
1453        let mut queue = collections::VecDeque::new();
1454        queue.push_back((
1455            PathBuf::from(util::path!("/")),
1456            self.state.lock().root.clone(),
1457        ));
1458        while let Some((path, entry)) = queue.pop_front() {
1459            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1460                for (name, entry) in entries {
1461                    queue.push_back((path.join(name), entry.clone()));
1462                }
1463            }
1464            if include_dot_git
1465                || !path
1466                    .components()
1467                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1468            {
1469                result.push(path);
1470            }
1471        }
1472        result
1473    }
1474
1475    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1476        let mut result = Vec::new();
1477        let mut queue = collections::VecDeque::new();
1478        queue.push_back((
1479            PathBuf::from(util::path!("/")),
1480            self.state.lock().root.clone(),
1481        ));
1482        while let Some((path, entry)) = queue.pop_front() {
1483            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1484                for (name, entry) in entries {
1485                    queue.push_back((path.join(name), entry.clone()));
1486                }
1487                if include_dot_git
1488                    || !path
1489                        .components()
1490                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1491                {
1492                    result.push(path);
1493                }
1494            }
1495        }
1496        result
1497    }
1498
1499    pub fn files(&self) -> Vec<PathBuf> {
1500        let mut result = Vec::new();
1501        let mut queue = collections::VecDeque::new();
1502        queue.push_back((
1503            PathBuf::from(util::path!("/")),
1504            self.state.lock().root.clone(),
1505        ));
1506        while let Some((path, entry)) = queue.pop_front() {
1507            let e = entry.lock();
1508            match &*e {
1509                FakeFsEntry::File { .. } => result.push(path),
1510                FakeFsEntry::Dir { entries, .. } => {
1511                    for (name, entry) in entries {
1512                        queue.push_back((path.join(name), entry.clone()));
1513                    }
1514                }
1515                FakeFsEntry::Symlink { .. } => {}
1516            }
1517        }
1518        result
1519    }
1520
1521    /// How many `read_dir` calls have been issued.
1522    pub fn read_dir_call_count(&self) -> usize {
1523        self.state.lock().read_dir_call_count
1524    }
1525
1526    /// How many `metadata` calls have been issued.
1527    pub fn metadata_call_count(&self) -> usize {
1528        self.state.lock().metadata_call_count
1529    }
1530
1531    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1532        self.executor.simulate_random_delay()
1533    }
1534
1535    pub fn set_home_dir(&self, home_dir: PathBuf) {
1536        self.state.lock().home_dir = Some(home_dir);
1537    }
1538}
1539
1540#[cfg(any(test, feature = "test-support"))]
1541impl FakeFsEntry {
1542    fn is_file(&self) -> bool {
1543        matches!(self, Self::File { .. })
1544    }
1545
1546    fn is_symlink(&self) -> bool {
1547        matches!(self, Self::Symlink { .. })
1548    }
1549
1550    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1551        if let Self::File { content, .. } = self {
1552            Ok(content)
1553        } else {
1554            Err(anyhow!("not a file: {}", path.display()))
1555        }
1556    }
1557
1558    fn dir_entries(
1559        &mut self,
1560        path: &Path,
1561    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1562        if let Self::Dir { entries, .. } = self {
1563            Ok(entries)
1564        } else {
1565            Err(anyhow!("not a directory: {}", path.display()))
1566        }
1567    }
1568}
1569
1570#[cfg(any(test, feature = "test-support"))]
1571struct FakeWatcher {}
1572
1573#[cfg(any(test, feature = "test-support"))]
1574impl Watcher for FakeWatcher {
1575    fn add(&self, _: &Path) -> Result<()> {
1576        Ok(())
1577    }
1578
1579    fn remove(&self, _: &Path) -> Result<()> {
1580        Ok(())
1581    }
1582}
1583
1584#[cfg(any(test, feature = "test-support"))]
1585#[derive(Debug)]
1586struct FakeHandle {
1587    inode: u64,
1588}
1589
1590#[cfg(any(test, feature = "test-support"))]
1591impl FileHandle for FakeHandle {
1592    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1593        let fs = fs.as_fake();
1594        let state = fs.state.lock();
1595        let Some(target) = state.moves.get(&self.inode) else {
1596            anyhow::bail!("fake fd not moved")
1597        };
1598
1599        if state.try_read_path(&target, false).is_some() {
1600            return Ok(target.clone());
1601        }
1602        anyhow::bail!("fake fd target not found")
1603    }
1604}
1605
1606#[cfg(any(test, feature = "test-support"))]
1607#[async_trait::async_trait]
1608impl Fs for FakeFs {
1609    async fn create_dir(&self, path: &Path) -> Result<()> {
1610        self.simulate_random_delay().await;
1611
1612        let mut created_dirs = Vec::new();
1613        let mut cur_path = PathBuf::new();
1614        for component in path.components() {
1615            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1616            cur_path.push(component);
1617            if should_skip {
1618                continue;
1619            }
1620            let mut state = self.state.lock();
1621
1622            let inode = state.get_and_increment_inode();
1623            let mtime = state.get_and_increment_mtime();
1624            state.write_path(&cur_path, |entry| {
1625                entry.or_insert_with(|| {
1626                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1627                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1628                        inode,
1629                        mtime,
1630                        len: 0,
1631                        entries: Default::default(),
1632                        git_repo_state: None,
1633                    }))
1634                });
1635                Ok(())
1636            })?
1637        }
1638
1639        self.state.lock().emit_event(created_dirs);
1640        Ok(())
1641    }
1642
1643    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1644        self.simulate_random_delay().await;
1645        let mut state = self.state.lock();
1646        let inode = state.get_and_increment_inode();
1647        let mtime = state.get_and_increment_mtime();
1648        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1649            inode,
1650            mtime,
1651            len: 0,
1652            content: Vec::new(),
1653        }));
1654        let mut kind = Some(PathEventKind::Created);
1655        state.write_path(path, |entry| {
1656            match entry {
1657                btree_map::Entry::Occupied(mut e) => {
1658                    if options.overwrite {
1659                        kind = Some(PathEventKind::Changed);
1660                        *e.get_mut() = file;
1661                    } else if !options.ignore_if_exists {
1662                        return Err(anyhow!("path already exists: {}", path.display()));
1663                    }
1664                }
1665                btree_map::Entry::Vacant(e) => {
1666                    e.insert(file);
1667                }
1668            }
1669            Ok(())
1670        })?;
1671        state.emit_event([(path, kind)]);
1672        Ok(())
1673    }
1674
1675    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1676        let mut state = self.state.lock();
1677        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1678        state
1679            .write_path(path.as_ref(), move |e| match e {
1680                btree_map::Entry::Vacant(e) => {
1681                    e.insert(file);
1682                    Ok(())
1683                }
1684                btree_map::Entry::Occupied(mut e) => {
1685                    *e.get_mut() = file;
1686                    Ok(())
1687                }
1688            })
1689            .unwrap();
1690        state.emit_event([(path, None)]);
1691
1692        Ok(())
1693    }
1694
1695    async fn create_file_with(
1696        &self,
1697        path: &Path,
1698        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1699    ) -> Result<()> {
1700        let mut bytes = Vec::new();
1701        content.read_to_end(&mut bytes).await?;
1702        self.write_file_internal(path, bytes)?;
1703        Ok(())
1704    }
1705
1706    async fn extract_tar_file(
1707        &self,
1708        path: &Path,
1709        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1710    ) -> Result<()> {
1711        let mut entries = content.entries()?;
1712        while let Some(entry) = entries.next().await {
1713            let mut entry = entry?;
1714            if entry.header().entry_type().is_file() {
1715                let path = path.join(entry.path()?.as_ref());
1716                let mut bytes = Vec::new();
1717                entry.read_to_end(&mut bytes).await?;
1718                self.create_dir(path.parent().unwrap()).await?;
1719                self.write_file_internal(&path, bytes)?;
1720            }
1721        }
1722        Ok(())
1723    }
1724
1725    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1726        self.simulate_random_delay().await;
1727
1728        let old_path = normalize_path(old_path);
1729        let new_path = normalize_path(new_path);
1730
1731        let mut state = self.state.lock();
1732        let moved_entry = state.write_path(&old_path, |e| {
1733            if let btree_map::Entry::Occupied(e) = e {
1734                Ok(e.get().clone())
1735            } else {
1736                Err(anyhow!("path does not exist: {}", &old_path.display()))
1737            }
1738        })?;
1739
1740        let inode = match *moved_entry.lock() {
1741            FakeFsEntry::File { inode, .. } => inode,
1742            FakeFsEntry::Dir { inode, .. } => inode,
1743            _ => 0,
1744        };
1745
1746        state.moves.insert(inode, new_path.clone());
1747
1748        state.write_path(&new_path, |e| {
1749            match e {
1750                btree_map::Entry::Occupied(mut e) => {
1751                    if options.overwrite {
1752                        *e.get_mut() = moved_entry;
1753                    } else if !options.ignore_if_exists {
1754                        return Err(anyhow!("path already exists: {}", new_path.display()));
1755                    }
1756                }
1757                btree_map::Entry::Vacant(e) => {
1758                    e.insert(moved_entry);
1759                }
1760            }
1761            Ok(())
1762        })?;
1763
1764        state
1765            .write_path(&old_path, |e| {
1766                if let btree_map::Entry::Occupied(e) = e {
1767                    Ok(e.remove())
1768                } else {
1769                    unreachable!()
1770                }
1771            })
1772            .unwrap();
1773
1774        state.emit_event([
1775            (old_path, Some(PathEventKind::Removed)),
1776            (new_path, Some(PathEventKind::Created)),
1777        ]);
1778        Ok(())
1779    }
1780
1781    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1782        self.simulate_random_delay().await;
1783
1784        let source = normalize_path(source);
1785        let target = normalize_path(target);
1786        let mut state = self.state.lock();
1787        let mtime = state.get_and_increment_mtime();
1788        let inode = state.get_and_increment_inode();
1789        let source_entry = state.read_path(&source)?;
1790        let content = source_entry.lock().file_content(&source)?.clone();
1791        let mut kind = Some(PathEventKind::Created);
1792        state.write_path(&target, |e| match e {
1793            btree_map::Entry::Occupied(e) => {
1794                if options.overwrite {
1795                    kind = Some(PathEventKind::Changed);
1796                    Ok(Some(e.get().clone()))
1797                } else if !options.ignore_if_exists {
1798                    return Err(anyhow!("{target:?} already exists"));
1799                } else {
1800                    Ok(None)
1801                }
1802            }
1803            btree_map::Entry::Vacant(e) => Ok(Some(
1804                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1805                    inode,
1806                    mtime,
1807                    len: content.len() as u64,
1808                    content,
1809                })))
1810                .clone(),
1811            )),
1812        })?;
1813        state.emit_event([(target, kind)]);
1814        Ok(())
1815    }
1816
1817    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1818        self.simulate_random_delay().await;
1819
1820        let path = normalize_path(path);
1821        let parent_path = path
1822            .parent()
1823            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1824        let base_name = path.file_name().unwrap();
1825
1826        let mut state = self.state.lock();
1827        let parent_entry = state.read_path(parent_path)?;
1828        let mut parent_entry = parent_entry.lock();
1829        let entry = parent_entry
1830            .dir_entries(parent_path)?
1831            .entry(base_name.to_str().unwrap().into());
1832
1833        match entry {
1834            btree_map::Entry::Vacant(_) => {
1835                if !options.ignore_if_not_exists {
1836                    return Err(anyhow!("{path:?} does not exist"));
1837                }
1838            }
1839            btree_map::Entry::Occupied(e) => {
1840                {
1841                    let mut entry = e.get().lock();
1842                    let children = entry.dir_entries(&path)?;
1843                    if !options.recursive && !children.is_empty() {
1844                        return Err(anyhow!("{path:?} is not empty"));
1845                    }
1846                }
1847                e.remove();
1848            }
1849        }
1850        state.emit_event([(path, Some(PathEventKind::Removed))]);
1851        Ok(())
1852    }
1853
1854    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1855        self.simulate_random_delay().await;
1856
1857        let path = normalize_path(path);
1858        let parent_path = path
1859            .parent()
1860            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1861        let base_name = path.file_name().unwrap();
1862        let mut state = self.state.lock();
1863        let parent_entry = state.read_path(parent_path)?;
1864        let mut parent_entry = parent_entry.lock();
1865        let entry = parent_entry
1866            .dir_entries(parent_path)?
1867            .entry(base_name.to_str().unwrap().into());
1868        match entry {
1869            btree_map::Entry::Vacant(_) => {
1870                if !options.ignore_if_not_exists {
1871                    return Err(anyhow!("{path:?} does not exist"));
1872                }
1873            }
1874            btree_map::Entry::Occupied(e) => {
1875                e.get().lock().file_content(&path)?;
1876                e.remove();
1877            }
1878        }
1879        state.emit_event([(path, Some(PathEventKind::Removed))]);
1880        Ok(())
1881    }
1882
1883    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
1884        let bytes = self.load_internal(path).await?;
1885        Ok(Box::new(io::Cursor::new(bytes)))
1886    }
1887
1888    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1889        self.simulate_random_delay().await;
1890        let state = self.state.lock();
1891        let entry = state.read_path(&path)?;
1892        let entry = entry.lock();
1893        let inode = match *entry {
1894            FakeFsEntry::File { inode, .. } => inode,
1895            FakeFsEntry::Dir { inode, .. } => inode,
1896            _ => unreachable!(),
1897        };
1898        Ok(Arc::new(FakeHandle { inode }))
1899    }
1900
1901    async fn load(&self, path: &Path) -> Result<String> {
1902        let content = self.load_internal(path).await?;
1903        Ok(String::from_utf8(content.clone())?)
1904    }
1905
1906    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1907        self.load_internal(path).await
1908    }
1909
1910    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1911        self.simulate_random_delay().await;
1912        let path = normalize_path(path.as_path());
1913        self.write_file_internal(path, data.into_bytes())?;
1914        Ok(())
1915    }
1916
1917    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1918        self.simulate_random_delay().await;
1919        let path = normalize_path(path);
1920        let content = chunks(text, line_ending).collect::<String>();
1921        if let Some(path) = path.parent() {
1922            self.create_dir(path).await?;
1923        }
1924        self.write_file_internal(path, content.into_bytes())?;
1925        Ok(())
1926    }
1927
1928    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1929        let path = normalize_path(path);
1930        self.simulate_random_delay().await;
1931        let state = self.state.lock();
1932        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1933            Ok(canonical_path)
1934        } else {
1935            Err(anyhow!("path does not exist: {}", path.display()))
1936        }
1937    }
1938
1939    async fn is_file(&self, path: &Path) -> bool {
1940        let path = normalize_path(path);
1941        self.simulate_random_delay().await;
1942        let state = self.state.lock();
1943        if let Some((entry, _)) = state.try_read_path(&path, true) {
1944            entry.lock().is_file()
1945        } else {
1946            false
1947        }
1948    }
1949
1950    async fn is_dir(&self, path: &Path) -> bool {
1951        self.metadata(path)
1952            .await
1953            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1954    }
1955
1956    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1957        self.simulate_random_delay().await;
1958        let path = normalize_path(path);
1959        let mut state = self.state.lock();
1960        state.metadata_call_count += 1;
1961        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1962            let is_symlink = entry.lock().is_symlink();
1963            if is_symlink {
1964                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1965                    entry = e;
1966                } else {
1967                    return Ok(None);
1968                }
1969            }
1970
1971            let entry = entry.lock();
1972            Ok(Some(match &*entry {
1973                FakeFsEntry::File {
1974                    inode, mtime, len, ..
1975                } => Metadata {
1976                    inode: *inode,
1977                    mtime: *mtime,
1978                    len: *len,
1979                    is_dir: false,
1980                    is_symlink,
1981                    is_fifo: false,
1982                },
1983                FakeFsEntry::Dir {
1984                    inode, mtime, len, ..
1985                } => Metadata {
1986                    inode: *inode,
1987                    mtime: *mtime,
1988                    len: *len,
1989                    is_dir: true,
1990                    is_symlink,
1991                    is_fifo: false,
1992                },
1993                FakeFsEntry::Symlink { .. } => unreachable!(),
1994            }))
1995        } else {
1996            Ok(None)
1997        }
1998    }
1999
2000    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2001        self.simulate_random_delay().await;
2002        let path = normalize_path(path);
2003        let state = self.state.lock();
2004        if let Some((entry, _)) = state.try_read_path(&path, false) {
2005            let entry = entry.lock();
2006            if let FakeFsEntry::Symlink { target } = &*entry {
2007                Ok(target.clone())
2008            } else {
2009                Err(anyhow!("not a symlink: {}", path.display()))
2010            }
2011        } else {
2012            Err(anyhow!("path does not exist: {}", path.display()))
2013        }
2014    }
2015
2016    async fn read_dir(
2017        &self,
2018        path: &Path,
2019    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2020        self.simulate_random_delay().await;
2021        let path = normalize_path(path);
2022        let mut state = self.state.lock();
2023        state.read_dir_call_count += 1;
2024        let entry = state.read_path(&path)?;
2025        let mut entry = entry.lock();
2026        let children = entry.dir_entries(&path)?;
2027        let paths = children
2028            .keys()
2029            .map(|file_name| Ok(path.join(file_name)))
2030            .collect::<Vec<_>>();
2031        Ok(Box::pin(futures::stream::iter(paths)))
2032    }
2033
2034    async fn watch(
2035        &self,
2036        path: &Path,
2037        _: Duration,
2038    ) -> (
2039        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2040        Arc<dyn Watcher>,
2041    ) {
2042        self.simulate_random_delay().await;
2043        let (tx, rx) = smol::channel::unbounded();
2044        self.state.lock().event_txs.push(tx);
2045        let path = path.to_path_buf();
2046        let executor = self.executor.clone();
2047        (
2048            Box::pin(futures::StreamExt::filter(rx, move |events| {
2049                let result = events
2050                    .iter()
2051                    .any(|evt_path| evt_path.path.starts_with(&path));
2052                let executor = executor.clone();
2053                async move {
2054                    executor.simulate_random_delay().await;
2055                    result
2056                }
2057            })),
2058            Arc::new(FakeWatcher {}),
2059        )
2060    }
2061
2062    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
2063        let state = self.state.lock();
2064        let entry = state.read_path(abs_dot_git).unwrap();
2065        let mut entry = entry.lock();
2066        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
2067            let state = git_repo_state
2068                .get_or_insert_with(|| {
2069                    Arc::new(Mutex::new(FakeGitRepositoryState::new(
2070                        abs_dot_git.to_path_buf(),
2071                        state.git_event_tx.clone(),
2072                    )))
2073                })
2074                .clone();
2075            Some(git::repository::FakeGitRepository::open(state))
2076        } else {
2077            None
2078        }
2079    }
2080
2081    fn is_fake(&self) -> bool {
2082        true
2083    }
2084
2085    async fn is_case_sensitive(&self) -> Result<bool> {
2086        Ok(true)
2087    }
2088
2089    #[cfg(any(test, feature = "test-support"))]
2090    fn as_fake(&self) -> Arc<FakeFs> {
2091        self.this.upgrade().unwrap()
2092    }
2093
2094    fn home_dir(&self) -> Option<PathBuf> {
2095        self.state.lock().home_dir.clone()
2096    }
2097}
2098
2099fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2100    rope.chunks().flat_map(move |chunk| {
2101        let mut newline = false;
2102        chunk.split('\n').flat_map(move |line| {
2103            let ending = if newline {
2104                Some(line_ending.as_str())
2105            } else {
2106                None
2107            };
2108            newline = true;
2109            ending.into_iter().chain([line])
2110        })
2111    })
2112}
2113
2114pub fn normalize_path(path: &Path) -> PathBuf {
2115    let mut components = path.components().peekable();
2116    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2117        components.next();
2118        PathBuf::from(c.as_os_str())
2119    } else {
2120        PathBuf::new()
2121    };
2122
2123    for component in components {
2124        match component {
2125            Component::Prefix(..) => unreachable!(),
2126            Component::RootDir => {
2127                ret.push(component.as_os_str());
2128            }
2129            Component::CurDir => {}
2130            Component::ParentDir => {
2131                ret.pop();
2132            }
2133            Component::Normal(c) => {
2134                ret.push(c);
2135            }
2136        }
2137    }
2138    ret
2139}
2140
2141pub async fn copy_recursive<'a>(
2142    fs: &'a dyn Fs,
2143    source: &'a Path,
2144    target: &'a Path,
2145    options: CopyOptions,
2146) -> Result<()> {
2147    for (is_dir, item) in read_dir_items(fs, source).await? {
2148        let Ok(item_relative_path) = item.strip_prefix(source) else {
2149            continue;
2150        };
2151        let target_item = if item_relative_path == Path::new("") {
2152            target.to_path_buf()
2153        } else {
2154            target.join(item_relative_path)
2155        };
2156        if is_dir {
2157            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2158                if options.ignore_if_exists {
2159                    continue;
2160                } else {
2161                    return Err(anyhow!("{target_item:?} already exists"));
2162                }
2163            }
2164            let _ = fs
2165                .remove_dir(
2166                    &target_item,
2167                    RemoveOptions {
2168                        recursive: true,
2169                        ignore_if_not_exists: true,
2170                    },
2171                )
2172                .await;
2173            fs.create_dir(&target_item).await?;
2174        } else {
2175            fs.copy_file(&item, &target_item, options).await?;
2176        }
2177    }
2178    Ok(())
2179}
2180
2181async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(bool, PathBuf)>> {
2182    let mut items = Vec::new();
2183    read_recursive(fs, source, &mut items).await?;
2184    Ok(items)
2185}
2186
2187fn read_recursive<'a>(
2188    fs: &'a dyn Fs,
2189    source: &'a Path,
2190    output: &'a mut Vec<(bool, PathBuf)>,
2191) -> BoxFuture<'a, Result<()>> {
2192    use futures::future::FutureExt;
2193
2194    async move {
2195        let metadata = fs
2196            .metadata(source)
2197            .await?
2198            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2199
2200        if metadata.is_dir {
2201            output.push((true, source.to_path_buf()));
2202            let mut children = fs.read_dir(source).await?;
2203            while let Some(child_path) = children.next().await {
2204                if let Ok(child_path) = child_path {
2205                    read_recursive(fs, &child_path, output).await?;
2206                }
2207            }
2208        } else {
2209            output.push((false, source.to_path_buf()));
2210        }
2211        Ok(())
2212    }
2213    .boxed()
2214}
2215
2216// todo(windows)
2217// can we get file id not open the file twice?
2218// https://github.com/rust-lang/rust/issues/63010
2219#[cfg(target_os = "windows")]
2220async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2221    use std::os::windows::io::AsRawHandle;
2222
2223    use smol::fs::windows::OpenOptionsExt;
2224    use windows::Win32::{
2225        Foundation::HANDLE,
2226        Storage::FileSystem::{
2227            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2228        },
2229    };
2230
2231    let file = smol::fs::OpenOptions::new()
2232        .read(true)
2233        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2234        .open(path)
2235        .await?;
2236
2237    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2238    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2239    // This function supports Windows XP+
2240    smol::unblock(move || {
2241        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2242
2243        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2244    })
2245    .await
2246}
2247
2248#[cfg(test)]
2249mod tests {
2250    use super::*;
2251    use gpui::BackgroundExecutor;
2252    use serde_json::json;
2253    use util::path;
2254
2255    #[gpui::test]
2256    async fn test_fake_fs(executor: BackgroundExecutor) {
2257        let fs = FakeFs::new(executor.clone());
2258        fs.insert_tree(
2259            path!("/root"),
2260            json!({
2261                "dir1": {
2262                    "a": "A",
2263                    "b": "B"
2264                },
2265                "dir2": {
2266                    "c": "C",
2267                    "dir3": {
2268                        "d": "D"
2269                    }
2270                }
2271            }),
2272        )
2273        .await;
2274
2275        assert_eq!(
2276            fs.files(),
2277            vec![
2278                PathBuf::from(path!("/root/dir1/a")),
2279                PathBuf::from(path!("/root/dir1/b")),
2280                PathBuf::from(path!("/root/dir2/c")),
2281                PathBuf::from(path!("/root/dir2/dir3/d")),
2282            ]
2283        );
2284
2285        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2286            .await
2287            .unwrap();
2288
2289        assert_eq!(
2290            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2291                .await
2292                .unwrap(),
2293            PathBuf::from(path!("/root/dir2/dir3")),
2294        );
2295        assert_eq!(
2296            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2297                .await
2298                .unwrap(),
2299            PathBuf::from(path!("/root/dir2/dir3/d")),
2300        );
2301        assert_eq!(
2302            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2303                .await
2304                .unwrap(),
2305            "D",
2306        );
2307    }
2308
2309    #[gpui::test]
2310    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2311        let fs = FakeFs::new(executor.clone());
2312        fs.insert_tree(
2313            path!("/outer"),
2314            json!({
2315                "a": "A",
2316                "b": "B",
2317                "inner": {}
2318            }),
2319        )
2320        .await;
2321
2322        assert_eq!(
2323            fs.files(),
2324            vec![
2325                PathBuf::from(path!("/outer/a")),
2326                PathBuf::from(path!("/outer/b")),
2327            ]
2328        );
2329
2330        let source = Path::new(path!("/outer/a"));
2331        let target = Path::new(path!("/outer/a copy"));
2332        copy_recursive(fs.as_ref(), source, target, Default::default())
2333            .await
2334            .unwrap();
2335
2336        assert_eq!(
2337            fs.files(),
2338            vec![
2339                PathBuf::from(path!("/outer/a")),
2340                PathBuf::from(path!("/outer/a copy")),
2341                PathBuf::from(path!("/outer/b")),
2342            ]
2343        );
2344
2345        let source = Path::new(path!("/outer/a"));
2346        let target = Path::new(path!("/outer/inner/a copy"));
2347        copy_recursive(fs.as_ref(), source, target, Default::default())
2348            .await
2349            .unwrap();
2350
2351        assert_eq!(
2352            fs.files(),
2353            vec![
2354                PathBuf::from(path!("/outer/a")),
2355                PathBuf::from(path!("/outer/a copy")),
2356                PathBuf::from(path!("/outer/b")),
2357                PathBuf::from(path!("/outer/inner/a copy")),
2358            ]
2359        );
2360    }
2361
2362    #[gpui::test]
2363    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2364        let fs = FakeFs::new(executor.clone());
2365        fs.insert_tree(
2366            path!("/outer"),
2367            json!({
2368                "a": "A",
2369                "empty": {},
2370                "non-empty": {
2371                    "b": "B",
2372                }
2373            }),
2374        )
2375        .await;
2376
2377        assert_eq!(
2378            fs.files(),
2379            vec![
2380                PathBuf::from(path!("/outer/a")),
2381                PathBuf::from(path!("/outer/non-empty/b")),
2382            ]
2383        );
2384        assert_eq!(
2385            fs.directories(false),
2386            vec![
2387                PathBuf::from(path!("/")),
2388                PathBuf::from(path!("/outer")),
2389                PathBuf::from(path!("/outer/empty")),
2390                PathBuf::from(path!("/outer/non-empty")),
2391            ]
2392        );
2393
2394        let source = Path::new(path!("/outer/empty"));
2395        let target = Path::new(path!("/outer/empty copy"));
2396        copy_recursive(fs.as_ref(), source, target, Default::default())
2397            .await
2398            .unwrap();
2399
2400        assert_eq!(
2401            fs.files(),
2402            vec![
2403                PathBuf::from(path!("/outer/a")),
2404                PathBuf::from(path!("/outer/non-empty/b")),
2405            ]
2406        );
2407        assert_eq!(
2408            fs.directories(false),
2409            vec![
2410                PathBuf::from(path!("/")),
2411                PathBuf::from(path!("/outer")),
2412                PathBuf::from(path!("/outer/empty")),
2413                PathBuf::from(path!("/outer/empty copy")),
2414                PathBuf::from(path!("/outer/non-empty")),
2415            ]
2416        );
2417
2418        let source = Path::new(path!("/outer/non-empty"));
2419        let target = Path::new(path!("/outer/non-empty copy"));
2420        copy_recursive(fs.as_ref(), source, target, Default::default())
2421            .await
2422            .unwrap();
2423
2424        assert_eq!(
2425            fs.files(),
2426            vec![
2427                PathBuf::from(path!("/outer/a")),
2428                PathBuf::from(path!("/outer/non-empty/b")),
2429                PathBuf::from(path!("/outer/non-empty copy/b")),
2430            ]
2431        );
2432        assert_eq!(
2433            fs.directories(false),
2434            vec![
2435                PathBuf::from(path!("/")),
2436                PathBuf::from(path!("/outer")),
2437                PathBuf::from(path!("/outer/empty")),
2438                PathBuf::from(path!("/outer/empty copy")),
2439                PathBuf::from(path!("/outer/non-empty")),
2440                PathBuf::from(path!("/outer/non-empty copy")),
2441            ]
2442        );
2443    }
2444
2445    #[gpui::test]
2446    async fn test_copy_recursive(executor: BackgroundExecutor) {
2447        let fs = FakeFs::new(executor.clone());
2448        fs.insert_tree(
2449            path!("/outer"),
2450            json!({
2451                "inner1": {
2452                    "a": "A",
2453                    "b": "B",
2454                    "inner3": {
2455                        "d": "D",
2456                    },
2457                    "inner4": {}
2458                },
2459                "inner2": {
2460                    "c": "C",
2461                }
2462            }),
2463        )
2464        .await;
2465
2466        assert_eq!(
2467            fs.files(),
2468            vec![
2469                PathBuf::from(path!("/outer/inner1/a")),
2470                PathBuf::from(path!("/outer/inner1/b")),
2471                PathBuf::from(path!("/outer/inner2/c")),
2472                PathBuf::from(path!("/outer/inner1/inner3/d")),
2473            ]
2474        );
2475        assert_eq!(
2476            fs.directories(false),
2477            vec![
2478                PathBuf::from(path!("/")),
2479                PathBuf::from(path!("/outer")),
2480                PathBuf::from(path!("/outer/inner1")),
2481                PathBuf::from(path!("/outer/inner2")),
2482                PathBuf::from(path!("/outer/inner1/inner3")),
2483                PathBuf::from(path!("/outer/inner1/inner4")),
2484            ]
2485        );
2486
2487        let source = Path::new(path!("/outer"));
2488        let target = Path::new(path!("/outer/inner1/outer"));
2489        copy_recursive(fs.as_ref(), source, target, Default::default())
2490            .await
2491            .unwrap();
2492
2493        assert_eq!(
2494            fs.files(),
2495            vec![
2496                PathBuf::from(path!("/outer/inner1/a")),
2497                PathBuf::from(path!("/outer/inner1/b")),
2498                PathBuf::from(path!("/outer/inner2/c")),
2499                PathBuf::from(path!("/outer/inner1/inner3/d")),
2500                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2501                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2502                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2503                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2504            ]
2505        );
2506        assert_eq!(
2507            fs.directories(false),
2508            vec![
2509                PathBuf::from(path!("/")),
2510                PathBuf::from(path!("/outer")),
2511                PathBuf::from(path!("/outer/inner1")),
2512                PathBuf::from(path!("/outer/inner2")),
2513                PathBuf::from(path!("/outer/inner1/inner3")),
2514                PathBuf::from(path!("/outer/inner1/inner4")),
2515                PathBuf::from(path!("/outer/inner1/outer")),
2516                PathBuf::from(path!("/outer/inner1/outer/inner1")),
2517                PathBuf::from(path!("/outer/inner1/outer/inner2")),
2518                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
2519                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
2520            ]
2521        );
2522    }
2523
2524    #[gpui::test]
2525    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2526        let fs = FakeFs::new(executor.clone());
2527        fs.insert_tree(
2528            path!("/outer"),
2529            json!({
2530                "inner1": {
2531                    "a": "A",
2532                    "b": "B",
2533                    "outer": {
2534                        "inner1": {
2535                            "a": "B"
2536                        }
2537                    }
2538                },
2539                "inner2": {
2540                    "c": "C",
2541                }
2542            }),
2543        )
2544        .await;
2545
2546        assert_eq!(
2547            fs.files(),
2548            vec![
2549                PathBuf::from(path!("/outer/inner1/a")),
2550                PathBuf::from(path!("/outer/inner1/b")),
2551                PathBuf::from(path!("/outer/inner2/c")),
2552                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2553            ]
2554        );
2555        assert_eq!(
2556            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2557                .await
2558                .unwrap(),
2559            "B",
2560        );
2561
2562        let source = Path::new(path!("/outer"));
2563        let target = Path::new(path!("/outer/inner1/outer"));
2564        copy_recursive(
2565            fs.as_ref(),
2566            source,
2567            target,
2568            CopyOptions {
2569                overwrite: true,
2570                ..Default::default()
2571            },
2572        )
2573        .await
2574        .unwrap();
2575
2576        assert_eq!(
2577            fs.files(),
2578            vec![
2579                PathBuf::from(path!("/outer/inner1/a")),
2580                PathBuf::from(path!("/outer/inner1/b")),
2581                PathBuf::from(path!("/outer/inner2/c")),
2582                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2583                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2584                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2585                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2586            ]
2587        );
2588        assert_eq!(
2589            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2590                .await
2591                .unwrap(),
2592            "A"
2593        );
2594    }
2595
2596    #[gpui::test]
2597    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
2598        let fs = FakeFs::new(executor.clone());
2599        fs.insert_tree(
2600            path!("/outer"),
2601            json!({
2602                "inner1": {
2603                    "a": "A",
2604                    "b": "B",
2605                    "outer": {
2606                        "inner1": {
2607                            "a": "B"
2608                        }
2609                    }
2610                },
2611                "inner2": {
2612                    "c": "C",
2613                }
2614            }),
2615        )
2616        .await;
2617
2618        assert_eq!(
2619            fs.files(),
2620            vec![
2621                PathBuf::from(path!("/outer/inner1/a")),
2622                PathBuf::from(path!("/outer/inner1/b")),
2623                PathBuf::from(path!("/outer/inner2/c")),
2624                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2625            ]
2626        );
2627        assert_eq!(
2628            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2629                .await
2630                .unwrap(),
2631            "B",
2632        );
2633
2634        let source = Path::new(path!("/outer"));
2635        let target = Path::new(path!("/outer/inner1/outer"));
2636        copy_recursive(
2637            fs.as_ref(),
2638            source,
2639            target,
2640            CopyOptions {
2641                ignore_if_exists: true,
2642                ..Default::default()
2643            },
2644        )
2645        .await
2646        .unwrap();
2647
2648        assert_eq!(
2649            fs.files(),
2650            vec![
2651                PathBuf::from(path!("/outer/inner1/a")),
2652                PathBuf::from(path!("/outer/inner1/b")),
2653                PathBuf::from(path!("/outer/inner2/c")),
2654                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2655                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2656                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2657                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2658            ]
2659        );
2660        assert_eq!(
2661            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2662                .await
2663                .unwrap(),
2664            "B"
2665        );
2666    }
2667}