fs.rs

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