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(), err.raw_os_error()) {
 723                    (io::ErrorKind::NotFound, _) => Ok(None),
 724                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 725                    _ => Err(anyhow::Error::new(err)),
 726                };
 727            }
 728        };
 729
 730        let is_symlink = symlink_metadata.file_type().is_symlink();
 731        let metadata = if is_symlink {
 732            let path_buf = path.to_path_buf();
 733            let path_exists = self
 734                .executor
 735                .spawn(async move {
 736                    path_buf
 737                        .try_exists()
 738                        .with_context(|| format!("checking existence for path {path_buf:?}"))
 739                })
 740                .await?;
 741            if path_exists {
 742                let path_buf = path.to_path_buf();
 743                self.executor
 744                    .spawn(async move { std::fs::metadata(path_buf) })
 745                    .await
 746                    .with_context(|| "accessing symlink for path {path}")?
 747            } else {
 748                symlink_metadata
 749            }
 750        } else {
 751            symlink_metadata
 752        };
 753
 754        #[cfg(unix)]
 755        let inode = metadata.ino();
 756
 757        #[cfg(windows)]
 758        let inode = file_id(path).await?;
 759
 760        #[cfg(windows)]
 761        let is_fifo = false;
 762
 763        #[cfg(unix)]
 764        let is_fifo = metadata.file_type().is_fifo();
 765
 766        Ok(Some(Metadata {
 767            inode,
 768            mtime: MTime(metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH)),
 769            len: metadata.len(),
 770            is_symlink,
 771            is_dir: metadata.file_type().is_dir(),
 772            is_fifo,
 773        }))
 774    }
 775
 776    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 777        let path = path.to_owned();
 778        let path = self
 779            .executor
 780            .spawn(async move { std::fs::read_link(&path) })
 781            .await?;
 782        Ok(path)
 783    }
 784
 785    async fn read_dir(
 786        &self,
 787        path: &Path,
 788    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 789        let path = path.to_owned();
 790        let result = iter(
 791            self.executor
 792                .spawn(async move { std::fs::read_dir(path) })
 793                .await?,
 794        )
 795        .map(|entry| match entry {
 796            Ok(entry) => Ok(entry.path()),
 797            Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
 798        });
 799        Ok(Box::pin(result))
 800    }
 801
 802    #[cfg(target_os = "macos")]
 803    async fn watch(
 804        &self,
 805        path: &Path,
 806        latency: Duration,
 807    ) -> (
 808        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 809        Arc<dyn Watcher>,
 810    ) {
 811        use fsevent::StreamFlags;
 812
 813        let (events_tx, events_rx) = smol::channel::unbounded();
 814        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 815        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 816            events_tx,
 817            Arc::downgrade(&handles),
 818            latency,
 819        ));
 820        watcher.add(path).expect("handles can't be dropped");
 821
 822        (
 823            Box::pin(
 824                events_rx
 825                    .map(|events| {
 826                        events
 827                            .into_iter()
 828                            .map(|event| {
 829                                log::trace!("fs path event: {event:?}");
 830                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 831                                    Some(PathEventKind::Removed)
 832                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 833                                    Some(PathEventKind::Created)
 834                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED)
 835                                    | event.flags.contains(StreamFlags::ITEM_RENAMED)
 836                                {
 837                                    Some(PathEventKind::Changed)
 838                                } else {
 839                                    None
 840                                };
 841                                PathEvent {
 842                                    path: event.path,
 843                                    kind,
 844                                }
 845                            })
 846                            .collect()
 847                    })
 848                    .chain(futures::stream::once(async move {
 849                        drop(handles);
 850                        vec![]
 851                    })),
 852            ),
 853            watcher,
 854        )
 855    }
 856
 857    #[cfg(not(target_os = "macos"))]
 858    async fn watch(
 859        &self,
 860        path: &Path,
 861        latency: Duration,
 862    ) -> (
 863        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 864        Arc<dyn Watcher>,
 865    ) {
 866        use parking_lot::Mutex;
 867        use util::{ResultExt as _, paths::SanitizedPath};
 868
 869        let (tx, rx) = smol::channel::unbounded();
 870        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 871        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 872
 873        // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 874        if let Err(e) = watcher.add(path)
 875            && let Some(parent) = path.parent()
 876            && let Err(parent_e) = watcher.add(parent)
 877        {
 878            log::warn!(
 879                "Failed to watch {} and its parent directory {}:\n{e}\n{parent_e}",
 880                path.display(),
 881                parent.display()
 882            );
 883        }
 884
 885        // Check if path is a symlink and follow the target parent
 886        if let Some(mut target) = self.read_link(path).await.ok() {
 887            log::trace!("watch symlink {path:?} -> {target:?}");
 888            // Check if symlink target is relative path, if so make it absolute
 889            if target.is_relative()
 890                && let Some(parent) = path.parent()
 891            {
 892                target = parent.join(target);
 893                if let Ok(canonical) = self.canonicalize(&target).await {
 894                    target = SanitizedPath::new(&canonical).as_path().to_path_buf();
 895                }
 896            }
 897            watcher.add(&target).ok();
 898            if let Some(parent) = target.parent() {
 899                watcher.add(parent).log_err();
 900            }
 901        }
 902
 903        (
 904            Box::pin(rx.filter_map({
 905                let watcher = watcher.clone();
 906                move |_| {
 907                    let _ = watcher.clone();
 908                    let pending_paths = pending_paths.clone();
 909                    async move {
 910                        smol::Timer::after(latency).await;
 911                        let paths = std::mem::take(&mut *pending_paths.lock());
 912                        (!paths.is_empty()).then_some(paths)
 913                    }
 914                }
 915            })),
 916            watcher,
 917        )
 918    }
 919
 920    fn open_repo(
 921        &self,
 922        dotgit_path: &Path,
 923        system_git_binary_path: Option<&Path>,
 924    ) -> Option<Arc<dyn GitRepository>> {
 925        Some(Arc::new(RealGitRepository::new(
 926            dotgit_path,
 927            self.bundled_git_binary_path.clone(),
 928            system_git_binary_path.map(|path| path.to_path_buf()),
 929            self.executor.clone(),
 930        )?))
 931    }
 932
 933    async fn git_init(
 934        &self,
 935        abs_work_directory_path: &Path,
 936        fallback_branch_name: String,
 937    ) -> Result<()> {
 938        let config = new_smol_command("git")
 939            .current_dir(abs_work_directory_path)
 940            .args(&["config", "--global", "--get", "init.defaultBranch"])
 941            .output()
 942            .await?;
 943
 944        let branch_name;
 945
 946        if config.status.success() && !config.stdout.is_empty() {
 947            branch_name = String::from_utf8_lossy(&config.stdout);
 948        } else {
 949            branch_name = Cow::Borrowed(fallback_branch_name.as_str());
 950        }
 951
 952        new_smol_command("git")
 953            .current_dir(abs_work_directory_path)
 954            .args(&["init", "-b"])
 955            .arg(branch_name.trim())
 956            .output()
 957            .await?;
 958
 959        Ok(())
 960    }
 961
 962    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
 963        let output = new_smol_command("git")
 964            .current_dir(abs_work_directory)
 965            .args(&["clone", repo_url])
 966            .output()
 967            .await?;
 968
 969        if !output.status.success() {
 970            anyhow::bail!(
 971                "git clone failed: {}",
 972                String::from_utf8_lossy(&output.stderr)
 973            );
 974        }
 975
 976        Ok(())
 977    }
 978
 979    fn is_fake(&self) -> bool {
 980        false
 981    }
 982
 983    /// Checks whether the file system is case sensitive by attempting to create two files
 984    /// that have the same name except for the casing.
 985    ///
 986    /// It creates both files in a temporary directory it removes at the end.
 987    async fn is_case_sensitive(&self) -> Result<bool> {
 988        let temp_dir = TempDir::new()?;
 989        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 990        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 991
 992        let create_opts = CreateOptions {
 993            overwrite: false,
 994            ignore_if_exists: false,
 995        };
 996
 997        // Create file1
 998        self.create_file(&test_file_1, create_opts).await?;
 999
1000        // Now check whether it's possible to create file2
1001        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
1002            Ok(_) => Ok(true),
1003            Err(e) => {
1004                if let Some(io_error) = e.downcast_ref::<io::Error>() {
1005                    if io_error.kind() == io::ErrorKind::AlreadyExists {
1006                        Ok(false)
1007                    } else {
1008                        Err(e)
1009                    }
1010                } else {
1011                    Err(e)
1012                }
1013            }
1014        };
1015
1016        temp_dir.close()?;
1017        case_sensitive
1018    }
1019}
1020
1021#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
1022impl Watcher for RealWatcher {
1023    fn add(&self, _: &Path) -> Result<()> {
1024        Ok(())
1025    }
1026
1027    fn remove(&self, _: &Path) -> Result<()> {
1028        Ok(())
1029    }
1030}
1031
1032#[cfg(any(test, feature = "test-support"))]
1033pub struct FakeFs {
1034    this: std::sync::Weak<Self>,
1035    // Use an unfair lock to ensure tests are deterministic.
1036    state: Arc<Mutex<FakeFsState>>,
1037    executor: gpui::BackgroundExecutor,
1038}
1039
1040#[cfg(any(test, feature = "test-support"))]
1041struct FakeFsState {
1042    root: FakeFsEntry,
1043    next_inode: u64,
1044    next_mtime: SystemTime,
1045    git_event_tx: smol::channel::Sender<PathBuf>,
1046    event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
1047    events_paused: bool,
1048    buffered_events: Vec<PathEvent>,
1049    metadata_call_count: usize,
1050    read_dir_call_count: usize,
1051    path_write_counts: std::collections::HashMap<PathBuf, usize>,
1052    moves: std::collections::HashMap<u64, PathBuf>,
1053}
1054
1055#[cfg(any(test, feature = "test-support"))]
1056#[derive(Clone, Debug)]
1057enum FakeFsEntry {
1058    File {
1059        inode: u64,
1060        mtime: MTime,
1061        len: u64,
1062        content: Vec<u8>,
1063        // The path to the repository state directory, if this is a gitfile.
1064        git_dir_path: Option<PathBuf>,
1065    },
1066    Dir {
1067        inode: u64,
1068        mtime: MTime,
1069        len: u64,
1070        entries: BTreeMap<String, FakeFsEntry>,
1071        git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
1072    },
1073    Symlink {
1074        target: PathBuf,
1075    },
1076}
1077
1078#[cfg(any(test, feature = "test-support"))]
1079impl PartialEq for FakeFsEntry {
1080    fn eq(&self, other: &Self) -> bool {
1081        match (self, other) {
1082            (
1083                Self::File {
1084                    inode: l_inode,
1085                    mtime: l_mtime,
1086                    len: l_len,
1087                    content: l_content,
1088                    git_dir_path: l_git_dir_path,
1089                },
1090                Self::File {
1091                    inode: r_inode,
1092                    mtime: r_mtime,
1093                    len: r_len,
1094                    content: r_content,
1095                    git_dir_path: r_git_dir_path,
1096                },
1097            ) => {
1098                l_inode == r_inode
1099                    && l_mtime == r_mtime
1100                    && l_len == r_len
1101                    && l_content == r_content
1102                    && l_git_dir_path == r_git_dir_path
1103            }
1104            (
1105                Self::Dir {
1106                    inode: l_inode,
1107                    mtime: l_mtime,
1108                    len: l_len,
1109                    entries: l_entries,
1110                    git_repo_state: l_git_repo_state,
1111                },
1112                Self::Dir {
1113                    inode: r_inode,
1114                    mtime: r_mtime,
1115                    len: r_len,
1116                    entries: r_entries,
1117                    git_repo_state: r_git_repo_state,
1118                },
1119            ) => {
1120                let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1121                    (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1122                    (None, None) => true,
1123                    _ => false,
1124                };
1125                l_inode == r_inode
1126                    && l_mtime == r_mtime
1127                    && l_len == r_len
1128                    && l_entries == r_entries
1129                    && same_repo_state
1130            }
1131            (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1132                l_target == r_target
1133            }
1134            _ => false,
1135        }
1136    }
1137}
1138
1139#[cfg(any(test, feature = "test-support"))]
1140impl FakeFsState {
1141    fn get_and_increment_mtime(&mut self) -> MTime {
1142        let mtime = self.next_mtime;
1143        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1144        MTime(mtime)
1145    }
1146
1147    fn get_and_increment_inode(&mut self) -> u64 {
1148        let inode = self.next_inode;
1149        self.next_inode += 1;
1150        inode
1151    }
1152
1153    fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1154        let mut canonical_path = PathBuf::new();
1155        let mut path = target.to_path_buf();
1156        let mut entry_stack = Vec::new();
1157        'outer: loop {
1158            let mut path_components = path.components().peekable();
1159            let mut prefix = None;
1160            while let Some(component) = path_components.next() {
1161                match component {
1162                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1163                    Component::RootDir => {
1164                        entry_stack.clear();
1165                        entry_stack.push(&self.root);
1166                        canonical_path.clear();
1167                        match prefix {
1168                            Some(prefix_component) => {
1169                                canonical_path = PathBuf::from(prefix_component.as_os_str());
1170                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1171                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1172                            }
1173                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1174                        }
1175                    }
1176                    Component::CurDir => {}
1177                    Component::ParentDir => {
1178                        entry_stack.pop()?;
1179                        canonical_path.pop();
1180                    }
1181                    Component::Normal(name) => {
1182                        let current_entry = *entry_stack.last()?;
1183                        if let FakeFsEntry::Dir { entries, .. } = current_entry {
1184                            let entry = entries.get(name.to_str().unwrap())?;
1185                            if (path_components.peek().is_some() || follow_symlink)
1186                                && let FakeFsEntry::Symlink { target, .. } = entry
1187                            {
1188                                let mut target = target.clone();
1189                                target.extend(path_components);
1190                                path = target;
1191                                continue 'outer;
1192                            }
1193                            entry_stack.push(entry);
1194                            canonical_path = canonical_path.join(name);
1195                        } else {
1196                            return None;
1197                        }
1198                    }
1199                }
1200            }
1201            break;
1202        }
1203
1204        if entry_stack.is_empty() {
1205            None
1206        } else {
1207            Some(canonical_path)
1208        }
1209    }
1210
1211    fn try_entry(
1212        &mut self,
1213        target: &Path,
1214        follow_symlink: bool,
1215    ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1216        let canonical_path = self.canonicalize(target, follow_symlink)?;
1217
1218        let mut components = canonical_path
1219            .components()
1220            .skip_while(|component| matches!(component, Component::Prefix(_)));
1221        let Some(Component::RootDir) = components.next() else {
1222            panic!(
1223                "the path {:?} was not canonicalized properly {:?}",
1224                target, canonical_path
1225            )
1226        };
1227
1228        let mut entry = &mut self.root;
1229        for component in components {
1230            match component {
1231                Component::Normal(name) => {
1232                    if let FakeFsEntry::Dir { entries, .. } = entry {
1233                        entry = entries.get_mut(name.to_str().unwrap())?;
1234                    } else {
1235                        return None;
1236                    }
1237                }
1238                _ => {
1239                    panic!(
1240                        "the path {:?} was not canonicalized properly {:?}",
1241                        target, canonical_path
1242                    )
1243                }
1244            }
1245        }
1246
1247        Some((entry, canonical_path))
1248    }
1249
1250    fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1251        Ok(self
1252            .try_entry(target, true)
1253            .ok_or_else(|| {
1254                anyhow!(io::Error::new(
1255                    io::ErrorKind::NotFound,
1256                    format!("not found: {target:?}")
1257                ))
1258            })?
1259            .0)
1260    }
1261
1262    fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1263    where
1264        Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1265    {
1266        let path = normalize_path(path);
1267        let filename = path.file_name().context("cannot overwrite the root")?;
1268        let parent_path = path.parent().unwrap();
1269
1270        let parent = self.entry(parent_path)?;
1271        let new_entry = parent
1272            .dir_entries(parent_path)?
1273            .entry(filename.to_str().unwrap().into());
1274        callback(new_entry)
1275    }
1276
1277    fn emit_event<I, T>(&mut self, paths: I)
1278    where
1279        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1280        T: Into<PathBuf>,
1281    {
1282        self.buffered_events
1283            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1284                path: path.into(),
1285                kind,
1286            }));
1287
1288        if !self.events_paused {
1289            self.flush_events(self.buffered_events.len());
1290        }
1291    }
1292
1293    fn flush_events(&mut self, mut count: usize) {
1294        count = count.min(self.buffered_events.len());
1295        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1296        self.event_txs.retain(|(_, tx)| {
1297            let _ = tx.try_send(events.clone());
1298            !tx.is_closed()
1299        });
1300    }
1301}
1302
1303#[cfg(any(test, feature = "test-support"))]
1304pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1305    std::sync::LazyLock::new(|| OsStr::new(".git"));
1306
1307#[cfg(any(test, feature = "test-support"))]
1308impl FakeFs {
1309    /// We need to use something large enough for Windows and Unix to consider this a new file.
1310    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1311    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1312
1313    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1314        let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1315
1316        let this = Arc::new_cyclic(|this| Self {
1317            this: this.clone(),
1318            executor: executor.clone(),
1319            state: Arc::new(Mutex::new(FakeFsState {
1320                root: FakeFsEntry::Dir {
1321                    inode: 0,
1322                    mtime: MTime(UNIX_EPOCH),
1323                    len: 0,
1324                    entries: Default::default(),
1325                    git_repo_state: None,
1326                },
1327                git_event_tx: tx,
1328                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1329                next_inode: 1,
1330                event_txs: Default::default(),
1331                buffered_events: Vec::new(),
1332                events_paused: false,
1333                read_dir_call_count: 0,
1334                metadata_call_count: 0,
1335                path_write_counts: Default::default(),
1336                moves: Default::default(),
1337            })),
1338        });
1339
1340        executor.spawn({
1341            let this = this.clone();
1342            async move {
1343                while let Ok(git_event) = rx.recv().await {
1344                    if let Some(mut state) = this.state.try_lock() {
1345                        state.emit_event([(git_event, Some(PathEventKind::Changed))]);
1346                    } else {
1347                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1348                    }
1349                }
1350            }
1351        }).detach();
1352
1353        this
1354    }
1355
1356    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1357        let mut state = self.state.lock();
1358        state.next_mtime = next_mtime;
1359    }
1360
1361    pub fn get_and_increment_mtime(&self) -> MTime {
1362        let mut state = self.state.lock();
1363        state.get_and_increment_mtime()
1364    }
1365
1366    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1367        let mut state = self.state.lock();
1368        let path = path.as_ref();
1369        let new_mtime = state.get_and_increment_mtime();
1370        let new_inode = state.get_and_increment_inode();
1371        state
1372            .write_path(path, move |entry| {
1373                match entry {
1374                    btree_map::Entry::Vacant(e) => {
1375                        e.insert(FakeFsEntry::File {
1376                            inode: new_inode,
1377                            mtime: new_mtime,
1378                            content: Vec::new(),
1379                            len: 0,
1380                            git_dir_path: None,
1381                        });
1382                    }
1383                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1384                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1385                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1386                        FakeFsEntry::Symlink { .. } => {}
1387                    },
1388                }
1389                Ok(())
1390            })
1391            .unwrap();
1392        state.emit_event([(path.to_path_buf(), Some(PathEventKind::Changed))]);
1393    }
1394
1395    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1396        self.write_file_internal(path, content, true).unwrap()
1397    }
1398
1399    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1400        let mut state = self.state.lock();
1401        let path = path.as_ref();
1402        let file = FakeFsEntry::Symlink { target };
1403        state
1404            .write_path(path.as_ref(), move |e| match e {
1405                btree_map::Entry::Vacant(e) => {
1406                    e.insert(file);
1407                    Ok(())
1408                }
1409                btree_map::Entry::Occupied(mut e) => {
1410                    *e.get_mut() = file;
1411                    Ok(())
1412                }
1413            })
1414            .unwrap();
1415        state.emit_event([(path, Some(PathEventKind::Created))]);
1416    }
1417
1418    fn write_file_internal(
1419        &self,
1420        path: impl AsRef<Path>,
1421        new_content: Vec<u8>,
1422        recreate_inode: bool,
1423    ) -> Result<()> {
1424        let mut state = self.state.lock();
1425        let path_buf = path.as_ref().to_path_buf();
1426        *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1427        let new_inode = state.get_and_increment_inode();
1428        let new_mtime = state.get_and_increment_mtime();
1429        let new_len = new_content.len() as u64;
1430        let mut kind = None;
1431        state.write_path(path.as_ref(), |entry| {
1432            match entry {
1433                btree_map::Entry::Vacant(e) => {
1434                    kind = Some(PathEventKind::Created);
1435                    e.insert(FakeFsEntry::File {
1436                        inode: new_inode,
1437                        mtime: new_mtime,
1438                        len: new_len,
1439                        content: new_content,
1440                        git_dir_path: None,
1441                    });
1442                }
1443                btree_map::Entry::Occupied(mut e) => {
1444                    kind = Some(PathEventKind::Changed);
1445                    if let FakeFsEntry::File {
1446                        inode,
1447                        mtime,
1448                        len,
1449                        content,
1450                        ..
1451                    } = e.get_mut()
1452                    {
1453                        *mtime = new_mtime;
1454                        *content = new_content;
1455                        *len = new_len;
1456                        if recreate_inode {
1457                            *inode = new_inode;
1458                        }
1459                    } else {
1460                        anyhow::bail!("not a file")
1461                    }
1462                }
1463            }
1464            Ok(())
1465        })?;
1466        state.emit_event([(path.as_ref(), kind)]);
1467        Ok(())
1468    }
1469
1470    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1471        let path = path.as_ref();
1472        let path = normalize_path(path);
1473        let mut state = self.state.lock();
1474        let entry = state.entry(&path)?;
1475        entry.file_content(&path).cloned()
1476    }
1477
1478    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1479        let path = path.as_ref();
1480        let path = normalize_path(path);
1481        self.simulate_random_delay().await;
1482        let mut state = self.state.lock();
1483        let entry = state.entry(&path)?;
1484        entry.file_content(&path).cloned()
1485    }
1486
1487    pub fn pause_events(&self) {
1488        self.state.lock().events_paused = true;
1489    }
1490
1491    pub fn unpause_events_and_flush(&self) {
1492        self.state.lock().events_paused = false;
1493        self.flush_events(usize::MAX);
1494    }
1495
1496    pub fn buffered_event_count(&self) -> usize {
1497        self.state.lock().buffered_events.len()
1498    }
1499
1500    pub fn flush_events(&self, count: usize) {
1501        self.state.lock().flush_events(count);
1502    }
1503
1504    pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1505        self.state.lock().entry(target).cloned()
1506    }
1507
1508    pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1509        let mut state = self.state.lock();
1510        state.write_path(target, |entry| {
1511            match entry {
1512                btree_map::Entry::Vacant(vacant_entry) => {
1513                    vacant_entry.insert(new_entry);
1514                }
1515                btree_map::Entry::Occupied(mut occupied_entry) => {
1516                    occupied_entry.insert(new_entry);
1517                }
1518            }
1519            Ok(())
1520        })
1521    }
1522
1523    #[must_use]
1524    pub fn insert_tree<'a>(
1525        &'a self,
1526        path: impl 'a + AsRef<Path> + Send,
1527        tree: serde_json::Value,
1528    ) -> futures::future::BoxFuture<'a, ()> {
1529        use futures::FutureExt as _;
1530        use serde_json::Value::*;
1531
1532        async move {
1533            let path = path.as_ref();
1534
1535            match tree {
1536                Object(map) => {
1537                    self.create_dir(path).await.unwrap();
1538                    for (name, contents) in map {
1539                        let mut path = PathBuf::from(path);
1540                        path.push(name);
1541                        self.insert_tree(&path, contents).await;
1542                    }
1543                }
1544                Null => {
1545                    self.create_dir(path).await.unwrap();
1546                }
1547                String(contents) => {
1548                    self.insert_file(&path, contents.into_bytes()).await;
1549                }
1550                _ => {
1551                    panic!("JSON object must contain only objects, strings, or null");
1552                }
1553            }
1554        }
1555        .boxed()
1556    }
1557
1558    pub fn insert_tree_from_real_fs<'a>(
1559        &'a self,
1560        path: impl 'a + AsRef<Path> + Send,
1561        src_path: impl 'a + AsRef<Path> + Send,
1562    ) -> futures::future::BoxFuture<'a, ()> {
1563        use futures::FutureExt as _;
1564
1565        async move {
1566            let path = path.as_ref();
1567            if std::fs::metadata(&src_path).unwrap().is_file() {
1568                let contents = std::fs::read(src_path).unwrap();
1569                self.insert_file(path, contents).await;
1570            } else {
1571                self.create_dir(path).await.unwrap();
1572                for entry in std::fs::read_dir(&src_path).unwrap() {
1573                    let entry = entry.unwrap();
1574                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1575                        .await;
1576                }
1577            }
1578        }
1579        .boxed()
1580    }
1581
1582    pub fn with_git_state_and_paths<T, F>(
1583        &self,
1584        dot_git: &Path,
1585        emit_git_event: bool,
1586        f: F,
1587    ) -> Result<T>
1588    where
1589        F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1590    {
1591        let mut state = self.state.lock();
1592        let git_event_tx = state.git_event_tx.clone();
1593        let entry = state.entry(dot_git).context("open .git")?;
1594
1595        if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1596            let repo_state = git_repo_state.get_or_insert_with(|| {
1597                log::debug!("insert git state for {dot_git:?}");
1598                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1599            });
1600            let mut repo_state = repo_state.lock();
1601
1602            let result = f(&mut repo_state, dot_git, dot_git);
1603
1604            drop(repo_state);
1605            if emit_git_event {
1606                state.emit_event([(dot_git, Some(PathEventKind::Changed))]);
1607            }
1608
1609            Ok(result)
1610        } else if let FakeFsEntry::File {
1611            content,
1612            git_dir_path,
1613            ..
1614        } = &mut *entry
1615        {
1616            let path = match git_dir_path {
1617                Some(path) => path,
1618                None => {
1619                    let path = std::str::from_utf8(content)
1620                        .ok()
1621                        .and_then(|content| content.strip_prefix("gitdir:"))
1622                        .context("not a valid gitfile")?
1623                        .trim();
1624                    git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1625                }
1626            }
1627            .clone();
1628            let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1629                anyhow::bail!("pointed-to git dir {path:?} not found")
1630            };
1631            let FakeFsEntry::Dir {
1632                git_repo_state,
1633                entries,
1634                ..
1635            } = git_dir_entry
1636            else {
1637                anyhow::bail!("gitfile points to a non-directory")
1638            };
1639            let common_dir = if let Some(child) = entries.get("commondir") {
1640                Path::new(
1641                    std::str::from_utf8(child.file_content("commondir".as_ref())?)
1642                        .context("commondir content")?,
1643                )
1644                .to_owned()
1645            } else {
1646                canonical_path.clone()
1647            };
1648            let repo_state = git_repo_state.get_or_insert_with(|| {
1649                Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1650            });
1651            let mut repo_state = repo_state.lock();
1652
1653            let result = f(&mut repo_state, &canonical_path, &common_dir);
1654
1655            if emit_git_event {
1656                drop(repo_state);
1657                state.emit_event([(canonical_path, Some(PathEventKind::Changed))]);
1658            }
1659
1660            Ok(result)
1661        } else {
1662            anyhow::bail!("not a valid git repository");
1663        }
1664    }
1665
1666    pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1667    where
1668        F: FnOnce(&mut FakeGitRepositoryState) -> T,
1669    {
1670        self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1671    }
1672
1673    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1674        self.with_git_state(dot_git, true, |state| {
1675            let branch = branch.map(Into::into);
1676            state.branches.extend(branch.clone());
1677            state.current_branch_name = branch
1678        })
1679        .unwrap();
1680    }
1681
1682    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1683        self.with_git_state(dot_git, true, |state| {
1684            if let Some(first) = branches.first()
1685                && state.current_branch_name.is_none()
1686            {
1687                state.current_branch_name = Some(first.to_string())
1688            }
1689            state
1690                .branches
1691                .extend(branches.iter().map(ToString::to_string));
1692        })
1693        .unwrap();
1694    }
1695
1696    pub fn set_unmerged_paths_for_repo(
1697        &self,
1698        dot_git: &Path,
1699        unmerged_state: &[(RepoPath, UnmergedStatus)],
1700    ) {
1701        self.with_git_state(dot_git, true, |state| {
1702            state.unmerged_paths.clear();
1703            state.unmerged_paths.extend(
1704                unmerged_state
1705                    .iter()
1706                    .map(|(path, content)| (path.clone(), *content)),
1707            );
1708        })
1709        .unwrap();
1710    }
1711
1712    pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(&str, String)]) {
1713        self.with_git_state(dot_git, true, |state| {
1714            state.index_contents.clear();
1715            state.index_contents.extend(
1716                index_state
1717                    .iter()
1718                    .map(|(path, content)| (repo_path(path), content.clone())),
1719            );
1720        })
1721        .unwrap();
1722    }
1723
1724    pub fn set_head_for_repo(
1725        &self,
1726        dot_git: &Path,
1727        head_state: &[(&str, String)],
1728        sha: impl Into<String>,
1729    ) {
1730        self.with_git_state(dot_git, true, |state| {
1731            state.head_contents.clear();
1732            state.head_contents.extend(
1733                head_state
1734                    .iter()
1735                    .map(|(path, content)| (repo_path(path), content.clone())),
1736            );
1737            state.refs.insert("HEAD".into(), sha.into());
1738        })
1739        .unwrap();
1740    }
1741
1742    pub fn set_head_and_index_for_repo(&self, dot_git: &Path, contents_by_path: &[(&str, String)]) {
1743        self.with_git_state(dot_git, true, |state| {
1744            state.head_contents.clear();
1745            state.head_contents.extend(
1746                contents_by_path
1747                    .iter()
1748                    .map(|(path, contents)| (repo_path(path), contents.clone())),
1749            );
1750            state.index_contents = state.head_contents.clone();
1751        })
1752        .unwrap();
1753    }
1754
1755    pub fn set_merge_base_content_for_repo(
1756        &self,
1757        dot_git: &Path,
1758        contents_by_path: &[(&str, String)],
1759    ) {
1760        self.with_git_state(dot_git, true, |state| {
1761            use git::Oid;
1762
1763            state.merge_base_contents.clear();
1764            let oids = (1..)
1765                .map(|n| n.to_string())
1766                .map(|n| Oid::from_bytes(n.repeat(20).as_bytes()).unwrap());
1767            for ((path, content), oid) in contents_by_path.iter().zip(oids) {
1768                state.merge_base_contents.insert(repo_path(path), oid);
1769                state.oids.insert(oid, content.clone());
1770            }
1771        })
1772        .unwrap();
1773    }
1774
1775    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1776        self.with_git_state(dot_git, true, |state| {
1777            state.blames.clear();
1778            state.blames.extend(blames);
1779        })
1780        .unwrap();
1781    }
1782
1783    /// Put the given git repository into a state with the given status,
1784    /// by mutating the head, index, and unmerged state.
1785    pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&str, FileStatus)]) {
1786        let workdir_path = dot_git.parent().unwrap();
1787        let workdir_contents = self.files_with_contents(workdir_path);
1788        self.with_git_state(dot_git, true, |state| {
1789            state.index_contents.clear();
1790            state.head_contents.clear();
1791            state.unmerged_paths.clear();
1792            for (path, content) in workdir_contents {
1793                use util::{paths::PathStyle, rel_path::RelPath};
1794
1795                let repo_path: RepoPath = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap().into();
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}