fs.rs

   1#[cfg(target_os = "macos")]
   2mod mac_watcher;
   3
   4#[cfg(not(target_os = "macos"))]
   5pub mod fs_watcher;
   6
   7use anyhow::{Context as _, Result, anyhow};
   8#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   9use ashpd::desktop::trash;
  10use futures::stream::iter;
  11use gpui::App;
  12use gpui::BackgroundExecutor;
  13use gpui::Global;
  14use gpui::ReadGlobal as _;
  15use std::borrow::Cow;
  16use util::command::new_smol_command;
  17
  18#[cfg(unix)]
  19use std::os::fd::{AsFd, AsRawFd};
  20
  21#[cfg(unix)]
  22use std::os::unix::fs::{FileTypeExt, MetadataExt};
  23
  24#[cfg(any(target_os = "macos", target_os = "freebsd"))]
  25use std::mem::MaybeUninit;
  26
  27use async_tar::Archive;
  28use futures::{AsyncRead, Stream, StreamExt, future::BoxFuture};
  29use git::repository::{GitRepository, RealGitRepository};
  30use rope::Rope;
  31use serde::{Deserialize, Serialize};
  32use smol::io::AsyncWriteExt;
  33use std::{
  34    io::{self, Write},
  35    path::{Component, Path, PathBuf},
  36    pin::Pin,
  37    sync::Arc,
  38    time::{Duration, SystemTime, UNIX_EPOCH},
  39};
  40use tempfile::TempDir;
  41use text::LineEnding;
  42
  43#[cfg(any(test, feature = "test-support"))]
  44mod fake_git_repo;
  45#[cfg(any(test, feature = "test-support"))]
  46use collections::{BTreeMap, btree_map};
  47#[cfg(any(test, feature = "test-support"))]
  48use fake_git_repo::FakeGitRepositoryState;
  49#[cfg(any(test, feature = "test-support"))]
  50use git::{
  51    repository::{RepoPath, repo_path},
  52    status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus},
  53};
  54#[cfg(any(test, feature = "test-support"))]
  55use parking_lot::Mutex;
  56#[cfg(any(test, feature = "test-support"))]
  57use smol::io::AsyncReadExt;
  58#[cfg(any(test, feature = "test-support"))]
  59use std::ffi::OsStr;
  60
  61#[cfg(any(test, feature = "test-support"))]
  62pub use fake_git_repo::{LOAD_HEAD_TEXT_TASK, LOAD_INDEX_TEXT_TASK};
  63
  64pub trait Watcher: Send + Sync {
  65    fn add(&self, path: &Path) -> Result<()>;
  66    fn remove(&self, path: &Path) -> Result<()>;
  67}
  68
  69#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  70pub enum PathEventKind {
  71    Removed,
  72    Created,
  73    Changed,
  74}
  75
  76#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  77pub struct PathEvent {
  78    pub path: PathBuf,
  79    pub kind: Option<PathEventKind>,
  80}
  81
  82impl From<PathEvent> for PathBuf {
  83    fn from(event: PathEvent) -> Self {
  84        event.path
  85    }
  86}
  87
  88#[async_trait::async_trait]
  89pub trait Fs: Send + Sync {
  90    async fn create_dir(&self, path: &Path) -> Result<()>;
  91    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  92    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  93    async fn create_file_with(
  94        &self,
  95        path: &Path,
  96        content: Pin<&mut (dyn AsyncRead + Send)>,
  97    ) -> Result<()>;
  98    async fn extract_tar_file(
  99        &self,
 100        path: &Path,
 101        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 102    ) -> Result<()>;
 103    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
 104    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
 105    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 106    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 107        self.remove_dir(path, options).await
 108    }
 109    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 110    async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 111        self.remove_file(path, options).await
 112    }
 113    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
 114    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>>;
 115    async fn load(&self, path: &Path) -> Result<String> {
 116        Ok(String::from_utf8(self.load_bytes(path).await?)?)
 117    }
 118    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
 119    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 120    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
 121    async fn write(&self, path: &Path, content: &[u8]) -> Result<()>;
 122    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 123    async fn is_file(&self, path: &Path) -> bool;
 124    async fn is_dir(&self, path: &Path) -> bool;
 125    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 126    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 127    async fn read_dir(
 128        &self,
 129        path: &Path,
 130    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 131
 132    async fn watch(
 133        &self,
 134        path: &Path,
 135        latency: Duration,
 136    ) -> (
 137        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 138        Arc<dyn Watcher>,
 139    );
 140
 141    fn open_repo(
 142        &self,
 143        abs_dot_git: &Path,
 144        system_git_binary_path: Option<&Path>,
 145    ) -> Option<Arc<dyn GitRepository>>;
 146    async fn git_init(&self, abs_work_directory: &Path, fallback_branch_name: String)
 147    -> Result<()>;
 148    async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()>;
 149    fn is_fake(&self) -> bool;
 150    async fn is_case_sensitive(&self) -> Result<bool>;
 151
 152    #[cfg(any(test, feature = "test-support"))]
 153    fn as_fake(&self) -> Arc<FakeFs> {
 154        panic!("called as_fake on a real fs");
 155    }
 156}
 157
 158struct GlobalFs(Arc<dyn Fs>);
 159
 160impl Global for GlobalFs {}
 161
 162impl dyn Fs {
 163    /// Returns the global [`Fs`].
 164    pub fn global(cx: &App) -> Arc<Self> {
 165        GlobalFs::global(cx).0.clone()
 166    }
 167
 168    /// Sets the global [`Fs`].
 169    pub fn set_global(fs: Arc<Self>, cx: &mut App) {
 170        cx.set_global(GlobalFs(fs));
 171    }
 172}
 173
 174#[derive(Copy, Clone, Default)]
 175pub struct CreateOptions {
 176    pub overwrite: bool,
 177    pub ignore_if_exists: bool,
 178}
 179
 180#[derive(Copy, Clone, Default)]
 181pub struct CopyOptions {
 182    pub overwrite: bool,
 183    pub ignore_if_exists: bool,
 184}
 185
 186#[derive(Copy, Clone, Default)]
 187pub struct RenameOptions {
 188    pub overwrite: bool,
 189    pub ignore_if_exists: bool,
 190}
 191
 192#[derive(Copy, Clone, Default)]
 193pub struct RemoveOptions {
 194    pub recursive: bool,
 195    pub ignore_if_not_exists: bool,
 196}
 197
 198#[derive(Copy, Clone, Debug)]
 199pub struct Metadata {
 200    pub inode: u64,
 201    pub mtime: MTime,
 202    pub is_symlink: bool,
 203    pub is_dir: bool,
 204    pub len: u64,
 205    pub is_fifo: bool,
 206}
 207
 208/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
 209/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
 210/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
 211/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
 212///
 213/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
 214#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
 215#[serde(transparent)]
 216pub struct MTime(SystemTime);
 217
 218impl MTime {
 219    /// Conversion intended for persistence and testing.
 220    pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
 221        MTime(UNIX_EPOCH + Duration::new(secs, nanos))
 222    }
 223
 224    /// Conversion intended for persistence.
 225    pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
 226        self.0
 227            .duration_since(UNIX_EPOCH)
 228            .ok()
 229            .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
 230    }
 231
 232    /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
 233    /// "_for_user" is to discourage misuse - this method should not be used when making decisions
 234    /// about file dirtiness.
 235    pub fn timestamp_for_user(self) -> SystemTime {
 236        self.0
 237    }
 238
 239    /// Temporary method to split out the behavior changes from introduction of this newtype.
 240    pub fn bad_is_greater_than(self, other: MTime) -> bool {
 241        self.0 > other.0
 242    }
 243}
 244
 245impl From<proto::Timestamp> for MTime {
 246    fn from(timestamp: proto::Timestamp) -> Self {
 247        MTime(timestamp.into())
 248    }
 249}
 250
 251impl From<MTime> for proto::Timestamp {
 252    fn from(mtime: MTime) -> Self {
 253        mtime.0.into()
 254    }
 255}
 256
 257pub struct RealFs {
 258    bundled_git_binary_path: Option<PathBuf>,
 259    executor: BackgroundExecutor,
 260}
 261
 262pub trait FileHandle: Send + Sync + std::fmt::Debug {
 263    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
 264}
 265
 266impl FileHandle for std::fs::File {
 267    #[cfg(target_os = "macos")]
 268    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 269        use std::{
 270            ffi::{CStr, OsStr},
 271            os::unix::ffi::OsStrExt,
 272        };
 273
 274        let fd = self.as_fd();
 275        let mut path_buf = MaybeUninit::<[u8; libc::PATH_MAX as usize]>::uninit();
 276
 277        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
 278        if result == -1 {
 279            anyhow::bail!("fcntl returned -1".to_string());
 280        }
 281
 282        // SAFETY: `fcntl` will initialize the path buffer.
 283        let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr().cast()) };
 284        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 285        Ok(path)
 286    }
 287
 288    #[cfg(target_os = "linux")]
 289    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 290        let fd = self.as_fd();
 291        let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
 292        let new_path = std::fs::read_link(fd_path)?;
 293        if new_path
 294            .file_name()
 295            .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
 296        {
 297            anyhow::bail!("file was deleted")
 298        };
 299
 300        Ok(new_path)
 301    }
 302
 303    #[cfg(target_os = "freebsd")]
 304    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 305        use std::{
 306            ffi::{CStr, OsStr},
 307            os::unix::ffi::OsStrExt,
 308        };
 309
 310        let fd = self.as_fd();
 311        let mut kif = MaybeUninit::<libc::kinfo_file>::uninit();
 312        kif.kf_structsize = libc::KINFO_FILE_SIZE;
 313
 314        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_KINFO, kif.as_mut_ptr()) };
 315        if result == -1 {
 316            anyhow::bail!("fcntl returned -1".to_string());
 317        }
 318
 319        // SAFETY: `fcntl` will initialize the kif.
 320        let c_str = unsafe { CStr::from_ptr(kif.assume_init().kf_path.as_ptr()) };
 321        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 322        Ok(path)
 323    }
 324
 325    #[cfg(target_os = "windows")]
 326    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 327        use std::ffi::OsString;
 328        use std::os::windows::ffi::OsStringExt;
 329        use std::os::windows::io::AsRawHandle;
 330
 331        use windows::Win32::Foundation::HANDLE;
 332        use windows::Win32::Storage::FileSystem::{
 333            FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW,
 334        };
 335
 336        let handle = HANDLE(self.as_raw_handle() as _);
 337
 338        // Query required buffer size (in wide chars)
 339        let required_len =
 340            unsafe { GetFinalPathNameByHandleW(handle, &mut [], FILE_NAME_NORMALIZED) };
 341        if required_len == 0 {
 342            anyhow::bail!("GetFinalPathNameByHandleW returned 0 length");
 343        }
 344
 345        // Allocate buffer and retrieve the path
 346        let mut buf: Vec<u16> = vec![0u16; required_len as usize + 1];
 347        let written = unsafe { GetFinalPathNameByHandleW(handle, &mut buf, FILE_NAME_NORMALIZED) };
 348        if written == 0 {
 349            anyhow::bail!("GetFinalPathNameByHandleW failed to write path");
 350        }
 351
 352        let os_str: OsString = OsString::from_wide(&buf[..written as usize]);
 353        Ok(PathBuf::from(os_str))
 354    }
 355}
 356
 357pub struct RealWatcher {}
 358
 359impl RealFs {
 360    pub fn new(git_binary_path: Option<PathBuf>, executor: BackgroundExecutor) -> Self {
 361        Self {
 362            bundled_git_binary_path: git_binary_path,
 363            executor,
 364        }
 365    }
 366}
 367
 368#[async_trait::async_trait]
 369impl Fs for RealFs {
 370    async fn create_dir(&self, path: &Path) -> Result<()> {
 371        Ok(smol::fs::create_dir_all(path).await?)
 372    }
 373
 374    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 375        #[cfg(unix)]
 376        smol::fs::unix::symlink(target, path).await?;
 377
 378        #[cfg(windows)]
 379        if smol::fs::metadata(&target).await?.is_dir() {
 380            let status = new_smol_command("cmd")
 381                .args(["/C", "mklink", "/J"])
 382                .args([path, target.as_path()])
 383                .status()
 384                .await?;
 385
 386            if !status.success() {
 387                return Err(anyhow::anyhow!(
 388                    "Failed to create junction from {:?} to {:?}",
 389                    path,
 390                    target
 391                ));
 392            }
 393        } else {
 394            smol::fs::windows::symlink_file(target, path).await?
 395        }
 396
 397        Ok(())
 398    }
 399
 400    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 401        let mut open_options = smol::fs::OpenOptions::new();
 402        open_options.write(true).create(true);
 403        if options.overwrite {
 404            open_options.truncate(true);
 405        } else if !options.ignore_if_exists {
 406            open_options.create_new(true);
 407        }
 408        open_options.open(path).await?;
 409        Ok(())
 410    }
 411
 412    async fn create_file_with(
 413        &self,
 414        path: &Path,
 415        content: Pin<&mut (dyn AsyncRead + Send)>,
 416    ) -> Result<()> {
 417        let mut file = smol::fs::File::create(&path).await?;
 418        futures::io::copy(content, &mut file).await?;
 419        Ok(())
 420    }
 421
 422    async fn extract_tar_file(
 423        &self,
 424        path: &Path,
 425        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 426    ) -> Result<()> {
 427        content.unpack(path).await?;
 428        Ok(())
 429    }
 430
 431    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 432        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 433            if options.ignore_if_exists {
 434                return Ok(());
 435            } else {
 436                anyhow::bail!("{target:?} already exists");
 437            }
 438        }
 439
 440        smol::fs::copy(source, target).await?;
 441        Ok(())
 442    }
 443
 444    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 445        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 446            if options.ignore_if_exists {
 447                return Ok(());
 448            } else {
 449                anyhow::bail!("{target:?} already exists");
 450            }
 451        }
 452
 453        smol::fs::rename(source, target).await?;
 454        Ok(())
 455    }
 456
 457    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 458        let result = if options.recursive {
 459            smol::fs::remove_dir_all(path).await
 460        } else {
 461            smol::fs::remove_dir(path).await
 462        };
 463        match result {
 464            Ok(()) => Ok(()),
 465            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 466                Ok(())
 467            }
 468            Err(err) => Err(err)?,
 469        }
 470    }
 471
 472    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 473        #[cfg(windows)]
 474        if let Ok(Some(metadata)) = self.metadata(path).await
 475            && metadata.is_symlink
 476            && metadata.is_dir
 477        {
 478            self.remove_dir(
 479                path,
 480                RemoveOptions {
 481                    recursive: false,
 482                    ignore_if_not_exists: true,
 483                },
 484            )
 485            .await?;
 486            return Ok(());
 487        }
 488
 489        match smol::fs::remove_file(path).await {
 490            Ok(()) => Ok(()),
 491            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 492                Ok(())
 493            }
 494            Err(err) => Err(err)?,
 495        }
 496    }
 497
 498    #[cfg(target_os = "macos")]
 499    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 500        use cocoa::{
 501            base::{id, nil},
 502            foundation::{NSAutoreleasePool, NSString},
 503        };
 504        use objc::{class, msg_send, sel, sel_impl};
 505
 506        unsafe {
 507            unsafe fn ns_string(string: &str) -> id {
 508                unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 509            }
 510
 511            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 512            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 513            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 514
 515            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 516        }
 517        Ok(())
 518    }
 519
 520    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 521    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 522        if let Ok(Some(metadata)) = self.metadata(path).await
 523            && metadata.is_symlink
 524        {
 525            // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
 526            return self.remove_file(path, RemoveOptions::default()).await;
 527        }
 528        let file = smol::fs::File::open(path).await?;
 529        match trash::trash_file(&file.as_fd()).await {
 530            Ok(_) => Ok(()),
 531            Err(err) => {
 532                log::error!("Failed to trash file: {}", err);
 533                // Trashing files can fail if you don't have a trashing dbus service configured.
 534                // In that case, delete the file directly instead.
 535                return self.remove_file(path, RemoveOptions::default()).await;
 536            }
 537        }
 538    }
 539
 540    #[cfg(target_os = "windows")]
 541    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 542        use util::paths::SanitizedPath;
 543        use windows::{
 544            Storage::{StorageDeleteOption, StorageFile},
 545            core::HSTRING,
 546        };
 547        // todo(windows)
 548        // When new version of `windows-rs` release, make this operation `async`
 549        let path = path.canonicalize()?;
 550        let path = SanitizedPath::new(&path);
 551        let path_string = path.to_string();
 552        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 553        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 554        Ok(())
 555    }
 556
 557    #[cfg(target_os = "macos")]
 558    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 559        self.trash_file(path, options).await
 560    }
 561
 562    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 563    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 564        self.trash_file(path, options).await
 565    }
 566
 567    #[cfg(target_os = "windows")]
 568    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 569        use util::paths::SanitizedPath;
 570        use windows::{
 571            Storage::{StorageDeleteOption, StorageFolder},
 572            core::HSTRING,
 573        };
 574
 575        // todo(windows)
 576        // When new version of `windows-rs` release, make this operation `async`
 577        let path = path.canonicalize()?;
 578        let path = SanitizedPath::new(&path);
 579        let path_string = path.to_string();
 580        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 581        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 582        Ok(())
 583    }
 584
 585    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
 586        Ok(Box::new(std::fs::File::open(path)?))
 587    }
 588
 589    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 590        let mut options = std::fs::OpenOptions::new();
 591        options.read(true);
 592        #[cfg(windows)]
 593        {
 594            use std::os::windows::fs::OpenOptionsExt;
 595            options.custom_flags(windows::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS.0);
 596        }
 597        Ok(Arc::new(options.open(path)?))
 598    }
 599
 600    async fn load(&self, path: &Path) -> Result<String> {
 601        let path = path.to_path_buf();
 602        self.executor
 603            .spawn(async move { Ok(std::fs::read_to_string(path)?) })
 604            .await
 605    }
 606
 607    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 608        let path = path.to_path_buf();
 609        let bytes = self
 610            .executor
 611            .spawn(async move { std::fs::read(path) })
 612            .await?;
 613        Ok(bytes)
 614    }
 615
 616    #[cfg(not(target_os = "windows"))]
 617    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 618        smol::unblock(move || {
 619            // Use the directory of the destination as temp dir to avoid
 620            // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 621            // See https://github.com/zed-industries/zed/pull/8437 for more details.
 622            let mut tmp_file =
 623                tempfile::NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 624            tmp_file.write_all(data.as_bytes())?;
 625            tmp_file.persist(path)?;
 626            anyhow::Ok(())
 627        })
 628        .await?;
 629
 630        Ok(())
 631    }
 632
 633    #[cfg(target_os = "windows")]
 634    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 635        smol::unblock(move || {
 636            // If temp dir is set to a different drive than the destination,
 637            // we receive error:
 638            //
 639            // failed to persist temporary file:
 640            // The system cannot move the file to a different disk drive. (os error 17)
 641            //
 642            // This is because `ReplaceFileW` does not support cross volume moves.
 643            // See the remark section: "The backup file, replaced file, and replacement file must all reside on the same volume."
 644            // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew#remarks
 645            //
 646            // So we use the directory of the destination as a temp dir to avoid it.
 647            // https://github.com/zed-industries/zed/issues/16571
 648            let temp_dir = TempDir::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
 649            let temp_file = {
 650                let temp_file_path = temp_dir.path().join("temp_file");
 651                let mut file = std::fs::File::create_new(&temp_file_path)?;
 652                file.write_all(data.as_bytes())?;
 653                temp_file_path
 654            };
 655            atomic_replace(path.as_path(), temp_file.as_path())?;
 656            anyhow::Ok(())
 657        })
 658        .await?;
 659        Ok(())
 660    }
 661
 662    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 663        let buffer_size = text.summary().len.min(10 * 1024);
 664        if let Some(path) = path.parent() {
 665            self.create_dir(path).await?;
 666        }
 667        let file = smol::fs::File::create(path).await?;
 668        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 669        for chunk in chunks(text, line_ending) {
 670            writer.write_all(chunk.as_bytes()).await?;
 671        }
 672        writer.flush().await?;
 673        Ok(())
 674    }
 675
 676    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
 677        if let Some(path) = path.parent() {
 678            self.create_dir(path).await?;
 679        }
 680        let path = path.to_owned();
 681        let contents = content.to_owned();
 682        self.executor
 683            .spawn(async move {
 684                std::fs::write(path, contents)?;
 685                Ok(())
 686            })
 687            .await
 688    }
 689
 690    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 691        let path = path.to_owned();
 692        self.executor
 693            .spawn(async move {
 694                std::fs::canonicalize(&path).with_context(|| format!("canonicalizing {path:?}"))
 695            })
 696            .await
 697    }
 698
 699    async fn is_file(&self, path: &Path) -> bool {
 700        let path = path.to_owned();
 701        self.executor
 702            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) })
 703            .await
 704    }
 705
 706    async fn is_dir(&self, path: &Path) -> bool {
 707        let path = path.to_owned();
 708        self.executor
 709            .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_dir()) })
 710            .await
 711    }
 712
 713    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 714        let path_buf = path.to_owned();
 715        let symlink_metadata = match self
 716            .executor
 717            .spawn(async move { std::fs::symlink_metadata(&path_buf) })
 718            .await
 719        {
 720            Ok(metadata) => metadata,
 721            Err(err) => {
 722                return match (err.kind(), 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 = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap();
1796                let repo_path = RepoPath::from_rel_path(&repo_path);
1797                let status = statuses
1798                    .iter()
1799                    .find_map(|(p, status)| (*p == repo_path.as_unix_str()).then_some(status));
1800                let mut content = String::from_utf8_lossy(&content).to_string();
1801
1802                let mut index_content = None;
1803                let mut head_content = None;
1804                match status {
1805                    None => {
1806                        index_content = Some(content.clone());
1807                        head_content = Some(content);
1808                    }
1809                    Some(FileStatus::Untracked | FileStatus::Ignored) => {}
1810                    Some(FileStatus::Unmerged(unmerged_status)) => {
1811                        state
1812                            .unmerged_paths
1813                            .insert(repo_path.clone(), *unmerged_status);
1814                        content.push_str(" (unmerged)");
1815                        index_content = Some(content.clone());
1816                        head_content = Some(content);
1817                    }
1818                    Some(FileStatus::Tracked(TrackedStatus {
1819                        index_status,
1820                        worktree_status,
1821                    })) => {
1822                        match worktree_status {
1823                            StatusCode::Modified => {
1824                                let mut content = content.clone();
1825                                content.push_str(" (modified in working copy)");
1826                                index_content = Some(content);
1827                            }
1828                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1829                                index_content = Some(content.clone());
1830                            }
1831                            StatusCode::Added => {}
1832                            StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
1833                                panic!("cannot create these statuses for an existing file");
1834                            }
1835                        };
1836                        match index_status {
1837                            StatusCode::Modified => {
1838                                let mut content = index_content.clone().expect(
1839                                    "file cannot be both modified in index and created in working copy",
1840                                );
1841                                content.push_str(" (modified in index)");
1842                                head_content = Some(content);
1843                            }
1844                            StatusCode::TypeChanged | StatusCode::Unmodified => {
1845                                head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
1846                            }
1847                            StatusCode::Added => {}
1848                            StatusCode::Deleted  => {
1849                                head_content = Some("".into());
1850                            }
1851                            StatusCode::Renamed | StatusCode::Copied => {
1852                                panic!("cannot create these statuses for an existing file");
1853                            }
1854                        };
1855                    }
1856                };
1857
1858                if let Some(content) = index_content {
1859                    state.index_contents.insert(repo_path.clone(), content);
1860                }
1861                if let Some(content) = head_content {
1862                    state.head_contents.insert(repo_path.clone(), content);
1863                }
1864            }
1865        }).unwrap();
1866    }
1867
1868    pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
1869        self.with_git_state(dot_git, true, |state| {
1870            state.simulated_index_write_error_message = message;
1871        })
1872        .unwrap();
1873    }
1874
1875    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1876        let mut result = Vec::new();
1877        let mut queue = collections::VecDeque::new();
1878        let state = &*self.state.lock();
1879        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1880        while let Some((path, entry)) = queue.pop_front() {
1881            if let FakeFsEntry::Dir { entries, .. } = entry {
1882                for (name, entry) in entries {
1883                    queue.push_back((path.join(name), entry));
1884                }
1885            }
1886            if include_dot_git
1887                || !path
1888                    .components()
1889                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1890            {
1891                result.push(path);
1892            }
1893        }
1894        result
1895    }
1896
1897    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1898        let mut result = Vec::new();
1899        let mut queue = collections::VecDeque::new();
1900        let state = &*self.state.lock();
1901        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1902        while let Some((path, entry)) = queue.pop_front() {
1903            if let FakeFsEntry::Dir { entries, .. } = entry {
1904                for (name, entry) in entries {
1905                    queue.push_back((path.join(name), entry));
1906                }
1907                if include_dot_git
1908                    || !path
1909                        .components()
1910                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1911                {
1912                    result.push(path);
1913                }
1914            }
1915        }
1916        result
1917    }
1918
1919    pub fn files(&self) -> Vec<PathBuf> {
1920        let mut result = Vec::new();
1921        let mut queue = collections::VecDeque::new();
1922        let state = &*self.state.lock();
1923        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1924        while let Some((path, entry)) = queue.pop_front() {
1925            match entry {
1926                FakeFsEntry::File { .. } => result.push(path),
1927                FakeFsEntry::Dir { entries, .. } => {
1928                    for (name, entry) in entries {
1929                        queue.push_back((path.join(name), entry));
1930                    }
1931                }
1932                FakeFsEntry::Symlink { .. } => {}
1933            }
1934        }
1935        result
1936    }
1937
1938    pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
1939        let mut result = Vec::new();
1940        let mut queue = collections::VecDeque::new();
1941        let state = &*self.state.lock();
1942        queue.push_back((PathBuf::from(util::path!("/")), &state.root));
1943        while let Some((path, entry)) = queue.pop_front() {
1944            match entry {
1945                FakeFsEntry::File { content, .. } => {
1946                    if path.starts_with(prefix) {
1947                        result.push((path, content.clone()));
1948                    }
1949                }
1950                FakeFsEntry::Dir { entries, .. } => {
1951                    for (name, entry) in entries {
1952                        queue.push_back((path.join(name), entry));
1953                    }
1954                }
1955                FakeFsEntry::Symlink { .. } => {}
1956            }
1957        }
1958        result
1959    }
1960
1961    /// How many `read_dir` calls have been issued.
1962    pub fn read_dir_call_count(&self) -> usize {
1963        self.state.lock().read_dir_call_count
1964    }
1965
1966    pub fn watched_paths(&self) -> Vec<PathBuf> {
1967        let state = self.state.lock();
1968        state
1969            .event_txs
1970            .iter()
1971            .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
1972            .collect()
1973    }
1974
1975    /// How many `metadata` calls have been issued.
1976    pub fn metadata_call_count(&self) -> usize {
1977        self.state.lock().metadata_call_count
1978    }
1979
1980    /// How many write operations have been issued for a specific path.
1981    pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
1982        let path = path.as_ref().to_path_buf();
1983        self.state
1984            .lock()
1985            .path_write_counts
1986            .get(&path)
1987            .copied()
1988            .unwrap_or(0)
1989    }
1990
1991    pub fn emit_fs_event(&self, path: impl Into<PathBuf>, event: Option<PathEventKind>) {
1992        self.state.lock().emit_event(std::iter::once((path, event)));
1993    }
1994
1995    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1996        self.executor.simulate_random_delay()
1997    }
1998}
1999
2000#[cfg(any(test, feature = "test-support"))]
2001impl FakeFsEntry {
2002    fn is_file(&self) -> bool {
2003        matches!(self, Self::File { .. })
2004    }
2005
2006    fn is_symlink(&self) -> bool {
2007        matches!(self, Self::Symlink { .. })
2008    }
2009
2010    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
2011        if let Self::File { content, .. } = self {
2012            Ok(content)
2013        } else {
2014            anyhow::bail!("not a file: {path:?}");
2015        }
2016    }
2017
2018    fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
2019        if let Self::Dir { entries, .. } = self {
2020            Ok(entries)
2021        } else {
2022            anyhow::bail!("not a directory: {path:?}");
2023        }
2024    }
2025}
2026
2027#[cfg(any(test, feature = "test-support"))]
2028struct FakeWatcher {
2029    tx: smol::channel::Sender<Vec<PathEvent>>,
2030    original_path: PathBuf,
2031    fs_state: Arc<Mutex<FakeFsState>>,
2032    prefixes: Mutex<Vec<PathBuf>>,
2033}
2034
2035#[cfg(any(test, feature = "test-support"))]
2036impl Watcher for FakeWatcher {
2037    fn add(&self, path: &Path) -> Result<()> {
2038        if path.starts_with(&self.original_path) {
2039            return Ok(());
2040        }
2041        self.fs_state
2042            .try_lock()
2043            .unwrap()
2044            .event_txs
2045            .push((path.to_owned(), self.tx.clone()));
2046        self.prefixes.lock().push(path.to_owned());
2047        Ok(())
2048    }
2049
2050    fn remove(&self, _: &Path) -> Result<()> {
2051        Ok(())
2052    }
2053}
2054
2055#[cfg(any(test, feature = "test-support"))]
2056#[derive(Debug)]
2057struct FakeHandle {
2058    inode: u64,
2059}
2060
2061#[cfg(any(test, feature = "test-support"))]
2062impl FileHandle for FakeHandle {
2063    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
2064        let fs = fs.as_fake();
2065        let mut state = fs.state.lock();
2066        let Some(target) = state.moves.get(&self.inode).cloned() else {
2067            anyhow::bail!("fake fd not moved")
2068        };
2069
2070        if state.try_entry(&target, false).is_some() {
2071            return Ok(target);
2072        }
2073        anyhow::bail!("fake fd target not found")
2074    }
2075}
2076
2077#[cfg(any(test, feature = "test-support"))]
2078#[async_trait::async_trait]
2079impl Fs for FakeFs {
2080    async fn create_dir(&self, path: &Path) -> Result<()> {
2081        self.simulate_random_delay().await;
2082
2083        let mut created_dirs = Vec::new();
2084        let mut cur_path = PathBuf::new();
2085        for component in path.components() {
2086            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
2087            cur_path.push(component);
2088            if should_skip {
2089                continue;
2090            }
2091            let mut state = self.state.lock();
2092
2093            let inode = state.get_and_increment_inode();
2094            let mtime = state.get_and_increment_mtime();
2095            state.write_path(&cur_path, |entry| {
2096                entry.or_insert_with(|| {
2097                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
2098                    FakeFsEntry::Dir {
2099                        inode,
2100                        mtime,
2101                        len: 0,
2102                        entries: Default::default(),
2103                        git_repo_state: None,
2104                    }
2105                });
2106                Ok(())
2107            })?
2108        }
2109
2110        self.state.lock().emit_event(created_dirs);
2111        Ok(())
2112    }
2113
2114    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2115        self.simulate_random_delay().await;
2116        let mut state = self.state.lock();
2117        let inode = state.get_and_increment_inode();
2118        let mtime = state.get_and_increment_mtime();
2119        let file = FakeFsEntry::File {
2120            inode,
2121            mtime,
2122            len: 0,
2123            content: Vec::new(),
2124            git_dir_path: None,
2125        };
2126        let mut kind = Some(PathEventKind::Created);
2127        state.write_path(path, |entry| {
2128            match entry {
2129                btree_map::Entry::Occupied(mut e) => {
2130                    if options.overwrite {
2131                        kind = Some(PathEventKind::Changed);
2132                        *e.get_mut() = file;
2133                    } else if !options.ignore_if_exists {
2134                        anyhow::bail!("path already exists: {path:?}");
2135                    }
2136                }
2137                btree_map::Entry::Vacant(e) => {
2138                    e.insert(file);
2139                }
2140            }
2141            Ok(())
2142        })?;
2143        state.emit_event([(path, kind)]);
2144        Ok(())
2145    }
2146
2147    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2148        let mut state = self.state.lock();
2149        let file = FakeFsEntry::Symlink { target };
2150        state
2151            .write_path(path.as_ref(), move |e| match e {
2152                btree_map::Entry::Vacant(e) => {
2153                    e.insert(file);
2154                    Ok(())
2155                }
2156                btree_map::Entry::Occupied(mut e) => {
2157                    *e.get_mut() = file;
2158                    Ok(())
2159                }
2160            })
2161            .unwrap();
2162        state.emit_event([(path, Some(PathEventKind::Created))]);
2163
2164        Ok(())
2165    }
2166
2167    async fn create_file_with(
2168        &self,
2169        path: &Path,
2170        mut content: Pin<&mut (dyn AsyncRead + Send)>,
2171    ) -> Result<()> {
2172        let mut bytes = Vec::new();
2173        content.read_to_end(&mut bytes).await?;
2174        self.write_file_internal(path, bytes, true)?;
2175        Ok(())
2176    }
2177
2178    async fn extract_tar_file(
2179        &self,
2180        path: &Path,
2181        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2182    ) -> Result<()> {
2183        let mut entries = content.entries()?;
2184        while let Some(entry) = entries.next().await {
2185            let mut entry = entry?;
2186            if entry.header().entry_type().is_file() {
2187                let path = path.join(entry.path()?.as_ref());
2188                let mut bytes = Vec::new();
2189                entry.read_to_end(&mut bytes).await?;
2190                self.create_dir(path.parent().unwrap()).await?;
2191                self.write_file_internal(&path, bytes, true)?;
2192            }
2193        }
2194        Ok(())
2195    }
2196
2197    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2198        self.simulate_random_delay().await;
2199
2200        let old_path = normalize_path(old_path);
2201        let new_path = normalize_path(new_path);
2202
2203        let mut state = self.state.lock();
2204        let moved_entry = state.write_path(&old_path, |e| {
2205            if let btree_map::Entry::Occupied(e) = e {
2206                Ok(e.get().clone())
2207            } else {
2208                anyhow::bail!("path does not exist: {old_path:?}")
2209            }
2210        })?;
2211
2212        let inode = match moved_entry {
2213            FakeFsEntry::File { inode, .. } => inode,
2214            FakeFsEntry::Dir { inode, .. } => inode,
2215            _ => 0,
2216        };
2217
2218        state.moves.insert(inode, new_path.clone());
2219
2220        state.write_path(&new_path, |e| {
2221            match e {
2222                btree_map::Entry::Occupied(mut e) => {
2223                    if options.overwrite {
2224                        *e.get_mut() = moved_entry;
2225                    } else if !options.ignore_if_exists {
2226                        anyhow::bail!("path already exists: {new_path:?}");
2227                    }
2228                }
2229                btree_map::Entry::Vacant(e) => {
2230                    e.insert(moved_entry);
2231                }
2232            }
2233            Ok(())
2234        })?;
2235
2236        state
2237            .write_path(&old_path, |e| {
2238                if let btree_map::Entry::Occupied(e) = e {
2239                    Ok(e.remove())
2240                } else {
2241                    unreachable!()
2242                }
2243            })
2244            .unwrap();
2245
2246        state.emit_event([
2247            (old_path, Some(PathEventKind::Removed)),
2248            (new_path, Some(PathEventKind::Created)),
2249        ]);
2250        Ok(())
2251    }
2252
2253    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2254        self.simulate_random_delay().await;
2255
2256        let source = normalize_path(source);
2257        let target = normalize_path(target);
2258        let mut state = self.state.lock();
2259        let mtime = state.get_and_increment_mtime();
2260        let inode = state.get_and_increment_inode();
2261        let source_entry = state.entry(&source)?;
2262        let content = source_entry.file_content(&source)?.clone();
2263        let mut kind = Some(PathEventKind::Created);
2264        state.write_path(&target, |e| match e {
2265            btree_map::Entry::Occupied(e) => {
2266                if options.overwrite {
2267                    kind = Some(PathEventKind::Changed);
2268                    Ok(Some(e.get().clone()))
2269                } else if !options.ignore_if_exists {
2270                    anyhow::bail!("{target:?} already exists");
2271                } else {
2272                    Ok(None)
2273                }
2274            }
2275            btree_map::Entry::Vacant(e) => Ok(Some(
2276                e.insert(FakeFsEntry::File {
2277                    inode,
2278                    mtime,
2279                    len: content.len() as u64,
2280                    content,
2281                    git_dir_path: None,
2282                })
2283                .clone(),
2284            )),
2285        })?;
2286        state.emit_event([(target, kind)]);
2287        Ok(())
2288    }
2289
2290    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2291        self.simulate_random_delay().await;
2292
2293        let path = normalize_path(path);
2294        let parent_path = path.parent().context("cannot remove the root")?;
2295        let base_name = path.file_name().context("cannot remove the root")?;
2296
2297        let mut state = self.state.lock();
2298        let parent_entry = state.entry(parent_path)?;
2299        let entry = parent_entry
2300            .dir_entries(parent_path)?
2301            .entry(base_name.to_str().unwrap().into());
2302
2303        match entry {
2304            btree_map::Entry::Vacant(_) => {
2305                if !options.ignore_if_not_exists {
2306                    anyhow::bail!("{path:?} does not exist");
2307                }
2308            }
2309            btree_map::Entry::Occupied(mut entry) => {
2310                {
2311                    let children = entry.get_mut().dir_entries(&path)?;
2312                    if !options.recursive && !children.is_empty() {
2313                        anyhow::bail!("{path:?} is not empty");
2314                    }
2315                }
2316                entry.remove();
2317            }
2318        }
2319        state.emit_event([(path, Some(PathEventKind::Removed))]);
2320        Ok(())
2321    }
2322
2323    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2324        self.simulate_random_delay().await;
2325
2326        let path = normalize_path(path);
2327        let parent_path = path.parent().context("cannot remove the root")?;
2328        let base_name = path.file_name().unwrap();
2329        let mut state = self.state.lock();
2330        let parent_entry = state.entry(parent_path)?;
2331        let entry = parent_entry
2332            .dir_entries(parent_path)?
2333            .entry(base_name.to_str().unwrap().into());
2334        match entry {
2335            btree_map::Entry::Vacant(_) => {
2336                if !options.ignore_if_not_exists {
2337                    anyhow::bail!("{path:?} does not exist");
2338                }
2339            }
2340            btree_map::Entry::Occupied(mut entry) => {
2341                entry.get_mut().file_content(&path)?;
2342                entry.remove();
2343            }
2344        }
2345        state.emit_event([(path, Some(PathEventKind::Removed))]);
2346        Ok(())
2347    }
2348
2349    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2350        let bytes = self.load_internal(path).await?;
2351        Ok(Box::new(io::Cursor::new(bytes)))
2352    }
2353
2354    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2355        self.simulate_random_delay().await;
2356        let mut state = self.state.lock();
2357        let inode = match state.entry(path)? {
2358            FakeFsEntry::File { inode, .. } => *inode,
2359            FakeFsEntry::Dir { inode, .. } => *inode,
2360            _ => unreachable!(),
2361        };
2362        Ok(Arc::new(FakeHandle { inode }))
2363    }
2364
2365    async fn load(&self, path: &Path) -> Result<String> {
2366        let content = self.load_internal(path).await?;
2367        Ok(String::from_utf8(content)?)
2368    }
2369
2370    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2371        self.load_internal(path).await
2372    }
2373
2374    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2375        self.simulate_random_delay().await;
2376        let path = normalize_path(path.as_path());
2377        if let Some(path) = path.parent() {
2378            self.create_dir(path).await?;
2379        }
2380        self.write_file_internal(path, data.into_bytes(), true)?;
2381        Ok(())
2382    }
2383
2384    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2385        self.simulate_random_delay().await;
2386        let path = normalize_path(path);
2387        let content = chunks(text, line_ending).collect::<String>();
2388        if let Some(path) = path.parent() {
2389            self.create_dir(path).await?;
2390        }
2391        self.write_file_internal(path, content.into_bytes(), false)?;
2392        Ok(())
2393    }
2394
2395    async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2396        self.simulate_random_delay().await;
2397        let path = normalize_path(path);
2398        if let Some(path) = path.parent() {
2399            self.create_dir(path).await?;
2400        }
2401        self.write_file_internal(path, content.to_vec(), false)?;
2402        Ok(())
2403    }
2404
2405    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2406        let path = normalize_path(path);
2407        self.simulate_random_delay().await;
2408        let state = self.state.lock();
2409        let canonical_path = state
2410            .canonicalize(&path, true)
2411            .with_context(|| format!("path does not exist: {path:?}"))?;
2412        Ok(canonical_path)
2413    }
2414
2415    async fn is_file(&self, path: &Path) -> bool {
2416        let path = normalize_path(path);
2417        self.simulate_random_delay().await;
2418        let mut state = self.state.lock();
2419        if let Some((entry, _)) = state.try_entry(&path, true) {
2420            entry.is_file()
2421        } else {
2422            false
2423        }
2424    }
2425
2426    async fn is_dir(&self, path: &Path) -> bool {
2427        self.metadata(path)
2428            .await
2429            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2430    }
2431
2432    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2433        self.simulate_random_delay().await;
2434        let path = normalize_path(path);
2435        let mut state = self.state.lock();
2436        state.metadata_call_count += 1;
2437        if let Some((mut entry, _)) = state.try_entry(&path, false) {
2438            let is_symlink = entry.is_symlink();
2439            if is_symlink {
2440                if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2441                    entry = e;
2442                } else {
2443                    return Ok(None);
2444                }
2445            }
2446
2447            Ok(Some(match &*entry {
2448                FakeFsEntry::File {
2449                    inode, mtime, len, ..
2450                } => Metadata {
2451                    inode: *inode,
2452                    mtime: *mtime,
2453                    len: *len,
2454                    is_dir: false,
2455                    is_symlink,
2456                    is_fifo: false,
2457                },
2458                FakeFsEntry::Dir {
2459                    inode, mtime, len, ..
2460                } => Metadata {
2461                    inode: *inode,
2462                    mtime: *mtime,
2463                    len: *len,
2464                    is_dir: true,
2465                    is_symlink,
2466                    is_fifo: false,
2467                },
2468                FakeFsEntry::Symlink { .. } => unreachable!(),
2469            }))
2470        } else {
2471            Ok(None)
2472        }
2473    }
2474
2475    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2476        self.simulate_random_delay().await;
2477        let path = normalize_path(path);
2478        let mut state = self.state.lock();
2479        let (entry, _) = state
2480            .try_entry(&path, false)
2481            .with_context(|| format!("path does not exist: {path:?}"))?;
2482        if let FakeFsEntry::Symlink { target } = entry {
2483            Ok(target.clone())
2484        } else {
2485            anyhow::bail!("not a symlink: {path:?}")
2486        }
2487    }
2488
2489    async fn read_dir(
2490        &self,
2491        path: &Path,
2492    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2493        self.simulate_random_delay().await;
2494        let path = normalize_path(path);
2495        let mut state = self.state.lock();
2496        state.read_dir_call_count += 1;
2497        let entry = state.entry(&path)?;
2498        let children = entry.dir_entries(&path)?;
2499        let paths = children
2500            .keys()
2501            .map(|file_name| Ok(path.join(file_name)))
2502            .collect::<Vec<_>>();
2503        Ok(Box::pin(futures::stream::iter(paths)))
2504    }
2505
2506    async fn watch(
2507        &self,
2508        path: &Path,
2509        _: Duration,
2510    ) -> (
2511        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2512        Arc<dyn Watcher>,
2513    ) {
2514        self.simulate_random_delay().await;
2515        let (tx, rx) = smol::channel::unbounded();
2516        let path = path.to_path_buf();
2517        self.state.lock().event_txs.push((path.clone(), tx.clone()));
2518        let executor = self.executor.clone();
2519        let watcher = Arc::new(FakeWatcher {
2520            tx,
2521            original_path: path.to_owned(),
2522            fs_state: self.state.clone(),
2523            prefixes: Mutex::new(vec![path]),
2524        });
2525        (
2526            Box::pin(futures::StreamExt::filter(rx, {
2527                let watcher = watcher.clone();
2528                move |events| {
2529                    let result = events.iter().any(|evt_path| {
2530                        watcher
2531                            .prefixes
2532                            .lock()
2533                            .iter()
2534                            .any(|prefix| evt_path.path.starts_with(prefix))
2535                    });
2536                    let executor = executor.clone();
2537                    async move {
2538                        executor.simulate_random_delay().await;
2539                        result
2540                    }
2541                }
2542            })),
2543            watcher,
2544        )
2545    }
2546
2547    fn open_repo(
2548        &self,
2549        abs_dot_git: &Path,
2550        _system_git_binary: Option<&Path>,
2551    ) -> Option<Arc<dyn GitRepository>> {
2552        use util::ResultExt as _;
2553
2554        self.with_git_state_and_paths(
2555            abs_dot_git,
2556            false,
2557            |_, repository_dir_path, common_dir_path| {
2558                Arc::new(fake_git_repo::FakeGitRepository {
2559                    fs: self.this.upgrade().unwrap(),
2560                    executor: self.executor.clone(),
2561                    dot_git_path: abs_dot_git.to_path_buf(),
2562                    repository_dir_path: repository_dir_path.to_owned(),
2563                    common_dir_path: common_dir_path.to_owned(),
2564                    checkpoints: Arc::default(),
2565                }) as _
2566            },
2567        )
2568        .log_err()
2569    }
2570
2571    async fn git_init(
2572        &self,
2573        abs_work_directory_path: &Path,
2574        _fallback_branch_name: String,
2575    ) -> Result<()> {
2576        self.create_dir(&abs_work_directory_path.join(".git")).await
2577    }
2578
2579    async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2580        anyhow::bail!("Git clone is not supported in fake Fs")
2581    }
2582
2583    fn is_fake(&self) -> bool {
2584        true
2585    }
2586
2587    async fn is_case_sensitive(&self) -> Result<bool> {
2588        Ok(true)
2589    }
2590
2591    #[cfg(any(test, feature = "test-support"))]
2592    fn as_fake(&self) -> Arc<FakeFs> {
2593        self.this.upgrade().unwrap()
2594    }
2595}
2596
2597fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
2598    rope.chunks().flat_map(move |chunk| {
2599        let mut newline = false;
2600        let end_with_newline = chunk.ends_with('\n').then_some(line_ending.as_str());
2601        chunk
2602            .lines()
2603            .flat_map(move |line| {
2604                let ending = if newline {
2605                    Some(line_ending.as_str())
2606                } else {
2607                    None
2608                };
2609                newline = true;
2610                ending.into_iter().chain([line])
2611            })
2612            .chain(end_with_newline)
2613    })
2614}
2615
2616pub fn normalize_path(path: &Path) -> PathBuf {
2617    let mut components = path.components().peekable();
2618    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2619        components.next();
2620        PathBuf::from(c.as_os_str())
2621    } else {
2622        PathBuf::new()
2623    };
2624
2625    for component in components {
2626        match component {
2627            Component::Prefix(..) => unreachable!(),
2628            Component::RootDir => {
2629                ret.push(component.as_os_str());
2630            }
2631            Component::CurDir => {}
2632            Component::ParentDir => {
2633                ret.pop();
2634            }
2635            Component::Normal(c) => {
2636                ret.push(c);
2637            }
2638        }
2639    }
2640    ret
2641}
2642
2643pub async fn copy_recursive<'a>(
2644    fs: &'a dyn Fs,
2645    source: &'a Path,
2646    target: &'a Path,
2647    options: CopyOptions,
2648) -> Result<()> {
2649    for (item, is_dir) in read_dir_items(fs, source).await? {
2650        let Ok(item_relative_path) = item.strip_prefix(source) else {
2651            continue;
2652        };
2653        let target_item = if item_relative_path == Path::new("") {
2654            target.to_path_buf()
2655        } else {
2656            target.join(item_relative_path)
2657        };
2658        if is_dir {
2659            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2660                if options.ignore_if_exists {
2661                    continue;
2662                } else {
2663                    anyhow::bail!("{target_item:?} already exists");
2664                }
2665            }
2666            let _ = fs
2667                .remove_dir(
2668                    &target_item,
2669                    RemoveOptions {
2670                        recursive: true,
2671                        ignore_if_not_exists: true,
2672                    },
2673                )
2674                .await;
2675            fs.create_dir(&target_item).await?;
2676        } else {
2677            fs.copy_file(&item, &target_item, options).await?;
2678        }
2679    }
2680    Ok(())
2681}
2682
2683/// Recursively reads all of the paths in the given directory.
2684///
2685/// Returns a vector of tuples of (path, is_dir).
2686pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2687    let mut items = Vec::new();
2688    read_recursive(fs, source, &mut items).await?;
2689    Ok(items)
2690}
2691
2692fn read_recursive<'a>(
2693    fs: &'a dyn Fs,
2694    source: &'a Path,
2695    output: &'a mut Vec<(PathBuf, bool)>,
2696) -> BoxFuture<'a, Result<()>> {
2697    use futures::future::FutureExt;
2698
2699    async move {
2700        let metadata = fs
2701            .metadata(source)
2702            .await?
2703            .with_context(|| format!("path does not exist: {source:?}"))?;
2704
2705        if metadata.is_dir {
2706            output.push((source.to_path_buf(), true));
2707            let mut children = fs.read_dir(source).await?;
2708            while let Some(child_path) = children.next().await {
2709                if let Ok(child_path) = child_path {
2710                    read_recursive(fs, &child_path, output).await?;
2711                }
2712            }
2713        } else {
2714            output.push((source.to_path_buf(), false));
2715        }
2716        Ok(())
2717    }
2718    .boxed()
2719}
2720
2721// todo(windows)
2722// can we get file id not open the file twice?
2723// https://github.com/rust-lang/rust/issues/63010
2724#[cfg(target_os = "windows")]
2725async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2726    use std::os::windows::io::AsRawHandle;
2727
2728    use smol::fs::windows::OpenOptionsExt;
2729    use windows::Win32::{
2730        Foundation::HANDLE,
2731        Storage::FileSystem::{
2732            BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2733        },
2734    };
2735
2736    let file = smol::fs::OpenOptions::new()
2737        .read(true)
2738        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2739        .open(path)
2740        .await?;
2741
2742    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2743    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2744    // This function supports Windows XP+
2745    smol::unblock(move || {
2746        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2747
2748        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2749    })
2750    .await
2751}
2752
2753#[cfg(target_os = "windows")]
2754fn atomic_replace<P: AsRef<Path>>(
2755    replaced_file: P,
2756    replacement_file: P,
2757) -> windows::core::Result<()> {
2758    use windows::{
2759        Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2760        core::HSTRING,
2761    };
2762
2763    // If the file does not exist, create it.
2764    let _ = std::fs::File::create_new(replaced_file.as_ref());
2765
2766    unsafe {
2767        ReplaceFileW(
2768            &HSTRING::from(replaced_file.as_ref().to_string_lossy().into_owned()),
2769            &HSTRING::from(replacement_file.as_ref().to_string_lossy().into_owned()),
2770            None,
2771            REPLACE_FILE_FLAGS::default(),
2772            None,
2773            None,
2774        )
2775    }
2776}
2777
2778#[cfg(test)]
2779mod tests {
2780    use super::*;
2781    use gpui::BackgroundExecutor;
2782    use serde_json::json;
2783    use util::path;
2784
2785    #[gpui::test]
2786    async fn test_fake_fs(executor: BackgroundExecutor) {
2787        let fs = FakeFs::new(executor.clone());
2788        fs.insert_tree(
2789            path!("/root"),
2790            json!({
2791                "dir1": {
2792                    "a": "A",
2793                    "b": "B"
2794                },
2795                "dir2": {
2796                    "c": "C",
2797                    "dir3": {
2798                        "d": "D"
2799                    }
2800                }
2801            }),
2802        )
2803        .await;
2804
2805        assert_eq!(
2806            fs.files(),
2807            vec![
2808                PathBuf::from(path!("/root/dir1/a")),
2809                PathBuf::from(path!("/root/dir1/b")),
2810                PathBuf::from(path!("/root/dir2/c")),
2811                PathBuf::from(path!("/root/dir2/dir3/d")),
2812            ]
2813        );
2814
2815        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2816            .await
2817            .unwrap();
2818
2819        assert_eq!(
2820            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2821                .await
2822                .unwrap(),
2823            PathBuf::from(path!("/root/dir2/dir3")),
2824        );
2825        assert_eq!(
2826            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2827                .await
2828                .unwrap(),
2829            PathBuf::from(path!("/root/dir2/dir3/d")),
2830        );
2831        assert_eq!(
2832            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2833                .await
2834                .unwrap(),
2835            "D",
2836        );
2837    }
2838
2839    #[gpui::test]
2840    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2841        let fs = FakeFs::new(executor.clone());
2842        fs.insert_tree(
2843            path!("/outer"),
2844            json!({
2845                "a": "A",
2846                "b": "B",
2847                "inner": {}
2848            }),
2849        )
2850        .await;
2851
2852        assert_eq!(
2853            fs.files(),
2854            vec![
2855                PathBuf::from(path!("/outer/a")),
2856                PathBuf::from(path!("/outer/b")),
2857            ]
2858        );
2859
2860        let source = Path::new(path!("/outer/a"));
2861        let target = Path::new(path!("/outer/a copy"));
2862        copy_recursive(fs.as_ref(), source, target, Default::default())
2863            .await
2864            .unwrap();
2865
2866        assert_eq!(
2867            fs.files(),
2868            vec![
2869                PathBuf::from(path!("/outer/a")),
2870                PathBuf::from(path!("/outer/a copy")),
2871                PathBuf::from(path!("/outer/b")),
2872            ]
2873        );
2874
2875        let source = Path::new(path!("/outer/a"));
2876        let target = Path::new(path!("/outer/inner/a copy"));
2877        copy_recursive(fs.as_ref(), source, target, Default::default())
2878            .await
2879            .unwrap();
2880
2881        assert_eq!(
2882            fs.files(),
2883            vec![
2884                PathBuf::from(path!("/outer/a")),
2885                PathBuf::from(path!("/outer/a copy")),
2886                PathBuf::from(path!("/outer/b")),
2887                PathBuf::from(path!("/outer/inner/a copy")),
2888            ]
2889        );
2890    }
2891
2892    #[gpui::test]
2893    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2894        let fs = FakeFs::new(executor.clone());
2895        fs.insert_tree(
2896            path!("/outer"),
2897            json!({
2898                "a": "A",
2899                "empty": {},
2900                "non-empty": {
2901                    "b": "B",
2902                }
2903            }),
2904        )
2905        .await;
2906
2907        assert_eq!(
2908            fs.files(),
2909            vec![
2910                PathBuf::from(path!("/outer/a")),
2911                PathBuf::from(path!("/outer/non-empty/b")),
2912            ]
2913        );
2914        assert_eq!(
2915            fs.directories(false),
2916            vec![
2917                PathBuf::from(path!("/")),
2918                PathBuf::from(path!("/outer")),
2919                PathBuf::from(path!("/outer/empty")),
2920                PathBuf::from(path!("/outer/non-empty")),
2921            ]
2922        );
2923
2924        let source = Path::new(path!("/outer/empty"));
2925        let target = Path::new(path!("/outer/empty copy"));
2926        copy_recursive(fs.as_ref(), source, target, Default::default())
2927            .await
2928            .unwrap();
2929
2930        assert_eq!(
2931            fs.files(),
2932            vec![
2933                PathBuf::from(path!("/outer/a")),
2934                PathBuf::from(path!("/outer/non-empty/b")),
2935            ]
2936        );
2937        assert_eq!(
2938            fs.directories(false),
2939            vec![
2940                PathBuf::from(path!("/")),
2941                PathBuf::from(path!("/outer")),
2942                PathBuf::from(path!("/outer/empty")),
2943                PathBuf::from(path!("/outer/empty copy")),
2944                PathBuf::from(path!("/outer/non-empty")),
2945            ]
2946        );
2947
2948        let source = Path::new(path!("/outer/non-empty"));
2949        let target = Path::new(path!("/outer/non-empty copy"));
2950        copy_recursive(fs.as_ref(), source, target, Default::default())
2951            .await
2952            .unwrap();
2953
2954        assert_eq!(
2955            fs.files(),
2956            vec![
2957                PathBuf::from(path!("/outer/a")),
2958                PathBuf::from(path!("/outer/non-empty/b")),
2959                PathBuf::from(path!("/outer/non-empty copy/b")),
2960            ]
2961        );
2962        assert_eq!(
2963            fs.directories(false),
2964            vec![
2965                PathBuf::from(path!("/")),
2966                PathBuf::from(path!("/outer")),
2967                PathBuf::from(path!("/outer/empty")),
2968                PathBuf::from(path!("/outer/empty copy")),
2969                PathBuf::from(path!("/outer/non-empty")),
2970                PathBuf::from(path!("/outer/non-empty copy")),
2971            ]
2972        );
2973    }
2974
2975    #[gpui::test]
2976    async fn test_copy_recursive(executor: BackgroundExecutor) {
2977        let fs = FakeFs::new(executor.clone());
2978        fs.insert_tree(
2979            path!("/outer"),
2980            json!({
2981                "inner1": {
2982                    "a": "A",
2983                    "b": "B",
2984                    "inner3": {
2985                        "d": "D",
2986                    },
2987                    "inner4": {}
2988                },
2989                "inner2": {
2990                    "c": "C",
2991                }
2992            }),
2993        )
2994        .await;
2995
2996        assert_eq!(
2997            fs.files(),
2998            vec![
2999                PathBuf::from(path!("/outer/inner1/a")),
3000                PathBuf::from(path!("/outer/inner1/b")),
3001                PathBuf::from(path!("/outer/inner2/c")),
3002                PathBuf::from(path!("/outer/inner1/inner3/d")),
3003            ]
3004        );
3005        assert_eq!(
3006            fs.directories(false),
3007            vec![
3008                PathBuf::from(path!("/")),
3009                PathBuf::from(path!("/outer")),
3010                PathBuf::from(path!("/outer/inner1")),
3011                PathBuf::from(path!("/outer/inner2")),
3012                PathBuf::from(path!("/outer/inner1/inner3")),
3013                PathBuf::from(path!("/outer/inner1/inner4")),
3014            ]
3015        );
3016
3017        let source = Path::new(path!("/outer"));
3018        let target = Path::new(path!("/outer/inner1/outer"));
3019        copy_recursive(fs.as_ref(), source, target, Default::default())
3020            .await
3021            .unwrap();
3022
3023        assert_eq!(
3024            fs.files(),
3025            vec![
3026                PathBuf::from(path!("/outer/inner1/a")),
3027                PathBuf::from(path!("/outer/inner1/b")),
3028                PathBuf::from(path!("/outer/inner2/c")),
3029                PathBuf::from(path!("/outer/inner1/inner3/d")),
3030                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3031                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3032                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3033                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
3034            ]
3035        );
3036        assert_eq!(
3037            fs.directories(false),
3038            vec![
3039                PathBuf::from(path!("/")),
3040                PathBuf::from(path!("/outer")),
3041                PathBuf::from(path!("/outer/inner1")),
3042                PathBuf::from(path!("/outer/inner2")),
3043                PathBuf::from(path!("/outer/inner1/inner3")),
3044                PathBuf::from(path!("/outer/inner1/inner4")),
3045                PathBuf::from(path!("/outer/inner1/outer")),
3046                PathBuf::from(path!("/outer/inner1/outer/inner1")),
3047                PathBuf::from(path!("/outer/inner1/outer/inner2")),
3048                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
3049                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
3050            ]
3051        );
3052    }
3053
3054    #[gpui::test]
3055    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
3056        let fs = FakeFs::new(executor.clone());
3057        fs.insert_tree(
3058            path!("/outer"),
3059            json!({
3060                "inner1": {
3061                    "a": "A",
3062                    "b": "B",
3063                    "outer": {
3064                        "inner1": {
3065                            "a": "B"
3066                        }
3067                    }
3068                },
3069                "inner2": {
3070                    "c": "C",
3071                }
3072            }),
3073        )
3074        .await;
3075
3076        assert_eq!(
3077            fs.files(),
3078            vec![
3079                PathBuf::from(path!("/outer/inner1/a")),
3080                PathBuf::from(path!("/outer/inner1/b")),
3081                PathBuf::from(path!("/outer/inner2/c")),
3082                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3083            ]
3084        );
3085        assert_eq!(
3086            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3087                .await
3088                .unwrap(),
3089            "B",
3090        );
3091
3092        let source = Path::new(path!("/outer"));
3093        let target = Path::new(path!("/outer/inner1/outer"));
3094        copy_recursive(
3095            fs.as_ref(),
3096            source,
3097            target,
3098            CopyOptions {
3099                overwrite: true,
3100                ..Default::default()
3101            },
3102        )
3103        .await
3104        .unwrap();
3105
3106        assert_eq!(
3107            fs.files(),
3108            vec![
3109                PathBuf::from(path!("/outer/inner1/a")),
3110                PathBuf::from(path!("/outer/inner1/b")),
3111                PathBuf::from(path!("/outer/inner2/c")),
3112                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3113                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3114                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3115                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3116            ]
3117        );
3118        assert_eq!(
3119            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3120                .await
3121                .unwrap(),
3122            "A"
3123        );
3124    }
3125
3126    #[gpui::test]
3127    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
3128        let fs = FakeFs::new(executor.clone());
3129        fs.insert_tree(
3130            path!("/outer"),
3131            json!({
3132                "inner1": {
3133                    "a": "A",
3134                    "b": "B",
3135                    "outer": {
3136                        "inner1": {
3137                            "a": "B"
3138                        }
3139                    }
3140                },
3141                "inner2": {
3142                    "c": "C",
3143                }
3144            }),
3145        )
3146        .await;
3147
3148        assert_eq!(
3149            fs.files(),
3150            vec![
3151                PathBuf::from(path!("/outer/inner1/a")),
3152                PathBuf::from(path!("/outer/inner1/b")),
3153                PathBuf::from(path!("/outer/inner2/c")),
3154                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3155            ]
3156        );
3157        assert_eq!(
3158            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3159                .await
3160                .unwrap(),
3161            "B",
3162        );
3163
3164        let source = Path::new(path!("/outer"));
3165        let target = Path::new(path!("/outer/inner1/outer"));
3166        copy_recursive(
3167            fs.as_ref(),
3168            source,
3169            target,
3170            CopyOptions {
3171                ignore_if_exists: true,
3172                ..Default::default()
3173            },
3174        )
3175        .await
3176        .unwrap();
3177
3178        assert_eq!(
3179            fs.files(),
3180            vec![
3181                PathBuf::from(path!("/outer/inner1/a")),
3182                PathBuf::from(path!("/outer/inner1/b")),
3183                PathBuf::from(path!("/outer/inner2/c")),
3184                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
3185                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
3186                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
3187                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
3188            ]
3189        );
3190        assert_eq!(
3191            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
3192                .await
3193                .unwrap(),
3194            "B"
3195        );
3196    }
3197
3198    #[gpui::test]
3199    async fn test_realfs_atomic_write(executor: BackgroundExecutor) {
3200        // With the file handle still open, the file should be replaced
3201        // https://github.com/zed-industries/zed/issues/30054
3202        let fs = RealFs {
3203            bundled_git_binary_path: None,
3204            executor,
3205        };
3206        let temp_dir = TempDir::new().unwrap();
3207        let file_to_be_replaced = temp_dir.path().join("file.txt");
3208        let mut file = std::fs::File::create_new(&file_to_be_replaced).unwrap();
3209        file.write_all(b"Hello").unwrap();
3210        // drop(file);  // We still hold the file handle here
3211        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3212        assert_eq!(content, "Hello");
3213        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "World".into())).unwrap();
3214        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3215        assert_eq!(content, "World");
3216    }
3217
3218    #[gpui::test]
3219    async fn test_realfs_atomic_write_non_existing_file(executor: BackgroundExecutor) {
3220        let fs = RealFs {
3221            bundled_git_binary_path: None,
3222            executor,
3223        };
3224        let temp_dir = TempDir::new().unwrap();
3225        let file_to_be_replaced = temp_dir.path().join("file.txt");
3226        smol::block_on(fs.atomic_write(file_to_be_replaced.clone(), "Hello".into())).unwrap();
3227        let content = std::fs::read_to_string(&file_to_be_replaced).unwrap();
3228        assert_eq!(content, "Hello");
3229    }
3230}