fs.rs

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