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