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