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