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