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 = new_smol_command("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() {
 723                    io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => Ok(None),
 724                    _ => Err(anyhow::Error::new(err)),
 725                };
 726            }
 727        };
 728
 729        let is_symlink = symlink_metadata.file_type().is_symlink();
 730        let metadata = if is_symlink {
 731            let path_buf = path.to_path_buf();
 732            let path_exists = self
 733                .executor
 734                .spawn(async move {
 735                    path_buf
 736                        .try_exists()
 737                        .with_context(|| format!("checking existence for path {path_buf:?}"))
 738                })
 739                .await?;
 740            if path_exists {
 741                let path_buf = path.to_path_buf();
 742                self.executor
 743                    .spawn(async move { std::fs::metadata(path_buf) })
 744                    .await
 745                    .with_context(|| "accessing symlink for path {path}")?
 746            } else {
 747                symlink_metadata
 748            }
 749        } else {
 750            symlink_metadata
 751        };
 752
 753        #[cfg(unix)]
 754        let inode = metadata.ino();
 755
 756        #[cfg(windows)]
 757        let inode = file_id(path).await?;
 758
 759        #[cfg(windows)]
 760        let is_fifo = false;
 761
 762        #[cfg(unix)]
 763        let is_fifo = metadata.file_type().is_fifo();
 764
 765        Ok(Some(Metadata {
 766            inode,
 767            mtime: MTime(metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH)),
 768            len: metadata.len(),
 769            is_symlink,
 770            is_dir: metadata.file_type().is_dir(),
 771            is_fifo,
 772        }))
 773    }
 774
 775    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 776        let path = path.to_owned();
 777        let path = self
 778            .executor
 779            .spawn(async move { std::fs::read_link(&path) })
 780            .await?;
 781        Ok(path)
 782    }
 783
 784    async fn read_dir(
 785        &self,
 786        path: &Path,
 787    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 788        let path = path.to_owned();
 789        let result = iter(
 790            self.executor
 791                .spawn(async move { std::fs::read_dir(path) })
 792                .await?,
 793        )
 794        .map(|entry| match entry {
 795            Ok(entry) => Ok(entry.path()),
 796            Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
 797        });
 798        Ok(Box::pin(result))
 799    }
 800
 801    #[cfg(target_os = "macos")]
 802    async fn watch(
 803        &self,
 804        path: &Path,
 805        latency: Duration,
 806    ) -> (
 807        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 808        Arc<dyn Watcher>,
 809    ) {
 810        use fsevent::StreamFlags;
 811
 812        let (events_tx, events_rx) = smol::channel::unbounded();
 813        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 814        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 815            events_tx,
 816            Arc::downgrade(&handles),
 817            latency,
 818        ));
 819        watcher.add(path).expect("handles can't be dropped");
 820
 821        (
 822            Box::pin(
 823                events_rx
 824                    .map(|events| {
 825                        events
 826                            .into_iter()
 827                            .map(|event| {
 828                                log::trace!("fs path event: {event:?}");
 829                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 830                                    Some(PathEventKind::Removed)
 831                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 832                                    Some(PathEventKind::Created)
 833                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED)
 834                                    | event.flags.contains(StreamFlags::ITEM_RENAMED)
 835                                {
 836                                    Some(PathEventKind::Changed)
 837                                } else {
 838                                    None
 839                                };
 840                                PathEvent {
 841                                    path: event.path,
 842                                    kind,
 843                                }
 844                            })
 845                            .collect()
 846                    })
 847                    .chain(futures::stream::once(async move {
 848                        drop(handles);
 849                        vec![]
 850                    })),
 851            ),
 852            watcher,
 853        )
 854    }
 855
 856    #[cfg(not(target_os = "macos"))]
 857    async fn watch(
 858        &self,
 859        path: &Path,
 860        latency: Duration,
 861    ) -> (
 862        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 863        Arc<dyn Watcher>,
 864    ) {
 865        use parking_lot::Mutex;
 866        use util::{ResultExt as _, paths::SanitizedPath};
 867
 868        let (tx, rx) = smol::channel::unbounded();
 869        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 870        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 871
 872        // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 873        if let Err(e) = watcher.add(path)
 874            && let Some(parent) = path.parent()
 875            && let Err(parent_e) = watcher.add(parent)
 876        {
 877            log::warn!(
 878                "Failed to watch {} and its parent directory {}:\n{e}\n{parent_e}",
 879                path.display(),
 880                parent.display()
 881            );
 882        }
 883
 884        // Check if path is a symlink and follow the target parent
 885        if let Some(mut target) = self.read_link(path).await.ok() {
 886            log::trace!("watch symlink {path:?} -> {target:?}");
 887            // Check if symlink target is relative path, if so make it absolute
 888            if target.is_relative()
 889                && let Some(parent) = path.parent()
 890            {
 891                target = parent.join(target);
 892                if let Ok(canonical) = self.canonicalize(&target).await {
 893                    target = SanitizedPath::new(&canonical).as_path().to_path_buf();
 894                }
 895            }
 896            watcher.add(&target).ok();
 897            if let Some(parent) = target.parent() {
 898                watcher.add(parent).log_err();
 899            }
 900        }
 901
 902        (
 903            Box::pin(rx.filter_map({
 904                let watcher = watcher.clone();
 905                move |_| {
 906                    let _ = watcher.clone();
 907                    let pending_paths = pending_paths.clone();
 908                    async move {
 909                        smol::Timer::after(latency).await;
 910                        let paths = std::mem::take(&mut *pending_paths.lock());
 911                        (!paths.is_empty()).then_some(paths)
 912                    }
 913                }
 914            })),
 915            watcher,
 916        )
 917    }
 918
 919    fn open_repo(
 920        &self,
 921        dotgit_path: &Path,
 922        system_git_binary_path: Option<&Path>,
 923    ) -> Option<Arc<dyn GitRepository>> {
 924        Some(Arc::new(RealGitRepository::new(
 925            dotgit_path,
 926            self.bundled_git_binary_path.clone(),
 927            system_git_binary_path.map(|path| path.to_path_buf()),
 928            self.executor.clone(),
 929        )?))
 930    }
 931
 932    async fn git_init(
 933        &self,
 934        abs_work_directory_path: &Path,
 935        fallback_branch_name: String,
 936    ) -> Result<()> {
 937        let config = new_smol_command("git")
 938            .current_dir(abs_work_directory_path)
 939            .args(&["config", "--global", "--get", "init.defaultBranch"])
 940            .output()
 941            .await?;
 942
 943        let branch_name;
 944
 945        if config.status.success() && !config.stdout.is_empty() {
 946            branch_name = String::from_utf8_lossy(&config.stdout);
 947        } else {
 948            branch_name = Cow::Borrowed(fallback_branch_name.as_str());
 949        }
 950
 951        new_smol_command("git")
 952            .current_dir(abs_work_directory_path)
 953            .args(&["init", "-b"])
 954            .arg(branch_name.trim())
 955            .output()
 956            .await?;
 957
 958        Ok(())
 959    }
 960
 961    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
 962        let output = new_smol_command("git")
 963            .current_dir(abs_work_directory)
 964            .args(&["clone", repo_url])
 965            .output()
 966            .await?;
 967
 968        if !output.status.success() {
 969            anyhow::bail!(
 970                "git clone failed: {}",
 971                String::from_utf8_lossy(&output.stderr)
 972            );
 973        }
 974
 975        Ok(())
 976    }
 977
 978    fn is_fake(&self) -> bool {
 979        false
 980    }
 981
 982    /// Checks whether the file system is case sensitive by attempting to create two files
 983    /// that have the same name except for the casing.
 984    ///
 985    /// It creates both files in a temporary directory it removes at the end.
 986    async fn is_case_sensitive(&self) -> Result<bool> {
 987        let temp_dir = TempDir::new()?;
 988        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 989        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 990
 991        let create_opts = CreateOptions {
 992            overwrite: false,
 993            ignore_if_exists: false,
 994        };
 995
 996        // Create file1
 997        self.create_file(&test_file_1, create_opts).await?;
 998
 999        // Now check whether it's possible to create file2
1000        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
1001            Ok(_) => Ok(true),
1002            Err(e) => {
1003                if let Some(io_error) = e.downcast_ref::<io::Error>() {
1004                    if io_error.kind() == io::ErrorKind::AlreadyExists {
1005                        Ok(false)
1006                    } else {
1007                        Err(e)
1008                    }
1009                } else {
1010                    Err(e)
1011                }
1012            }
1013        };
1014
1015        temp_dir.close()?;
1016        case_sensitive
1017    }
1018}
1019
1020#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
1021impl Watcher for RealWatcher {
1022    fn add(&self, _: &Path) -> Result<()> {
1023        Ok(())
1024    }
1025
1026    fn remove(&self, _: &Path) -> Result<()> {
1027        Ok(())
1028    }
1029}
1030
1031#[cfg(any(test, feature = "test-support"))]
1032pub struct FakeFs {
1033    this: std::sync::Weak<Self>,
1034    // Use an unfair lock to ensure tests are deterministic.
1035    state: Arc<Mutex<FakeFsState>>,
1036    executor: gpui::BackgroundExecutor,
1037}
1038
1039#[cfg(any(test, feature = "test-support"))]
1040struct FakeFsState {
1041    root: FakeFsEntry,
1042    next_inode: u64,
1043    next_mtime: SystemTime,
1044    git_event_tx: smol::channel::Sender<PathBuf>,
1045    event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
1046    events_paused: bool,
1047    buffered_events: Vec<PathEvent>,
1048    metadata_call_count: usize,
1049    read_dir_call_count: usize,
1050    path_write_counts: std::collections::HashMap<PathBuf, usize>,
1051    moves: std::collections::HashMap<u64, PathBuf>,
1052}
1053
1054#[cfg(any(test, feature = "test-support"))]
1055#[derive(Clone, Debug)]
1056enum FakeFsEntry {
1057    File {
1058        inode: u64,
1059        mtime: MTime,
1060        len: u64,
1061        content: Vec<u8>,
1062        // The path to the repository state directory, if this is a gitfile.
1063        git_dir_path: Option<PathBuf>,
1064    },
1065    Dir {
1066        inode: u64,
1067        mtime: MTime,
1068        len: u64,
1069        entries: BTreeMap<String, FakeFsEntry>,
1070        git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
1071    },
1072    Symlink {
1073        target: PathBuf,
1074    },
1075}
1076
1077#[cfg(any(test, feature = "test-support"))]
1078impl PartialEq for FakeFsEntry {
1079    fn eq(&self, other: &Self) -> bool {
1080        match (self, other) {
1081            (
1082                Self::File {
1083                    inode: l_inode,
1084                    mtime: l_mtime,
1085                    len: l_len,
1086                    content: l_content,
1087                    git_dir_path: l_git_dir_path,
1088                },
1089                Self::File {
1090                    inode: r_inode,
1091                    mtime: r_mtime,
1092                    len: r_len,
1093                    content: r_content,
1094                    git_dir_path: r_git_dir_path,
1095                },
1096            ) => {
1097                l_inode == r_inode
1098                    && l_mtime == r_mtime
1099                    && l_len == r_len
1100                    && l_content == r_content
1101                    && l_git_dir_path == r_git_dir_path
1102            }
1103            (
1104                Self::Dir {
1105                    inode: l_inode,
1106                    mtime: l_mtime,
1107                    len: l_len,
1108                    entries: l_entries,
1109                    git_repo_state: l_git_repo_state,
1110                },
1111                Self::Dir {
1112                    inode: r_inode,
1113                    mtime: r_mtime,
1114                    len: r_len,
1115                    entries: r_entries,
1116                    git_repo_state: r_git_repo_state,
1117                },
1118            ) => {
1119                let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1120                    (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1121                    (None, None) => true,
1122                    _ => false,
1123                };
1124                l_inode == r_inode
1125                    && l_mtime == r_mtime
1126                    && l_len == r_len
1127                    && l_entries == r_entries
1128                    && same_repo_state
1129            }
1130            (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1131                l_target == r_target
1132            }
1133            _ => false,
1134        }
1135    }
1136}
1137
1138#[cfg(any(test, feature = "test-support"))]
1139impl FakeFsState {
1140    fn get_and_increment_mtime(&mut self) -> MTime {
1141        let mtime = self.next_mtime;
1142        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1143        MTime(mtime)
1144    }
1145
1146    fn get_and_increment_inode(&mut self) -> u64 {
1147        let inode = self.next_inode;
1148        self.next_inode += 1;
1149        inode
1150    }
1151
1152    fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1153        let mut canonical_path = PathBuf::new();
1154        let mut path = target.to_path_buf();
1155        let mut entry_stack = Vec::new();
1156        'outer: loop {
1157            let mut path_components = path.components().peekable();
1158            let mut prefix = None;
1159            while let Some(component) = path_components.next() {
1160                match component {
1161                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1162                    Component::RootDir => {
1163                        entry_stack.clear();
1164                        entry_stack.push(&self.root);
1165                        canonical_path.clear();
1166                        match prefix {
1167                            Some(prefix_component) => {
1168                                canonical_path = PathBuf::from(prefix_component.as_os_str());
1169                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1170                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1171                            }
1172                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1173                        }
1174                    }
1175                    Component::CurDir => {}
1176                    Component::ParentDir => {
1177                        entry_stack.pop()?;
1178                        canonical_path.pop();
1179                    }
1180                    Component::Normal(name) => {
1181                        let current_entry = *entry_stack.last()?;
1182                        if let FakeFsEntry::Dir { entries, .. } = current_entry {
1183                            let entry = entries.get(name.to_str().unwrap())?;
1184                            if (path_components.peek().is_some() || follow_symlink)
1185                                && let FakeFsEntry::Symlink { target, .. } = entry
1186                            {
1187                                let mut target = target.clone();
1188                                target.extend(path_components);
1189                                path = target;
1190                                continue 'outer;
1191                            }
1192                            entry_stack.push(entry);
1193                            canonical_path = canonical_path.join(name);
1194                        } else {
1195                            return None;
1196                        }
1197                    }
1198                }
1199            }
1200            break;
1201        }
1202
1203        if entry_stack.is_empty() {
1204            None
1205        } else {
1206            Some(canonical_path)
1207        }
1208    }
1209
1210    fn try_entry(
1211        &mut self,
1212        target: &Path,
1213        follow_symlink: bool,
1214    ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1215        let canonical_path = self.canonicalize(target, follow_symlink)?;
1216
1217        let mut components = canonical_path
1218            .components()
1219            .skip_while(|component| matches!(component, Component::Prefix(_)));
1220        let Some(Component::RootDir) = components.next() else {
1221            panic!(
1222                "the path {:?} was not canonicalized properly {:?}",
1223                target, canonical_path
1224            )
1225        };
1226
1227        let mut entry = &mut self.root;
1228        for component in components {
1229            match component {
1230                Component::Normal(name) => {
1231                    if let FakeFsEntry::Dir { entries, .. } = entry {
1232                        entry = entries.get_mut(name.to_str().unwrap())?;
1233                    } else {
1234                        return None;
1235                    }
1236                }
1237                _ => {
1238                    panic!(
1239                        "the path {:?} was not canonicalized properly {:?}",
1240                        target, canonical_path
1241                    )
1242                }
1243            }
1244        }
1245
1246        Some((entry, canonical_path))
1247    }
1248
1249    fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1250        Ok(self
1251            .try_entry(target, true)
1252            .ok_or_else(|| {
1253                anyhow!(io::Error::new(
1254                    io::ErrorKind::NotFound,
1255                    format!("not found: {target:?}")
1256                ))
1257            })?
1258            .0)
1259    }
1260
1261    fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1262    where
1263        Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1264    {
1265        let path = normalize_path(path);
1266        let filename = path.file_name().context("cannot overwrite the root")?;
1267        let parent_path = path.parent().unwrap();
1268
1269        let parent = self.entry(parent_path)?;
1270        let new_entry = parent
1271            .dir_entries(parent_path)?
1272            .entry(filename.to_str().unwrap().into());
1273        callback(new_entry)
1274    }
1275
1276    fn emit_event<I, T>(&mut self, paths: I)
1277    where
1278        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1279        T: Into<PathBuf>,
1280    {
1281        self.buffered_events
1282            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1283                path: path.into(),
1284                kind,
1285            }));
1286
1287        if !self.events_paused {
1288            self.flush_events(self.buffered_events.len());
1289        }
1290    }
1291
1292    fn flush_events(&mut self, mut count: usize) {
1293        count = count.min(self.buffered_events.len());
1294        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1295        self.event_txs.retain(|(_, tx)| {
1296            let _ = tx.try_send(events.clone());
1297            !tx.is_closed()
1298        });
1299    }
1300}
1301
1302#[cfg(any(test, feature = "test-support"))]
1303pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1304    std::sync::LazyLock::new(|| OsStr::new(".git"));
1305
1306#[cfg(any(test, feature = "test-support"))]
1307impl FakeFs {
1308    /// We need to use something large enough for Windows and Unix to consider this a new file.
1309    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1310    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1311
1312    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1313        let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1314
1315        let this = Arc::new_cyclic(|this| Self {
1316            this: this.clone(),
1317            executor: executor.clone(),
1318            state: Arc::new(Mutex::new(FakeFsState {
1319                root: FakeFsEntry::Dir {
1320                    inode: 0,
1321                    mtime: MTime(UNIX_EPOCH),
1322                    len: 0,
1323                    entries: Default::default(),
1324                    git_repo_state: None,
1325                },
1326                git_event_tx: tx,
1327                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1328                next_inode: 1,
1329                event_txs: Default::default(),
1330                buffered_events: Vec::new(),
1331                events_paused: false,
1332                read_dir_call_count: 0,
1333                metadata_call_count: 0,
1334                path_write_counts: Default::default(),
1335                moves: Default::default(),
1336            })),
1337        });
1338
1339        executor.spawn({
1340            let this = this.clone();
1341            async move {
1342                while let Ok(git_event) = rx.recv().await {
1343                    if let Some(mut state) = this.state.try_lock() {
1344                        state.emit_event([(git_event, Some(PathEventKind::Changed))]);
1345                    } else {
1346                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1347                    }
1348                }
1349            }
1350        }).detach();
1351
1352        this
1353    }
1354
1355    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1356        let mut state = self.state.lock();
1357        state.next_mtime = next_mtime;
1358    }
1359
1360    pub fn get_and_increment_mtime(&self) -> MTime {
1361        let mut state = self.state.lock();
1362        state.get_and_increment_mtime()
1363    }
1364
1365    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1366        let mut state = self.state.lock();
1367        let path = path.as_ref();
1368        let new_mtime = state.get_and_increment_mtime();
1369        let new_inode = state.get_and_increment_inode();
1370        state
1371            .write_path(path, move |entry| {
1372                match entry {
1373                    btree_map::Entry::Vacant(e) => {
1374                        e.insert(FakeFsEntry::File {
1375                            inode: new_inode,
1376                            mtime: new_mtime,
1377                            content: Vec::new(),
1378                            len: 0,
1379                            git_dir_path: None,
1380                        });
1381                    }
1382                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1383                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1384                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1385                        FakeFsEntry::Symlink { .. } => {}
1386                    },
1387                }
1388                Ok(())
1389            })
1390            .unwrap();
1391        state.emit_event([(path.to_path_buf(), Some(PathEventKind::Changed))]);
1392    }
1393
1394    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1395        self.write_file_internal(path, content, true).unwrap()
1396    }
1397
1398    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1399        let mut state = self.state.lock();
1400        let path = path.as_ref();
1401        let file = FakeFsEntry::Symlink { target };
1402        state
1403            .write_path(path.as_ref(), move |e| match e {
1404                btree_map::Entry::Vacant(e) => {
1405                    e.insert(file);
1406                    Ok(())
1407                }
1408                btree_map::Entry::Occupied(mut e) => {
1409                    *e.get_mut() = file;
1410                    Ok(())
1411                }
1412            })
1413            .unwrap();
1414        state.emit_event([(path, Some(PathEventKind::Created))]);
1415    }
1416
1417    fn write_file_internal(
1418        &self,
1419        path: impl AsRef<Path>,
1420        new_content: Vec<u8>,
1421        recreate_inode: bool,
1422    ) -> Result<()> {
1423        let mut state = self.state.lock();
1424        let path_buf = path.as_ref().to_path_buf();
1425        *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1426        let new_inode = state.get_and_increment_inode();
1427        let new_mtime = state.get_and_increment_mtime();
1428        let new_len = new_content.len() as u64;
1429        let mut kind = None;
1430        state.write_path(path.as_ref(), |entry| {
1431            match entry {
1432                btree_map::Entry::Vacant(e) => {
1433                    kind = Some(PathEventKind::Created);
1434                    e.insert(FakeFsEntry::File {
1435                        inode: new_inode,
1436                        mtime: new_mtime,
1437                        len: new_len,
1438                        content: new_content,
1439                        git_dir_path: None,
1440                    });
1441                }
1442                btree_map::Entry::Occupied(mut e) => {
1443                    kind = Some(PathEventKind::Changed);
1444                    if let FakeFsEntry::File {
1445                        inode,
1446                        mtime,
1447                        len,
1448                        content,
1449                        ..
1450                    } = e.get_mut()
1451                    {
1452                        *mtime = new_mtime;
1453                        *content = new_content;
1454                        *len = new_len;
1455                        if recreate_inode {
1456                            *inode = new_inode;
1457                        }
1458                    } else {
1459                        anyhow::bail!("not a file")
1460                    }
1461                }
1462            }
1463            Ok(())
1464        })?;
1465        state.emit_event([(path.as_ref(), kind)]);
1466        Ok(())
1467    }
1468
1469    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1470        let path = path.as_ref();
1471        let path = normalize_path(path);
1472        let mut state = self.state.lock();
1473        let entry = state.entry(&path)?;
1474        entry.file_content(&path).cloned()
1475    }
1476
1477    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1478        let path = path.as_ref();
1479        let path = normalize_path(path);
1480        self.simulate_random_delay().await;
1481        let mut state = self.state.lock();
1482        let entry = state.entry(&path)?;
1483        entry.file_content(&path).cloned()
1484    }
1485
1486    pub fn pause_events(&self) {
1487        self.state.lock().events_paused = true;
1488    }
1489
1490    pub fn unpause_events_and_flush(&self) {
1491        self.state.lock().events_paused = false;
1492        self.flush_events(usize::MAX);
1493    }
1494
1495    pub fn buffered_event_count(&self) -> usize {
1496        self.state.lock().buffered_events.len()
1497    }
1498
1499    pub fn flush_events(&self, count: usize) {
1500        self.state.lock().flush_events(count);
1501    }
1502
1503    pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1504        self.state.lock().entry(target).cloned()
1505    }
1506
1507    pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1508        let mut state = self.state.lock();
1509        state.write_path(target, |entry| {
1510            match entry {
1511                btree_map::Entry::Vacant(vacant_entry) => {
1512                    vacant_entry.insert(new_entry);
1513                }
1514                btree_map::Entry::Occupied(mut occupied_entry) => {
1515                    occupied_entry.insert(new_entry);
1516                }
1517            }
1518            Ok(())
1519        })
1520    }
1521
1522    #[must_use]
1523    pub fn insert_tree<'a>(
1524        &'a self,
1525        path: impl 'a + AsRef<Path> + Send,
1526        tree: serde_json::Value,
1527    ) -> futures::future::BoxFuture<'a, ()> {
1528        use futures::FutureExt as _;
1529        use serde_json::Value::*;
1530
1531        async move {
1532            let path = path.as_ref();
1533
1534            match tree {
1535                Object(map) => {
1536                    self.create_dir(path).await.unwrap();
1537                    for (name, contents) in map {
1538                        let mut path = PathBuf::from(path);
1539                        path.push(name);
1540                        self.insert_tree(&path, contents).await;
1541                    }
1542                }
1543                Null => {
1544                    self.create_dir(path).await.unwrap();
1545                }
1546                String(contents) => {
1547                    self.insert_file(&path, contents.into_bytes()).await;
1548                }
1549                _ => {
1550                    panic!("JSON object must contain only objects, strings, or null");
1551                }
1552            }
1553        }
1554        .boxed()
1555    }
1556
1557    pub fn insert_tree_from_real_fs<'a>(
1558        &'a self,
1559        path: impl 'a + AsRef<Path> + Send,
1560        src_path: impl 'a + AsRef<Path> + Send,
1561    ) -> futures::future::BoxFuture<'a, ()> {
1562        use futures::FutureExt as _;
1563
1564        async move {
1565            let path = path.as_ref();
1566            if std::fs::metadata(&src_path).unwrap().is_file() {
1567                let contents = std::fs::read(src_path).unwrap();
1568                self.insert_file(path, contents).await;
1569            } else {
1570                self.create_dir(path).await.unwrap();
1571                for entry in std::fs::read_dir(&src_path).unwrap() {
1572                    let entry = entry.unwrap();
1573                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1574                        .await;
1575                }
1576            }
1577        }
1578        .boxed()
1579    }
1580
1581    pub fn with_git_state_and_paths<T, F>(
1582        &self,
1583        dot_git: &Path,
1584        emit_git_event: bool,
1585        f: F,
1586    ) -> Result<T>
1587    where
1588        F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1589    {
1590        let mut state = self.state.lock();
1591        let git_event_tx = state.git_event_tx.clone();
1592        let entry = state.entry(dot_git).context("open .git")?;
1593
1594        if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1595            let repo_state = git_repo_state.get_or_insert_with(|| {
1596                log::debug!("insert git state for {dot_git:?}");
1597                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1598            });
1599            let mut repo_state = repo_state.lock();
1600
1601            let result = f(&mut repo_state, dot_git, dot_git);
1602
1603            drop(repo_state);
1604            if emit_git_event {
1605                state.emit_event([(dot_git, Some(PathEventKind::Changed))]);
1606            }
1607
1608            Ok(result)
1609        } else if let FakeFsEntry::File {
1610            content,
1611            git_dir_path,
1612            ..
1613        } = &mut *entry
1614        {
1615            let path = match git_dir_path {
1616                Some(path) => path,
1617                None => {
1618                    let path = std::str::from_utf8(content)
1619                        .ok()
1620                        .and_then(|content| content.strip_prefix("gitdir:"))
1621                        .context("not a valid gitfile")?
1622                        .trim();
1623                    git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1624                }
1625            }
1626            .clone();
1627            let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1628                anyhow::bail!("pointed-to git dir {path:?} not found")
1629            };
1630            let FakeFsEntry::Dir {
1631                git_repo_state,
1632                entries,
1633                ..
1634            } = git_dir_entry
1635            else {
1636                anyhow::bail!("gitfile points to a non-directory")
1637            };
1638            let common_dir = if let Some(child) = entries.get("commondir") {
1639                Path::new(
1640                    std::str::from_utf8(child.file_content("commondir".as_ref())?)
1641                        .context("commondir content")?,
1642                )
1643                .to_owned()
1644            } else {
1645                canonical_path.clone()
1646            };
1647            let repo_state = git_repo_state.get_or_insert_with(|| {
1648                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1649            });
1650            let mut repo_state = repo_state.lock();
1651
1652            let result = f(&mut repo_state, &canonical_path, &common_dir);
1653
1654            if emit_git_event {
1655                drop(repo_state);
1656                state.emit_event([(canonical_path, Some(PathEventKind::Changed))]);
1657            }
1658
1659            Ok(result)
1660        } else {
1661            anyhow::bail!("not a valid git repository");
1662        }
1663    }
1664
1665    pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1666    where
1667        F: FnOnce(&mut FakeGitRepositoryState) -> T,
1668    {
1669        self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1670    }
1671
1672    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1673        self.with_git_state(dot_git, true, |state| {
1674            let branch = branch.map(Into::into);
1675            state.branches.extend(branch.clone());
1676            state.current_branch_name = branch
1677        })
1678        .unwrap();
1679    }
1680
1681    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1682        self.with_git_state(dot_git, true, |state| {
1683            if let Some(first) = branches.first()
1684                && state.current_branch_name.is_none()
1685            {
1686                state.current_branch_name = Some(first.to_string())
1687            }
1688            state
1689                .branches
1690                .extend(branches.iter().map(ToString::to_string));
1691        })
1692        .unwrap();
1693    }
1694
1695    pub fn set_unmerged_paths_for_repo(
1696        &self,
1697        dot_git: &Path,
1698        unmerged_state: &[(RepoPath, UnmergedStatus)],
1699    ) {
1700        self.with_git_state(dot_git, true, |state| {
1701            state.unmerged_paths.clear();
1702            state.unmerged_paths.extend(
1703                unmerged_state
1704                    .iter()
1705                    .map(|(path, content)| (path.clone(), *content)),
1706            );
1707        })
1708        .unwrap();
1709    }
1710
1711    pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(&str, String)]) {
1712        self.with_git_state(dot_git, true, |state| {
1713            state.index_contents.clear();
1714            state.index_contents.extend(
1715                index_state
1716                    .iter()
1717                    .map(|(path, content)| (repo_path(path), content.clone())),
1718            );
1719        })
1720        .unwrap();
1721    }
1722
1723    pub fn set_head_for_repo(
1724        &self,
1725        dot_git: &Path,
1726        head_state: &[(&str, String)],
1727        sha: impl Into<String>,
1728    ) {
1729        self.with_git_state(dot_git, true, |state| {
1730            state.head_contents.clear();
1731            state.head_contents.extend(
1732                head_state
1733                    .iter()
1734                    .map(|(path, content)| (repo_path(path), content.clone())),
1735            );
1736            state.refs.insert("HEAD".into(), sha.into());
1737        })
1738        .unwrap();
1739    }
1740
1741    pub fn set_head_and_index_for_repo(&self, dot_git: &Path, contents_by_path: &[(&str, String)]) {
1742        self.with_git_state(dot_git, true, |state| {
1743            state.head_contents.clear();
1744            state.head_contents.extend(
1745                contents_by_path
1746                    .iter()
1747                    .map(|(path, contents)| (repo_path(path), contents.clone())),
1748            );
1749            state.index_contents = state.head_contents.clone();
1750        })
1751        .unwrap();
1752    }
1753
1754    pub fn set_merge_base_content_for_repo(
1755        &self,
1756        dot_git: &Path,
1757        contents_by_path: &[(&str, String)],
1758    ) {
1759        self.with_git_state(dot_git, true, |state| {
1760            use git::Oid;
1761
1762            state.merge_base_contents.clear();
1763            let oids = (1..)
1764                .map(|n| n.to_string())
1765                .map(|n| Oid::from_bytes(n.repeat(20).as_bytes()).unwrap());
1766            for ((path, content), oid) in contents_by_path.iter().zip(oids) {
1767                state.merge_base_contents.insert(repo_path(path), oid);
1768                state.oids.insert(oid, content.clone());
1769            }
1770        })
1771        .unwrap();
1772    }
1773
1774    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1775        self.with_git_state(dot_git, true, |state| {
1776            state.blames.clear();
1777            state.blames.extend(blames);
1778        })
1779        .unwrap();
1780    }
1781
1782    /// Put the given git repository into a state with the given status,
1783    /// by mutating the head, index, and unmerged state.
1784    pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&str, FileStatus)]) {
1785        let workdir_path = dot_git.parent().unwrap();
1786        let workdir_contents = self.files_with_contents(workdir_path);
1787        self.with_git_state(dot_git, true, |state| {
1788            state.index_contents.clear();
1789            state.head_contents.clear();
1790            state.unmerged_paths.clear();
1791            for (path, content) in workdir_contents {
1792                use util::{paths::PathStyle, rel_path::RelPath};
1793
1794                let repo_path = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap();
1795                let repo_path = RepoPath::from_rel_path(&repo_path);
1796                let status = statuses
1797                    .iter()
1798                    .find_map(|(p, status)| (*p == repo_path.as_unix_str()).then_some(status));
1799                let mut content = String::from_utf8_lossy(&content).to_string();
1800
1801                let mut index_content = None;
1802                let mut head_content = None;
1803                match status {
1804                    None => {
1805                        index_content = Some(content.clone());
1806                        head_content = Some(content);
1807                    }
1808                    Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1809                    Some(FileStatus::Unmerged(unmerged_status)) => {
1810                        state
1811                            .unmerged_paths
1812                            .insert(repo_path.clone(), *unmerged_status);
1813                        content.push_str(" (unmerged)");
1814                        index_content = Some(content.clone());
1815                        head_content = Some(content);
1816                    }
1817                    Some(FileStatus::Tracked(TrackedStatus {
1818                        index_status,
1819                        worktree_status,
1820                    })) => {
1821                        match worktree_status {
1822                            StatusCode::Modified => {
1823                                let mut content = content.clone();
1824                                content.push_str(" (modified in working copy)");
1825                                index_content = Some(content);
1826                            }
1827                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1828                                index_content = Some(content.clone());
1829                            }
1830                            StatusCode::Added => {}
1831                            StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1832                                panic!("cannot create these statuses for an existing file");
1833                            }
1834                        };
1835                        match index_status {
1836                            StatusCode::Modified => {
1837                                let mut content = index_content.clone().expect(
1838                                    "file cannot be both modified in index and created in working copy",
1839                                );
1840                                content.push_str(" (modified in index)");
1841                                head_content = Some(content);
1842                            }
1843                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1844                                head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1845                            }
1846                            StatusCode::Added => {}
1847                            StatusCode::Deleted  => {
1848                                head_content = Some("".into());
1849                            }
1850                            StatusCode::Renamed | StatusCode::Copied => {
1851                                panic!("cannot create these statuses for an existing file");
1852                            }
1853                        };
1854                    }
1855                };
1856
1857                if let Some(content) = index_content {
1858                    state.index_contents.insert(repo_path.clone(), content);
1859                }
1860                if let Some(content) = head_content {
1861                    state.head_contents.insert(repo_path.clone(), content);
1862                }
1863            }
1864        }).unwrap();
1865    }
1866
1867    pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1868        self.with_git_state(dot_git, true, |state| {
1869            state.simulated_index_write_error_message = message;
1870        })
1871        .unwrap();
1872    }
1873
1874    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1875        let mut result = Vec::new();
1876        let mut queue = collections::VecDeque::new();
1877        let state = &*self.state.lock();
1878        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1879        while let Some((path, entry)) = queue.pop_front() {
1880            if let FakeFsEntry::Dir { entries, .. } = entry {
1881                for (name, entry) in entries {
1882                    queue.push_back((path.join(name), entry));
1883                }
1884            }
1885            if include_dot_git
1886                || !path
1887                    .components()
1888                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1889            {
1890                result.push(path);
1891            }
1892        }
1893        result
1894    }
1895
1896    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1897        let mut result = Vec::new();
1898        let mut queue = collections::VecDeque::new();
1899        let state = &*self.state.lock();
1900        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1901        while let Some((path, entry)) = queue.pop_front() {
1902            if let FakeFsEntry::Dir { entries, .. } = entry {
1903                for (name, entry) in entries {
1904                    queue.push_back((path.join(name), entry));
1905                }
1906                if include_dot_git
1907                    || !path
1908                        .components()
1909                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1910                {
1911                    result.push(path);
1912                }
1913            }
1914        }
1915        result
1916    }
1917
1918    pub fn files(&self) -> Vec<PathBuf> {
1919        let mut result = Vec::new();
1920        let mut queue = collections::VecDeque::new();
1921        let state = &*self.state.lock();
1922        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1923        while let Some((path, entry)) = queue.pop_front() {
1924            match entry {
1925                FakeFsEntry::File { .. } => result.push(path),
1926                FakeFsEntry::Dir { entries, .. } => {
1927                    for (name, entry) in entries {
1928                        queue.push_back((path.join(name), entry));
1929                    }
1930                }
1931                FakeFsEntry::Symlink { .. } => {}
1932            }
1933        }
1934        result
1935    }
1936
1937    pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1938        let mut result = Vec::new();
1939        let mut queue = collections::VecDeque::new();
1940        let state = &*self.state.lock();
1941        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1942        while let Some((path, entry)) = queue.pop_front() {
1943            match entry {
1944                FakeFsEntry::File { content, .. } => {
1945                    if path.starts_with(prefix) {
1946                        result.push((path, content.clone()));
1947                    }
1948                }
1949                FakeFsEntry::Dir { entries, .. } => {
1950                    for (name, entry) in entries {
1951                        queue.push_back((path.join(name), entry));
1952                    }
1953                }
1954                FakeFsEntry::Symlink { .. } => {}
1955            }
1956        }
1957        result
1958    }
1959
1960    /// How many `read_dir` calls have been issued.
1961    pub fn read_dir_call_count(&self) -> usize {
1962        self.state.lock().read_dir_call_count
1963    }
1964
1965    pub fn watched_paths(&self) -> Vec<PathBuf> {
1966        let state = self.state.lock();
1967        state
1968            .event_txs
1969            .iter()
1970            .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
1971            .collect()
1972    }
1973
1974    /// How many `metadata` calls have been issued.
1975    pub fn metadata_call_count(&self) -> usize {
1976        self.state.lock().metadata_call_count
1977    }
1978
1979    /// How many write operations have been issued for a specific path.
1980    pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
1981        let path = path.as_ref().to_path_buf();
1982        self.state
1983            .lock()
1984            .path_write_counts
1985            .get(&path)
1986            .copied()
1987            .unwrap_or(0)
1988    }
1989
1990    pub fn emit_fs_event(&self, path: impl Into<PathBuf>, event: Option<PathEventKind>) {
1991        self.state.lock().emit_event(std::iter::once((path, event)));
1992    }
1993
1994    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1995        self.executor.simulate_random_delay()
1996    }
1997}
1998
1999#[cfg(any(test, feature = "test-support"))]
2000impl FakeFsEntry {
2001    fn is_file(&self) -> bool {
2002        matches!(self, Self::File { .. })
2003    }
2004
2005    fn is_symlink(&self) -> bool {
2006        matches!(self, Self::Symlink { .. })
2007    }
2008
2009    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
2010        if let Self::File { content, .. } = self {
2011            Ok(content)
2012        } else {
2013            anyhow::bail!("not a file: {path:?}");
2014        }
2015    }
2016
2017    fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
2018        if let Self::Dir { entries, .. } = self {
2019            Ok(entries)
2020        } else {
2021            anyhow::bail!("not a directory: {path:?}");
2022        }
2023    }
2024}
2025
2026#[cfg(any(test, feature = "test-support"))]
2027struct FakeWatcher {
2028    tx: smol::channel::Sender<Vec<PathEvent>>,
2029    original_path: PathBuf,
2030    fs_state: Arc<Mutex<FakeFsState>>,
2031    prefixes: Mutex<Vec<PathBuf>>,
2032}
2033
2034#[cfg(any(test, feature = "test-support"))]
2035impl Watcher for FakeWatcher {
2036    fn add(&self, path: &Path) -> Result<()> {
2037        if path.starts_with(&self.original_path) {
2038            return Ok(());
2039        }
2040        self.fs_state
2041            .try_lock()
2042            .unwrap()
2043            .event_txs
2044            .push((path.to_owned(), self.tx.clone()));
2045        self.prefixes.lock().push(path.to_owned());
2046        Ok(())
2047    }
2048
2049    fn remove(&self, _: &Path) -> Result<()> {
2050        Ok(())
2051    }
2052}
2053
2054#[cfg(any(test, feature = "test-support"))]
2055#[derive(Debug)]
2056struct FakeHandle {
2057    inode: u64,
2058}
2059
2060#[cfg(any(test, feature = "test-support"))]
2061impl FileHandle for FakeHandle {
2062    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
2063        let fs = fs.as_fake();
2064        let mut state = fs.state.lock();
2065        let Some(target) = state.moves.get(&self.inode).cloned() else {
2066            anyhow::bail!("fake fd not moved")
2067        };
2068
2069        if state.try_entry(&target, false).is_some() {
2070            return Ok(target);
2071        }
2072        anyhow::bail!("fake fd target not found")
2073    }
2074}
2075
2076#[cfg(any(test, feature = "test-support"))]
2077#[async_trait::async_trait]
2078impl Fs for FakeFs {
2079    async fn create_dir(&self, path: &Path) -> Result<()> {
2080        self.simulate_random_delay().await;
2081
2082        let mut created_dirs = Vec::new();
2083        let mut cur_path = PathBuf::new();
2084        for component in path.components() {
2085            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
2086            cur_path.push(component);
2087            if should_skip {
2088                continue;
2089            }
2090            let mut state = self.state.lock();
2091
2092            let inode = state.get_and_increment_inode();
2093            let mtime = state.get_and_increment_mtime();
2094            state.write_path(&cur_path, |entry| {
2095                entry.or_insert_with(|| {
2096                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
2097                    FakeFsEntry::Dir {
2098                        inode,
2099                        mtime,
2100                        len: 0,
2101                        entries: Default::default(),
2102                        git_repo_state: None,
2103                    }
2104                });
2105                Ok(())
2106            })?
2107        }
2108
2109        self.state.lock().emit_event(created_dirs);
2110        Ok(())
2111    }
2112
2113    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2114        self.simulate_random_delay().await;
2115        let mut state = self.state.lock();
2116        let inode = state.get_and_increment_inode();
2117        let mtime = state.get_and_increment_mtime();
2118        let file = FakeFsEntry::File {
2119            inode,
2120            mtime,
2121            len: 0,
2122            content: Vec::new(),
2123            git_dir_path: None,
2124        };
2125        let mut kind = Some(PathEventKind::Created);
2126        state.write_path(path, |entry| {
2127            match entry {
2128                btree_map::Entry::Occupied(mut e) => {
2129                    if options.overwrite {
2130                        kind = Some(PathEventKind::Changed);
2131                        *e.get_mut() = file;
2132                    } else if !options.ignore_if_exists {
2133                        anyhow::bail!("path already exists: {path:?}");
2134                    }
2135                }
2136                btree_map::Entry::Vacant(e) => {
2137                    e.insert(file);
2138                }
2139            }
2140            Ok(())
2141        })?;
2142        state.emit_event([(path, kind)]);
2143        Ok(())
2144    }
2145
2146    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2147        let mut state = self.state.lock();
2148        let file = FakeFsEntry::Symlink { target };
2149        state
2150            .write_path(path.as_ref(), move |e| match e {
2151                btree_map::Entry::Vacant(e) => {
2152                    e.insert(file);
2153                    Ok(())
2154                }
2155                btree_map::Entry::Occupied(mut e) => {
2156                    *e.get_mut() = file;
2157                    Ok(())
2158                }
2159            })
2160            .unwrap();
2161        state.emit_event([(path, Some(PathEventKind::Created))]);
2162
2163        Ok(())
2164    }
2165
2166    async fn create_file_with(
2167        &self,
2168        path: &Path,
2169        mut content: Pin<&mut (dyn AsyncRead + Send)>,
2170    ) -> Result<()> {
2171        let mut bytes = Vec::new();
2172        content.read_to_end(&mut bytes).await?;
2173        self.write_file_internal(path, bytes, true)?;
2174        Ok(())
2175    }
2176
2177    async fn extract_tar_file(
2178        &self,
2179        path: &Path,
2180        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2181    ) -> Result<()> {
2182        let mut entries = content.entries()?;
2183        while let Some(entry) = entries.next().await {
2184            let mut entry = entry?;
2185            if entry.header().entry_type().is_file() {
2186                let path = path.join(entry.path()?.as_ref());
2187                let mut bytes = Vec::new();
2188                entry.read_to_end(&mut bytes).await?;
2189                self.create_dir(path.parent().unwrap()).await?;
2190                self.write_file_internal(&path, bytes, true)?;
2191            }
2192        }
2193        Ok(())
2194    }
2195
2196    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2197        self.simulate_random_delay().await;
2198
2199        let old_path = normalize_path(old_path);
2200        let new_path = normalize_path(new_path);
2201
2202        let mut state = self.state.lock();
2203        let moved_entry = state.write_path(&old_path, |e| {
2204            if let btree_map::Entry::Occupied(e) = e {
2205                Ok(e.get().clone())
2206            } else {
2207                anyhow::bail!("path does not exist: {old_path:?}")
2208            }
2209        })?;
2210
2211        let inode = match moved_entry {
2212            FakeFsEntry::File { inode, .. } => inode,
2213            FakeFsEntry::Dir { inode, .. } => inode,
2214            _ => 0,
2215        };
2216
2217        state.moves.insert(inode, new_path.clone());
2218
2219        state.write_path(&new_path, |e| {
2220            match e {
2221                btree_map::Entry::Occupied(mut e) => {
2222                    if options.overwrite {
2223                        *e.get_mut() = moved_entry;
2224                    } else if !options.ignore_if_exists {
2225                        anyhow::bail!("path already exists: {new_path:?}");
2226                    }
2227                }
2228                btree_map::Entry::Vacant(e) => {
2229                    e.insert(moved_entry);
2230                }
2231            }
2232            Ok(())
2233        })?;
2234
2235        state
2236            .write_path(&old_path, |e| {
2237                if let btree_map::Entry::Occupied(e) = e {
2238                    Ok(e.remove())
2239                } else {
2240                    unreachable!()
2241                }
2242            })
2243            .unwrap();
2244
2245        state.emit_event([
2246            (old_path, Some(PathEventKind::Removed)),
2247            (new_path, Some(PathEventKind::Created)),
2248        ]);
2249        Ok(())
2250    }
2251
2252    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2253        self.simulate_random_delay().await;
2254
2255        let source = normalize_path(source);
2256        let target = normalize_path(target);
2257        let mut state = self.state.lock();
2258        let mtime = state.get_and_increment_mtime();
2259        let inode = state.get_and_increment_inode();
2260        let source_entry = state.entry(&source)?;
2261        let content = source_entry.file_content(&source)?.clone();
2262        let mut kind = Some(PathEventKind::Created);
2263        state.write_path(&target, |e| match e {
2264            btree_map::Entry::Occupied(e) => {
2265                if options.overwrite {
2266                    kind = Some(PathEventKind::Changed);
2267                    Ok(Some(e.get().clone()))
2268                } else if !options.ignore_if_exists {
2269                    anyhow::bail!("{target:?} already exists");
2270                } else {
2271                    Ok(None)
2272                }
2273            }
2274            btree_map::Entry::Vacant(e) => Ok(Some(
2275                e.insert(FakeFsEntry::File {
2276                    inode,
2277                    mtime,
2278                    len: content.len() as u64,
2279                    content,
2280                    git_dir_path: None,
2281                })
2282                .clone(),
2283            )),
2284        })?;
2285        state.emit_event([(target, kind)]);
2286        Ok(())
2287    }
2288
2289    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2290        self.simulate_random_delay().await;
2291
2292        let path = normalize_path(path);
2293        let parent_path = path.parent().context("cannot remove the root")?;
2294        let base_name = path.file_name().context("cannot remove the root")?;
2295
2296        let mut state = self.state.lock();
2297        let parent_entry = state.entry(parent_path)?;
2298        let entry = parent_entry
2299            .dir_entries(parent_path)?
2300            .entry(base_name.to_str().unwrap().into());
2301
2302        match entry {
2303            btree_map::Entry::Vacant(_) => {
2304                if !options.ignore_if_not_exists {
2305                    anyhow::bail!("{path:?} does not exist");
2306                }
2307            }
2308            btree_map::Entry::Occupied(mut entry) => {
2309                {
2310                    let children = entry.get_mut().dir_entries(&path)?;
2311                    if !options.recursive && !children.is_empty() {
2312                        anyhow::bail!("{path:?} is not empty");
2313                    }
2314                }
2315                entry.remove();
2316            }
2317        }
2318        state.emit_event([(path, Some(PathEventKind::Removed))]);
2319        Ok(())
2320    }
2321
2322    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2323        self.simulate_random_delay().await;
2324
2325        let path = normalize_path(path);
2326        let parent_path = path.parent().context("cannot remove the root")?;
2327        let base_name = path.file_name().unwrap();
2328        let mut state = self.state.lock();
2329        let parent_entry = state.entry(parent_path)?;
2330        let entry = parent_entry
2331            .dir_entries(parent_path)?
2332            .entry(base_name.to_str().unwrap().into());
2333        match entry {
2334            btree_map::Entry::Vacant(_) => {
2335                if !options.ignore_if_not_exists {
2336                    anyhow::bail!("{path:?} does not exist");
2337                }
2338            }
2339            btree_map::Entry::Occupied(mut entry) => {
2340                entry.get_mut().file_content(&path)?;
2341                entry.remove();
2342            }
2343        }
2344        state.emit_event([(path, Some(PathEventKind::Removed))]);
2345        Ok(())
2346    }
2347
2348    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2349        let bytes = self.load_internal(path).await?;
2350        Ok(Box::new(io::Cursor::new(bytes)))
2351    }
2352
2353    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2354        self.simulate_random_delay().await;
2355        let mut state = self.state.lock();
2356        let inode = match state.entry(path)? {
2357            FakeFsEntry::File { inode, .. } => *inode,
2358            FakeFsEntry::Dir { inode, .. } => *inode,
2359            _ => unreachable!(),
2360        };
2361        Ok(Arc::new(FakeHandle { inode }))
2362    }
2363
2364    async fn load(&self, path: &Path) -> Result<String> {
2365        let content = self.load_internal(path).await?;
2366        Ok(String::from_utf8(content)?)
2367    }
2368
2369    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2370        self.load_internal(path).await
2371    }
2372
2373    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2374        self.simulate_random_delay().await;
2375        let path = normalize_path(path.as_path());
2376        if let Some(path) = path.parent() {
2377            self.create_dir(path).await?;
2378        }
2379        self.write_file_internal(path, data.into_bytes(), true)?;
2380        Ok(())
2381    }
2382
2383    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2384        self.simulate_random_delay().await;
2385        let path = normalize_path(path);
2386        let content = chunks(text, line_ending).collect::<String>();
2387        if let Some(path) = path.parent() {
2388            self.create_dir(path).await?;
2389        }
2390        self.write_file_internal(path, content.into_bytes(), false)?;
2391        Ok(())
2392    }
2393
2394    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2395        self.simulate_random_delay().await;
2396        let path = normalize_path(path);
2397        if let Some(path) = path.parent() {
2398            self.create_dir(path).await?;
2399        }
2400        self.write_file_internal(path, content.to_vec(), false)?;
2401        Ok(())
2402    }
2403
2404    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2405        let path = normalize_path(path);
2406        self.simulate_random_delay().await;
2407        let state = self.state.lock();
2408        let canonical_path = state
2409            .canonicalize(&path, true)
2410            .with_context(|| format!("path does not exist: {path:?}"))?;
2411        Ok(canonical_path)
2412    }
2413
2414    async fn is_file(&self, path: &Path) -> bool {
2415        let path = normalize_path(path);
2416        self.simulate_random_delay().await;
2417        let mut state = self.state.lock();
2418        if let Some((entry, _)) = state.try_entry(&path, true) {
2419            entry.is_file()
2420        } else {
2421            false
2422        }
2423    }
2424
2425    async fn is_dir(&self, path: &Path) -> bool {
2426        self.metadata(path)
2427            .await
2428            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2429    }
2430
2431    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2432        self.simulate_random_delay().await;
2433        let path = normalize_path(path);
2434        let mut state = self.state.lock();
2435        state.metadata_call_count += 1;
2436        if let Some((mut entry, _)) = state.try_entry(&path, false) {
2437            let is_symlink = entry.is_symlink();
2438            if is_symlink {
2439                if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2440                    entry = e;
2441                } else {
2442                    return Ok(None);
2443                }
2444            }
2445
2446            Ok(Some(match &*entry {
2447                FakeFsEntry::File {
2448                    inode, mtime, len, ..
2449                } => Metadata {
2450                    inode: *inode,
2451                    mtime: *mtime,
2452                    len: *len,
2453                    is_dir: false,
2454                    is_symlink,
2455                    is_fifo: false,
2456                },
2457                FakeFsEntry::Dir {
2458                    inode, mtime, len, ..
2459                } => Metadata {
2460                    inode: *inode,
2461                    mtime: *mtime,
2462                    len: *len,
2463                    is_dir: true,
2464                    is_symlink,
2465                    is_fifo: false,
2466                },
2467                FakeFsEntry::Symlink { .. } => unreachable!(),
2468            }))
2469        } else {
2470            Ok(None)
2471        }
2472    }
2473
2474    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2475        self.simulate_random_delay().await;
2476        let path = normalize_path(path);
2477        let mut state = self.state.lock();
2478        let (entry, _) = state
2479            .try_entry(&path, false)
2480            .with_context(|| format!("path does not exist: {path:?}"))?;
2481        if let FakeFsEntry::Symlink { target } = entry {
2482            Ok(target.clone())
2483        } else {
2484            anyhow::bail!("not a symlink: {path:?}")
2485        }
2486    }
2487
2488    async fn read_dir(
2489        &self,
2490        path: &Path,
2491    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2492        self.simulate_random_delay().await;
2493        let path = normalize_path(path);
2494        let mut state = self.state.lock();
2495        state.read_dir_call_count += 1;
2496        let entry = state.entry(&path)?;
2497        let children = entry.dir_entries(&path)?;
2498        let paths = children
2499            .keys()
2500            .map(|file_name| Ok(path.join(file_name)))
2501            .collect::<Vec<_>>();
2502        Ok(Box::pin(futures::stream::iter(paths)))
2503    }
2504
2505    async fn watch(
2506        &self,
2507        path: &Path,
2508        _: Duration,
2509    ) -> (
2510        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2511        Arc<dyn Watcher>,
2512    ) {
2513        self.simulate_random_delay().await;
2514        let (tx, rx) = smol::channel::unbounded();
2515        let path = path.to_path_buf();
2516        self.state.lock().event_txs.push((path.clone(), tx.clone()));
2517        let executor = self.executor.clone();
2518        let watcher = Arc::new(FakeWatcher {
2519            tx,
2520            original_path: path.to_owned(),
2521            fs_state: self.state.clone(),
2522            prefixes: Mutex::new(vec![path]),
2523        });
2524        (
2525            Box::pin(futures::StreamExt::filter(rx, {
2526                let watcher = watcher.clone();
2527                move |events| {
2528                    let result = events.iter().any(|evt_path| {
2529                        watcher
2530                            .prefixes
2531                            .lock()
2532                            .iter()
2533                            .any(|prefix| evt_path.path.starts_with(prefix))
2534                    });
2535                    let executor = executor.clone();
2536                    async move {
2537                        executor.simulate_random_delay().await;
2538                        result
2539                    }
2540                }
2541            })),
2542            watcher,
2543        )
2544    }
2545
2546    fn open_repo(
2547        &self,
2548        abs_dot_git: &Path,
2549        _system_git_binary: Option<&Path>,
2550    ) -> Option<Arc<dyn GitRepository>> {
2551        use util::ResultExt as _;
2552
2553        self.with_git_state_and_paths(
2554            abs_dot_git,
2555            false,
2556            |_, repository_dir_path, common_dir_path| {
2557                Arc::new(fake_git_repo::FakeGitRepository {
2558                    fs: self.this.upgrade().unwrap(),
2559                    executor: self.executor.clone(),
2560                    dot_git_path: abs_dot_git.to_path_buf(),
2561                    repository_dir_path: repository_dir_path.to_owned(),
2562                    common_dir_path: common_dir_path.to_owned(),
2563                    checkpoints: Arc::default(),
2564                }) as _
2565            },
2566        )
2567        .log_err()
2568    }
2569
2570    async fn git_init(
2571        &self,
2572        abs_work_directory_path: &Path,
2573        _fallback_branch_name: String,
2574    ) -> Result<()> {
2575        self.create_dir(&abs_work_directory_path.join(".git")).await
2576    }
2577
2578    async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2579        anyhow::bail!("Git clone is not supported in fake Fs")
2580    }
2581
2582    fn is_fake(&self) -> bool {
2583        true
2584    }
2585
2586    async fn is_case_sensitive(&self) -> Result<bool> {
2587        Ok(true)
2588    }
2589
2590    #[cfg(any(test, feature = "test-support"))]
2591    fn as_fake(&self) -> Arc<FakeFs> {
2592        self.this.upgrade().unwrap()
2593    }
2594}
2595
2596fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2597    rope.chunks().flat_map(move |chunk| {
2598        let mut newline = false;
2599        let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
2600        chunk
2601            .lines()
2602            .flat_map(move |line| {
2603                let ending = if newline {
2604                    Some(line_ending.as_str())
2605                } else {
2606                    None
2607                };
2608                newline = true;
2609                ending.into_iter().chain([line])
2610            })
2611            .chain(end_with_newline)
2612    })
2613}
2614
2615pub fn normalize_path(path: &Path) -> PathBuf {
2616    let mut components = path.components().peekable();
2617    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2618        components.next();
2619        PathBuf::from(c.as_os_str())
2620    } else {
2621        PathBuf::new()
2622    };
2623
2624    for component in components {
2625        match component {
2626            Component::Prefix(..) => unreachable!(),
2627            Component::RootDir => {
2628                ret.push(component.as_os_str());
2629            }
2630            Component::CurDir => {}
2631            Component::ParentDir => {
2632                ret.pop();
2633            }
2634            Component::Normal(c) => {
2635                ret.push(c);
2636            }
2637        }
2638    }
2639    ret
2640}
2641
2642pub async fn copy_recursive<'a>(
2643    fs: &'a dyn Fs,
2644    source: &'a Path,
2645    target: &'a Path,
2646    options: CopyOptions,
2647) -> Result<()> {
2648    for (item, is_dir) in read_dir_items(fs, source).await? {
2649        let Ok(item_relative_path) = item.strip_prefix(source) else {
2650            continue;
2651        };
2652        let target_item = if item_relative_path == Path::new("") {
2653            target.to_path_buf()
2654        } else {
2655            target.join(item_relative_path)
2656        };
2657        if is_dir {
2658            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2659                if options.ignore_if_exists {
2660                    continue;
2661                } else {
2662                    anyhow::bail!("{target_item:?} already exists");
2663                }
2664            }
2665            let _ = fs
2666                .remove_dir(
2667                    &target_item,
2668                    RemoveOptions {
2669                        recursive: true,
2670                        ignore_if_not_exists: true,
2671                    },
2672                )
2673                .await;
2674            fs.create_dir(&target_item).await?;
2675        } else {
2676            fs.copy_file(&item, &target_item, options).await?;
2677        }
2678    }
2679    Ok(())
2680}
2681
2682/// Recursively reads all of the paths in the given directory.
2683///
2684/// Returns a vector of tuples of (path, is_dir).
2685pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2686    let mut items = Vec::new();
2687    read_recursive(fs, source, &mut items).await?;
2688    Ok(items)
2689}
2690
2691fn read_recursive<'a>(
2692    fs: &'a dyn Fs,
2693    source: &'a Path,
2694    output: &'a mut Vec<(PathBuf, bool)>,
2695) -> BoxFuture<'a, Result<()>> {
2696    use futures::future::FutureExt;
2697
2698    async move {
2699        let metadata = fs
2700            .metadata(source)
2701            .await?
2702            .with_context(|| format!("path does not exist: {source:?}"))?;
2703
2704        if metadata.is_dir {
2705            output.push((source.to_path_buf(), true));
2706            let mut children = fs.read_dir(source).await?;
2707            while let Some(child_path) = children.next().await {
2708                if let Ok(child_path) = child_path {
2709                    read_recursive(fs, &child_path, output).await?;
2710                }
2711            }
2712        } else {
2713            output.push((source.to_path_buf(), false));
2714        }
2715        Ok(())
2716    }
2717    .boxed()
2718}
2719
2720// todo(windows)
2721// can we get file id not open the file twice?
2722// https://github.com/rust-lang/rust/issues/63010
2723#[cfg(target_os = "windows")]
2724async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2725    use std::os::windows::io::AsRawHandle;
2726
2727    use smol::fs::windows::OpenOptionsExt;
2728    use windows::Win32::{
2729        Foundation::HANDLE,
2730        Storage::FileSystem::{
2731            BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2732        },
2733    };
2734
2735    let file = smol::fs::OpenOptions::new()
2736        .read(true)
2737        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2738        .open(path)
2739        .await?;
2740
2741    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2742    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2743    // This function supports Windows XP+
2744    smol::unblock(move || {
2745        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2746
2747        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2748    })
2749    .await
2750}
2751
2752#[cfg(target_os = "windows")]
2753fn atomic_replace<P: AsRef<Path>>(
2754    replaced_file: P,
2755    replacement_file: P,
2756) -> windows::core::Result<()> {
2757    use windows::{
2758        Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2759        core::HSTRING,
2760    };
2761
2762    // If the file does not exist, create it.
2763    let _ = std::fs::File::create_new(replaced_file.as_ref());
2764
2765    unsafe {
2766        ReplaceFileW(
2767            &HSTRING::from(replaced_file.as_ref().to_string_lossy().into_owned()),
2768            &HSTRING::from(replacement_file.as_ref().to_string_lossy().into_owned()),
2769            None,
2770            REPLACE_FILE_FLAGS::default(),
2771            None,
2772            None,
2773        )
2774    }
2775}
2776
2777#[cfg(test)]
2778mod tests {
2779    use super::*;
2780    use gpui::BackgroundExecutor;
2781    use serde_json::json;
2782    use util::path;
2783
2784    #[gpui::test]
2785    async fn test_fake_fs(executor: BackgroundExecutor) {
2786        let fs = FakeFs::new(executor.clone());
2787        fs.insert_tree(
2788            path!("/root"),
2789            json!({
2790                "dir1": {
2791                    "a": "A",
2792                    "b": "B"
2793                },
2794                "dir2": {
2795                    "c": "C",
2796                    "dir3": {
2797                        "d": "D"
2798                    }
2799                }
2800            }),
2801        )
2802        .await;
2803
2804        assert_eq!(
2805            fs.files(),
2806            vec![
2807                PathBuf::from(path!("/root/dir1/a")),
2808                PathBuf::from(path!("/root/dir1/b")),
2809                PathBuf::from(path!("/root/dir2/c")),
2810                PathBuf::from(path!("/root/dir2/dir3/d")),
2811            ]
2812        );
2813
2814        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2815            .await
2816            .unwrap();
2817
2818        assert_eq!(
2819            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2820                .await
2821                .unwrap(),
2822            PathBuf::from(path!("/root/dir2/dir3")),
2823        );
2824        assert_eq!(
2825            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2826                .await
2827                .unwrap(),
2828            PathBuf::from(path!("/root/dir2/dir3/d")),
2829        );
2830        assert_eq!(
2831            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2832                .await
2833                .unwrap(),
2834            "D",
2835        );
2836    }
2837
2838    #[gpui::test]
2839    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2840        let fs = FakeFs::new(executor.clone());
2841        fs.insert_tree(
2842            path!("/outer"),
2843            json!({
2844                "a": "A",
2845                "b": "B",
2846                "inner": {}
2847            }),
2848        )
2849        .await;
2850
2851        assert_eq!(
2852            fs.files(),
2853            vec![
2854                PathBuf::from(path!("/outer/a")),
2855                PathBuf::from(path!("/outer/b")),
2856            ]
2857        );
2858
2859        let source = Path::new(path!("/outer/a"));
2860        let target = Path::new(path!("/outer/a copy"));
2861        copy_recursive(fs.as_ref(), source, target, Default::default())
2862            .await
2863            .unwrap();
2864
2865        assert_eq!(
2866            fs.files(),
2867            vec![
2868                PathBuf::from(path!("/outer/a")),
2869                PathBuf::from(path!("/outer/a copy")),
2870                PathBuf::from(path!("/outer/b")),
2871            ]
2872        );
2873
2874        let source = Path::new(path!("/outer/a"));
2875        let target = Path::new(path!("/outer/inner/a copy"));
2876        copy_recursive(fs.as_ref(), source, target, Default::default())
2877            .await
2878            .unwrap();
2879
2880        assert_eq!(
2881            fs.files(),
2882            vec![
2883                PathBuf::from(path!("/outer/a")),
2884                PathBuf::from(path!("/outer/a copy")),
2885                PathBuf::from(path!("/outer/b")),
2886                PathBuf::from(path!("/outer/inner/a copy")),
2887            ]
2888        );
2889    }
2890
2891    #[gpui::test]
2892    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2893        let fs = FakeFs::new(executor.clone());
2894        fs.insert_tree(
2895            path!("/outer"),
2896            json!({
2897                "a": "A",
2898                "empty": {},
2899                "non-empty": {
2900                    "b": "B",
2901                }
2902            }),
2903        )
2904        .await;
2905
2906        assert_eq!(
2907            fs.files(),
2908            vec![
2909                PathBuf::from(path!("/outer/a")),
2910                PathBuf::from(path!("/outer/non-empty/b")),
2911            ]
2912        );
2913        assert_eq!(
2914            fs.directories(false),
2915            vec![
2916                PathBuf::from(path!("/")),
2917                PathBuf::from(path!("/outer")),
2918                PathBuf::from(path!("/outer/empty")),
2919                PathBuf::from(path!("/outer/non-empty")),
2920            ]
2921        );
2922
2923        let source = Path::new(path!("/outer/empty"));
2924        let target = Path::new(path!("/outer/empty copy"));
2925        copy_recursive(fs.as_ref(), source, target, Default::default())
2926            .await
2927            .unwrap();
2928
2929        assert_eq!(
2930            fs.files(),
2931            vec![
2932                PathBuf::from(path!("/outer/a")),
2933                PathBuf::from(path!("/outer/non-empty/b")),
2934            ]
2935        );
2936        assert_eq!(
2937            fs.directories(false),
2938            vec![
2939                PathBuf::from(path!("/")),
2940                PathBuf::from(path!("/outer")),
2941                PathBuf::from(path!("/outer/empty")),
2942                PathBuf::from(path!("/outer/empty copy")),
2943                PathBuf::from(path!("/outer/non-empty")),
2944            ]
2945        );
2946
2947        let source = Path::new(path!("/outer/non-empty"));
2948        let target = Path::new(path!("/outer/non-empty copy"));
2949        copy_recursive(fs.as_ref(), source, target, Default::default())
2950            .await
2951            .unwrap();
2952
2953        assert_eq!(
2954            fs.files(),
2955            vec![
2956                PathBuf::from(path!("/outer/a")),
2957                PathBuf::from(path!("/outer/non-empty/b")),
2958                PathBuf::from(path!("/outer/non-empty copy/b")),
2959            ]
2960        );
2961        assert_eq!(
2962            fs.directories(false),
2963            vec![
2964                PathBuf::from(path!("/")),
2965                PathBuf::from(path!("/outer")),
2966                PathBuf::from(path!("/outer/empty")),
2967                PathBuf::from(path!("/outer/empty copy")),
2968                PathBuf::from(path!("/outer/non-empty")),
2969                PathBuf::from(path!("/outer/non-empty copy")),
2970            ]
2971        );
2972    }
2973
2974    #[gpui::test]
2975    async fn test_copy_recursive(executor: BackgroundExecutor) {
2976        let fs = FakeFs::new(executor.clone());
2977        fs.insert_tree(
2978            path!("/outer"),
2979            json!({
2980                "inner1": {
2981                    "a": "A",
2982                    "b": "B",
2983                    "inner3": {
2984                        "d": "D",
2985                    },
2986                    "inner4": {}
2987                },
2988                "inner2": {
2989                    "c": "C",
2990                }
2991            }),
2992        )
2993        .await;
2994
2995        assert_eq!(
2996            fs.files(),
2997            vec![
2998                PathBuf::from(path!("/outer/inner1/a")),
2999                PathBuf::from(path!("/outer/inner1/b")),
3000                PathBuf::from(path!("/outer/inner2/c")),
3001                PathBuf::from(path!("/outer/inner1/inner3/d")),
3002            ]
3003        );
3004        assert_eq!(
3005            fs.directories(false),
3006            vec![
3007                PathBuf::from(path!("/")),
3008                PathBuf::from(path!("/outer")),
3009                PathBuf::from(path!("/outer/inner1")),
3010                PathBuf::from(path!("/outer/inner2")),
3011                PathBuf::from(path!("/outer/inner1/inner3")),
3012                PathBuf::from(path!("/outer/inner1/inner4")),
3013            ]
3014        );
3015
3016        let source = Path::new(path!("/outer"));
3017        let target = Path::new(path!("/outer/inner1/outer"));
3018        copy_recursive(fs.as_ref(), source, target, Default::default())
3019            .await
3020            .unwrap();
3021
3022        assert_eq!(
3023            fs.files(),
3024            vec![
3025                PathBuf::from(path!("/outer/inner1/a")),
3026                PathBuf::from(path!("/outer/inner1/b")),
3027                PathBuf::from(path!("/outer/inner2/c")),
3028                PathBuf::from(path!("/outer/inner1/inner3/d")),
3029                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3030                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3031                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3032                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
3033            ]
3034        );
3035        assert_eq!(
3036            fs.directories(false),
3037            vec![
3038                PathBuf::from(path!("/")),
3039                PathBuf::from(path!("/outer")),
3040                PathBuf::from(path!("/outer/inner1")),
3041                PathBuf::from(path!("/outer/inner2")),
3042                PathBuf::from(path!("/outer/inner1/inner3")),
3043                PathBuf::from(path!("/outer/inner1/inner4")),
3044                PathBuf::from(path!("/outer/inner1/outer")),
3045                PathBuf::from(path!("/outer/inner1/outer/inner1")),
3046                PathBuf::from(path!("/outer/inner1/outer/inner2")),
3047                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
3048                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
3049            ]
3050        );
3051    }
3052
3053    #[gpui::test]
3054    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
3055        let fs = FakeFs::new(executor.clone());
3056        fs.insert_tree(
3057            path!("/outer"),
3058            json!({
3059                "inner1": {
3060                    "a": "A",
3061                    "b": "B",
3062                    "outer": {
3063                        "inner1": {
3064                            "a": "B"
3065                        }
3066                    }
3067                },
3068                "inner2": {
3069                    "c": "C",
3070                }
3071            }),
3072        )
3073        .await;
3074
3075        assert_eq!(
3076            fs.files(),
3077            vec![
3078                PathBuf::from(path!("/outer/inner1/a")),
3079                PathBuf::from(path!("/outer/inner1/b")),
3080                PathBuf::from(path!("/outer/inner2/c")),
3081                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3082            ]
3083        );
3084        assert_eq!(
3085            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3086                .await
3087                .unwrap(),
3088            "B",
3089        );
3090
3091        let source = Path::new(path!("/outer"));
3092        let target = Path::new(path!("/outer/inner1/outer"));
3093        copy_recursive(
3094            fs.as_ref(),
3095            source,
3096            target,
3097            CopyOptions {
3098                overwrite: true,
3099                ..Default::default()
3100            },
3101        )
3102        .await
3103        .unwrap();
3104
3105        assert_eq!(
3106            fs.files(),
3107            vec![
3108                PathBuf::from(path!("/outer/inner1/a")),
3109                PathBuf::from(path!("/outer/inner1/b")),
3110                PathBuf::from(path!("/outer/inner2/c")),
3111                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3112                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3113                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3114                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3115            ]
3116        );
3117        assert_eq!(
3118            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3119                .await
3120                .unwrap(),
3121            "A"
3122        );
3123    }
3124
3125    #[gpui::test]
3126    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
3127        let fs = FakeFs::new(executor.clone());
3128        fs.insert_tree(
3129            path!("/outer"),
3130            json!({
3131                "inner1": {
3132                    "a": "A",
3133                    "b": "B",
3134                    "outer": {
3135                        "inner1": {
3136                            "a": "B"
3137                        }
3138                    }
3139                },
3140                "inner2": {
3141                    "c": "C",
3142                }
3143            }),
3144        )
3145        .await;
3146
3147        assert_eq!(
3148            fs.files(),
3149            vec![
3150                PathBuf::from(path!("/outer/inner1/a")),
3151                PathBuf::from(path!("/outer/inner1/b")),
3152                PathBuf::from(path!("/outer/inner2/c")),
3153                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3154            ]
3155        );
3156        assert_eq!(
3157            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3158                .await
3159                .unwrap(),
3160            "B",
3161        );
3162
3163        let source = Path::new(path!("/outer"));
3164        let target = Path::new(path!("/outer/inner1/outer"));
3165        copy_recursive(
3166            fs.as_ref(),
3167            source,
3168            target,
3169            CopyOptions {
3170                ignore_if_exists: true,
3171                ..Default::default()
3172            },
3173        )
3174        .await
3175        .unwrap();
3176
3177        assert_eq!(
3178            fs.files(),
3179            vec![
3180                PathBuf::from(path!("/outer/inner1/a")),
3181                PathBuf::from(path!("/outer/inner1/b")),
3182                PathBuf::from(path!("/outer/inner2/c")),
3183                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3184                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3185                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3186                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3187            ]
3188        );
3189        assert_eq!(
3190            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3191                .await
3192                .unwrap(),
3193            "B"
3194        );
3195    }
3196
3197    #[gpui::test]
3198    async fn test_realfs_atomic_write(executor: BackgroundExecutor) {
3199        // With the file handle still open, the file should be replaced
3200        // https://github.com/zed-industries/zed/issues/30054
3201        let fs = RealFs {
3202            bundled_git_binary_path: None,
3203            executor,
3204        };
3205        let temp_dir = TempDir::new().unwrap();
3206        let file_to_be_replaced = temp_dir.path().join("file.txt");
3207        let mut file = std::fs::File::create_new(&file_to_be_replaced).unwrap();
3208        file.write_all(b"Hello").unwrap();
3209        // drop(file);  // We still hold the file handle here
3210        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3211        assert_eq!(content, "Hello");
3212        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "World".into())).unwrap();
3213        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3214        assert_eq!(content, "World");
3215    }
3216
3217    #[gpui::test]
3218    async fn test_realfs_atomic_write_non_existing_file(executor: BackgroundExecutor) {
3219        let fs = RealFs {
3220            bundled_git_binary_path: None,
3221            executor,
3222        };
3223        let temp_dir = TempDir::new().unwrap();
3224        let file_to_be_replaced = temp_dir.path().join("file.txt");
3225        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "Hello".into())).unwrap();
3226        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3227        assert_eq!(content, "Hello");
3228    }
3229}