fs.rs

   1#[cfg(target_os = "macos")]
   2mod mac_watcher;
   3
   4#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   5pub mod linux_watcher;
   6
   7use anyhow::{anyhow, Result};
   8use git::GitHostingProviderRegistry;
   9
  10#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  11use ashpd::desktop::trash;
  12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  13use std::fs::File;
  14#[cfg(unix)]
  15use std::os::fd::AsFd;
  16#[cfg(unix)]
  17use std::os::fd::AsRawFd;
  18
  19#[cfg(unix)]
  20use std::os::unix::fs::MetadataExt;
  21
  22#[cfg(unix)]
  23use std::os::unix::fs::FileTypeExt;
  24
  25use async_tar::Archive;
  26use futures::{future::BoxFuture, AsyncRead, Stream, StreamExt};
  27use git::repository::{GitRepository, RealGitRepository};
  28use gpui::{AppContext, Global, ReadGlobal};
  29use rope::Rope;
  30use serde::{Deserialize, Serialize};
  31use smol::io::AsyncWriteExt;
  32use std::{
  33    io::{self, Write},
  34    path::{Component, Path, PathBuf},
  35    pin::Pin,
  36    sync::Arc,
  37    time::{Duration, SystemTime, UNIX_EPOCH},
  38};
  39use tempfile::{NamedTempFile, TempDir};
  40use text::LineEnding;
  41use util::ResultExt;
  42
  43#[cfg(any(test, feature = "test-support"))]
  44use collections::{btree_map, BTreeMap};
  45#[cfg(any(test, feature = "test-support"))]
  46use git::repository::{FakeGitRepositoryState, GitFileStatus};
  47#[cfg(any(test, feature = "test-support"))]
  48use parking_lot::Mutex;
  49#[cfg(any(test, feature = "test-support"))]
  50use smol::io::AsyncReadExt;
  51#[cfg(any(test, feature = "test-support"))]
  52use std::ffi::OsStr;
  53
  54pub trait Watcher: Send + Sync {
  55    fn add(&self, path: &Path) -> Result<()>;
  56    fn remove(&self, path: &Path) -> Result<()>;
  57}
  58
  59#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  60pub enum PathEventKind {
  61    Removed,
  62    Created,
  63    Changed,
  64}
  65
  66#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
  67pub struct PathEvent {
  68    pub path: PathBuf,
  69    pub kind: Option<PathEventKind>,
  70}
  71
  72impl From<PathEvent> for PathBuf {
  73    fn from(event: PathEvent) -> Self {
  74        event.path
  75    }
  76}
  77
  78#[async_trait::async_trait]
  79pub trait Fs: Send + Sync {
  80    async fn create_dir(&self, path: &Path) -> Result<()>;
  81    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
  82    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  83    async fn create_file_with(
  84        &self,
  85        path: &Path,
  86        content: Pin<&mut (dyn AsyncRead + Send)>,
  87    ) -> Result<()>;
  88    async fn extract_tar_file(
  89        &self,
  90        path: &Path,
  91        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
  92    ) -> Result<()>;
  93    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
  94    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
  95    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  96    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
  97        self.remove_dir(path, options).await
  98    }
  99    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 100    async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 101        self.remove_file(path, options).await
 102    }
 103    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
 104    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
 105    async fn load(&self, path: &Path) -> Result<String> {
 106        Ok(String::from_utf8(self.load_bytes(path).await?)?)
 107    }
 108    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
 109    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 110    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
 111    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 112    async fn is_file(&self, path: &Path) -> bool;
 113    async fn is_dir(&self, path: &Path) -> bool;
 114    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 115    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 116    async fn read_dir(
 117        &self,
 118        path: &Path,
 119    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 120
 121    async fn watch(
 122        &self,
 123        path: &Path,
 124        latency: Duration,
 125    ) -> (
 126        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 127        Arc<dyn Watcher>,
 128    );
 129
 130    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>>;
 131    fn is_fake(&self) -> bool;
 132    async fn is_case_sensitive(&self) -> Result<bool>;
 133
 134    #[cfg(any(test, feature = "test-support"))]
 135    fn as_fake(&self) -> Arc<FakeFs> {
 136        panic!("called as_fake on a real fs");
 137    }
 138}
 139
 140struct GlobalFs(Arc<dyn Fs>);
 141
 142impl Global for GlobalFs {}
 143
 144impl dyn Fs {
 145    /// Returns the global [`Fs`].
 146    pub fn global(cx: &AppContext) -> Arc<Self> {
 147        GlobalFs::global(cx).0.clone()
 148    }
 149
 150    /// Sets the global [`Fs`].
 151    pub fn set_global(fs: Arc<Self>, cx: &mut AppContext) {
 152        cx.set_global(GlobalFs(fs));
 153    }
 154}
 155
 156#[derive(Copy, Clone, Default)]
 157pub struct CreateOptions {
 158    pub overwrite: bool,
 159    pub ignore_if_exists: bool,
 160}
 161
 162#[derive(Copy, Clone, Default)]
 163pub struct CopyOptions {
 164    pub overwrite: bool,
 165    pub ignore_if_exists: bool,
 166}
 167
 168#[derive(Copy, Clone, Default)]
 169pub struct RenameOptions {
 170    pub overwrite: bool,
 171    pub ignore_if_exists: bool,
 172}
 173
 174#[derive(Copy, Clone, Default)]
 175pub struct RemoveOptions {
 176    pub recursive: bool,
 177    pub ignore_if_not_exists: bool,
 178}
 179
 180#[derive(Copy, Clone, Debug)]
 181pub struct Metadata {
 182    pub inode: u64,
 183    pub mtime: MTime,
 184    pub is_symlink: bool,
 185    pub is_dir: bool,
 186    pub len: u64,
 187    pub is_fifo: bool,
 188}
 189
 190/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
 191/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
 192/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
 193/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
 194///
 195/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
 196#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
 197#[serde(transparent)]
 198pub struct MTime(SystemTime);
 199
 200impl MTime {
 201    /// Conversion intended for persistence and testing.
 202    pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
 203        MTime(UNIX_EPOCH + Duration::new(secs, nanos))
 204    }
 205
 206    /// Conversion intended for persistence.
 207    pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
 208        self.0
 209            .duration_since(UNIX_EPOCH)
 210            .ok()
 211            .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
 212    }
 213
 214    /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
 215    /// "_for_user" is to discourage misuse - this method should not be used when making decisions
 216    /// about file dirtiness.
 217    pub fn timestamp_for_user(self) -> SystemTime {
 218        self.0
 219    }
 220
 221    /// Temporary method to split out the behavior changes from introduction of this newtype.
 222    pub fn bad_is_greater_than(self, other: MTime) -> bool {
 223        self.0 > other.0
 224    }
 225}
 226
 227impl From<proto::Timestamp> for MTime {
 228    fn from(timestamp: proto::Timestamp) -> Self {
 229        MTime(timestamp.into())
 230    }
 231}
 232
 233impl From<MTime> for proto::Timestamp {
 234    fn from(mtime: MTime) -> Self {
 235        mtime.0.into()
 236    }
 237}
 238
 239#[derive(Default)]
 240pub struct RealFs {
 241    git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 242    git_binary_path: Option<PathBuf>,
 243}
 244
 245pub trait FileHandle: Send + Sync + std::fmt::Debug {
 246    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
 247}
 248
 249impl FileHandle for std::fs::File {
 250    #[cfg(target_os = "macos")]
 251    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 252        use std::{
 253            ffi::{CStr, OsStr},
 254            os::unix::ffi::OsStrExt,
 255        };
 256
 257        let fd = self.as_fd();
 258        let mut path_buf: [libc::c_char; libc::PATH_MAX as usize] = [0; libc::PATH_MAX as usize];
 259
 260        let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
 261        if result == -1 {
 262            anyhow::bail!("fcntl returned -1".to_string());
 263        }
 264
 265        let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr()) };
 266        let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
 267        Ok(path)
 268    }
 269
 270    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 271    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 272        let fd = self.as_fd();
 273        let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
 274        let new_path = std::fs::read_link(fd_path)?;
 275        if new_path
 276            .file_name()
 277            .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
 278        {
 279            anyhow::bail!("file was deleted")
 280        };
 281
 282        Ok(new_path)
 283    }
 284
 285    #[cfg(target_os = "windows")]
 286    fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
 287        anyhow::bail!("unimplemented")
 288    }
 289}
 290
 291pub struct RealWatcher {}
 292
 293impl RealFs {
 294    pub fn new(
 295        git_hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 296        git_binary_path: Option<PathBuf>,
 297    ) -> Self {
 298        Self {
 299            git_hosting_provider_registry,
 300            git_binary_path,
 301        }
 302    }
 303}
 304
 305#[async_trait::async_trait]
 306impl Fs for RealFs {
 307    async fn create_dir(&self, path: &Path) -> Result<()> {
 308        Ok(smol::fs::create_dir_all(path).await?)
 309    }
 310
 311    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
 312        #[cfg(unix)]
 313        smol::fs::unix::symlink(target, path).await?;
 314
 315        #[cfg(windows)]
 316        if smol::fs::metadata(&target).await?.is_dir() {
 317            smol::fs::windows::symlink_dir(target, path).await?
 318        } else {
 319            smol::fs::windows::symlink_file(target, path).await?
 320        }
 321
 322        Ok(())
 323    }
 324
 325    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 326        let mut open_options = smol::fs::OpenOptions::new();
 327        open_options.write(true).create(true);
 328        if options.overwrite {
 329            open_options.truncate(true);
 330        } else if !options.ignore_if_exists {
 331            open_options.create_new(true);
 332        }
 333        open_options.open(path).await?;
 334        Ok(())
 335    }
 336
 337    async fn create_file_with(
 338        &self,
 339        path: &Path,
 340        content: Pin<&mut (dyn AsyncRead + Send)>,
 341    ) -> Result<()> {
 342        let mut file = smol::fs::File::create(&path).await?;
 343        futures::io::copy(content, &mut file).await?;
 344        Ok(())
 345    }
 346
 347    async fn extract_tar_file(
 348        &self,
 349        path: &Path,
 350        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
 351    ) -> Result<()> {
 352        content.unpack(path).await?;
 353        Ok(())
 354    }
 355
 356    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 357        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 358            if options.ignore_if_exists {
 359                return Ok(());
 360            } else {
 361                return Err(anyhow!("{target:?} already exists"));
 362            }
 363        }
 364
 365        smol::fs::copy(source, target).await?;
 366        Ok(())
 367    }
 368
 369    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 370        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 371            if options.ignore_if_exists {
 372                return Ok(());
 373            } else {
 374                return Err(anyhow!("{target:?} already exists"));
 375            }
 376        }
 377
 378        smol::fs::rename(source, target).await?;
 379        Ok(())
 380    }
 381
 382    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 383        let result = if options.recursive {
 384            smol::fs::remove_dir_all(path).await
 385        } else {
 386            smol::fs::remove_dir(path).await
 387        };
 388        match result {
 389            Ok(()) => Ok(()),
 390            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 391                Ok(())
 392            }
 393            Err(err) => Err(err)?,
 394        }
 395    }
 396
 397    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 398        #[cfg(windows)]
 399        if let Ok(Some(metadata)) = self.metadata(path).await {
 400            if metadata.is_symlink && metadata.is_dir {
 401                self.remove_dir(
 402                    path,
 403                    RemoveOptions {
 404                        recursive: false,
 405                        ignore_if_not_exists: true,
 406                    },
 407                )
 408                .await?;
 409                return Ok(());
 410            }
 411        }
 412
 413        match smol::fs::remove_file(path).await {
 414            Ok(()) => Ok(()),
 415            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 416                Ok(())
 417            }
 418            Err(err) => Err(err)?,
 419        }
 420    }
 421
 422    #[cfg(target_os = "macos")]
 423    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 424        use cocoa::{
 425            base::{id, nil},
 426            foundation::{NSAutoreleasePool, NSString},
 427        };
 428        use objc::{class, msg_send, sel, sel_impl};
 429
 430        unsafe {
 431            unsafe fn ns_string(string: &str) -> id {
 432                NSString::alloc(nil).init_str(string).autorelease()
 433            }
 434
 435            let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
 436            let array: id = msg_send![class!(NSArray), arrayWithObject: url];
 437            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 438
 439            let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
 440        }
 441        Ok(())
 442    }
 443
 444    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 445    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 446        let file = File::open(path)?;
 447        match trash::trash_file(&file.as_fd()).await {
 448            Ok(_) => Ok(()),
 449            Err(err) => Err(anyhow::Error::new(err)),
 450        }
 451    }
 452
 453    #[cfg(target_os = "windows")]
 454    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 455        use util::paths::SanitizedPath;
 456        use windows::{
 457            core::HSTRING,
 458            Storage::{StorageDeleteOption, StorageFile},
 459        };
 460        // todo(windows)
 461        // When new version of `windows-rs` release, make this operation `async`
 462        let path = SanitizedPath::from(path.canonicalize()?);
 463        let path_string = path.to_string();
 464        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 465        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 466        Ok(())
 467    }
 468
 469    #[cfg(target_os = "macos")]
 470    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 471        self.trash_file(path, options).await
 472    }
 473
 474    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 475    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 476        self.trash_file(path, options).await
 477    }
 478
 479    #[cfg(target_os = "windows")]
 480    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 481        use util::paths::SanitizedPath;
 482        use windows::{
 483            core::HSTRING,
 484            Storage::{StorageDeleteOption, StorageFolder},
 485        };
 486
 487        // todo(windows)
 488        // When new version of `windows-rs` release, make this operation `async`
 489        let path = SanitizedPath::from(path.canonicalize()?);
 490        let path_string = path.to_string();
 491        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 492        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 493        Ok(())
 494    }
 495
 496    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 497        Ok(Box::new(std::fs::File::open(path)?))
 498    }
 499
 500    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 501        Ok(Arc::new(std::fs::File::open(path)?))
 502    }
 503
 504    async fn load(&self, path: &Path) -> Result<String> {
 505        let path = path.to_path_buf();
 506        let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
 507        Ok(text)
 508    }
 509    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 510        let path = path.to_path_buf();
 511        let bytes = smol::unblock(|| std::fs::read(path)).await?;
 512        Ok(bytes)
 513    }
 514
 515    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 516        smol::unblock(move || {
 517            let mut tmp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 518                // Use the directory of the destination as temp dir to avoid
 519                // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 520                // See https://github.com/zed-industries/zed/pull/8437 for more details.
 521                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 522            } else if cfg!(target_os = "windows") {
 523                // If temp dir is set to a different drive than the destination,
 524                // we receive error:
 525                //
 526                // failed to persist temporary file:
 527                // The system cannot move the file to a different disk drive. (os error 17)
 528                //
 529                // So we use the directory of the destination as a temp dir to avoid it.
 530                // https://github.com/zed-industries/zed/issues/16571
 531                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 532            } else {
 533                NamedTempFile::new()
 534            }?;
 535            tmp_file.write_all(data.as_bytes())?;
 536            tmp_file.persist(path)?;
 537            Ok::<(), anyhow::Error>(())
 538        })
 539        .await?;
 540
 541        Ok(())
 542    }
 543
 544    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 545        let buffer_size = text.summary().len.min(10 * 1024);
 546        if let Some(path) = path.parent() {
 547            self.create_dir(path).await?;
 548        }
 549        let file = smol::fs::File::create(path).await?;
 550        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 551        for chunk in chunks(text, line_ending) {
 552            writer.write_all(chunk.as_bytes()).await?;
 553        }
 554        writer.flush().await?;
 555        Ok(())
 556    }
 557
 558    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 559        Ok(smol::fs::canonicalize(path).await?)
 560    }
 561
 562    async fn is_file(&self, path: &Path) -> bool {
 563        smol::fs::metadata(path)
 564            .await
 565            .map_or(false, |metadata| metadata.is_file())
 566    }
 567
 568    async fn is_dir(&self, path: &Path) -> bool {
 569        smol::fs::metadata(path)
 570            .await
 571            .map_or(false, |metadata| metadata.is_dir())
 572    }
 573
 574    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 575        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 576            Ok(metadata) => metadata,
 577            Err(err) => {
 578                return match (err.kind(), err.raw_os_error()) {
 579                    (io::ErrorKind::NotFound, _) => Ok(None),
 580                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 581                    _ => Err(anyhow::Error::new(err)),
 582                }
 583            }
 584        };
 585
 586        let is_symlink = symlink_metadata.file_type().is_symlink();
 587        let metadata = if is_symlink {
 588            smol::fs::metadata(path).await?
 589        } else {
 590            symlink_metadata
 591        };
 592
 593        #[cfg(unix)]
 594        let inode = metadata.ino();
 595
 596        #[cfg(windows)]
 597        let inode = file_id(path).await?;
 598
 599        #[cfg(windows)]
 600        let is_fifo = false;
 601
 602        #[cfg(unix)]
 603        let is_fifo = metadata.file_type().is_fifo();
 604
 605        Ok(Some(Metadata {
 606            inode,
 607            mtime: MTime(metadata.modified().unwrap()),
 608            len: metadata.len(),
 609            is_symlink,
 610            is_dir: metadata.file_type().is_dir(),
 611            is_fifo,
 612        }))
 613    }
 614
 615    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 616        let path = smol::fs::read_link(path).await?;
 617        Ok(path)
 618    }
 619
 620    async fn read_dir(
 621        &self,
 622        path: &Path,
 623    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 624        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 625            Ok(entry) => Ok(entry.path()),
 626            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 627        });
 628        Ok(Box::pin(result))
 629    }
 630
 631    #[cfg(target_os = "macos")]
 632    async fn watch(
 633        &self,
 634        path: &Path,
 635        latency: Duration,
 636    ) -> (
 637        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 638        Arc<dyn Watcher>,
 639    ) {
 640        use fsevent::StreamFlags;
 641
 642        let (events_tx, events_rx) = smol::channel::unbounded();
 643        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 644        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 645            events_tx,
 646            Arc::downgrade(&handles),
 647            latency,
 648        ));
 649        watcher.add(path).expect("handles can't be dropped");
 650
 651        (
 652            Box::pin(
 653                events_rx
 654                    .map(|events| {
 655                        events
 656                            .into_iter()
 657                            .map(|event| {
 658                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 659                                    Some(PathEventKind::Removed)
 660                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 661                                    Some(PathEventKind::Created)
 662                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
 663                                    Some(PathEventKind::Changed)
 664                                } else {
 665                                    None
 666                                };
 667                                PathEvent {
 668                                    path: event.path,
 669                                    kind,
 670                                }
 671                            })
 672                            .collect()
 673                    })
 674                    .chain(futures::stream::once(async move {
 675                        drop(handles);
 676                        vec![]
 677                    })),
 678            ),
 679            watcher,
 680        )
 681    }
 682
 683    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 684    async fn watch(
 685        &self,
 686        path: &Path,
 687        latency: Duration,
 688    ) -> (
 689        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 690        Arc<dyn Watcher>,
 691    ) {
 692        use parking_lot::Mutex;
 693
 694        let (tx, rx) = smol::channel::unbounded();
 695        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 696        let watcher = Arc::new(linux_watcher::LinuxWatcher::new(tx, pending_paths.clone()));
 697
 698        if watcher.add(path).is_err() {
 699            // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 700            if let Some(parent) = path.parent() {
 701                if let Err(e) = watcher.add(parent) {
 702                    log::warn!("Failed to watch: {e}");
 703                }
 704            }
 705        }
 706
 707        // Check if path is a symlink and follow the target parent
 708        if let Some(target) = self.read_link(&path).await.ok() {
 709            watcher.add(&target).ok();
 710            if let Some(parent) = target.parent() {
 711                watcher.add(parent).log_err();
 712            }
 713        }
 714
 715        (
 716            Box::pin(rx.filter_map({
 717                let watcher = watcher.clone();
 718                move |_| {
 719                    let _ = watcher.clone();
 720                    let pending_paths = pending_paths.clone();
 721                    async move {
 722                        smol::Timer::after(latency).await;
 723                        let paths = std::mem::take(&mut *pending_paths.lock());
 724                        (!paths.is_empty()).then_some(paths)
 725                    }
 726                }
 727            })),
 728            watcher,
 729        )
 730    }
 731
 732    #[cfg(target_os = "windows")]
 733    async fn watch(
 734        &self,
 735        path: &Path,
 736        _latency: Duration,
 737    ) -> (
 738        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 739        Arc<dyn Watcher>,
 740    ) {
 741        use notify::{EventKind, Watcher};
 742
 743        let (tx, rx) = smol::channel::unbounded();
 744
 745        let mut file_watcher = notify::recommended_watcher({
 746            let tx = tx.clone();
 747            move |event: Result<notify::Event, _>| {
 748                if let Some(event) = event.log_err() {
 749                    let kind = match event.kind {
 750                        EventKind::Create(_) => Some(PathEventKind::Created),
 751                        EventKind::Modify(_) => Some(PathEventKind::Changed),
 752                        EventKind::Remove(_) => Some(PathEventKind::Removed),
 753                        _ => None,
 754                    };
 755
 756                    tx.try_send(
 757                        event
 758                            .paths
 759                            .into_iter()
 760                            .map(|path| PathEvent { path, kind })
 761                            .collect::<Vec<_>>(),
 762                    )
 763                    .ok();
 764                }
 765            }
 766        })
 767        .expect("Could not start file watcher");
 768
 769        file_watcher
 770            .watch(path, notify::RecursiveMode::Recursive)
 771            .log_err();
 772
 773        (
 774            Box::pin(rx.chain(futures::stream::once(async move {
 775                drop(file_watcher);
 776                vec![]
 777            }))),
 778            Arc::new(RealWatcher {}),
 779        )
 780    }
 781
 782    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
 783        // with libgit2, we can open git repo from an existing work dir
 784        // https://libgit2.org/docs/reference/main/repository/git_repository_open.html
 785        let workdir_root = dotgit_path.parent()?;
 786        let repo = git2::Repository::open(workdir_root).log_err()?;
 787        Some(Arc::new(RealGitRepository::new(
 788            repo,
 789            self.git_binary_path.clone(),
 790            self.git_hosting_provider_registry.clone(),
 791        )))
 792    }
 793
 794    fn is_fake(&self) -> bool {
 795        false
 796    }
 797
 798    /// Checks whether the file system is case sensitive by attempting to create two files
 799    /// that have the same name except for the casing.
 800    ///
 801    /// It creates both files in a temporary directory it removes at the end.
 802    async fn is_case_sensitive(&self) -> Result<bool> {
 803        let temp_dir = TempDir::new()?;
 804        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 805        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 806
 807        let create_opts = CreateOptions {
 808            overwrite: false,
 809            ignore_if_exists: false,
 810        };
 811
 812        // Create file1
 813        self.create_file(&test_file_1, create_opts).await?;
 814
 815        // Now check whether it's possible to create file2
 816        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 817            Ok(_) => Ok(true),
 818            Err(e) => {
 819                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 820                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 821                        Ok(false)
 822                    } else {
 823                        Err(e)
 824                    }
 825                } else {
 826                    Err(e)
 827                }
 828            }
 829        };
 830
 831        temp_dir.close()?;
 832        case_sensitive
 833    }
 834}
 835
 836#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
 837impl Watcher for RealWatcher {
 838    fn add(&self, _: &Path) -> Result<()> {
 839        Ok(())
 840    }
 841
 842    fn remove(&self, _: &Path) -> Result<()> {
 843        Ok(())
 844    }
 845}
 846
 847#[cfg(any(test, feature = "test-support"))]
 848pub struct FakeFs {
 849    this: std::sync::Weak<Self>,
 850    // Use an unfair lock to ensure tests are deterministic.
 851    state: Mutex<FakeFsState>,
 852    executor: gpui::BackgroundExecutor,
 853}
 854
 855#[cfg(any(test, feature = "test-support"))]
 856struct FakeFsState {
 857    root: Arc<Mutex<FakeFsEntry>>,
 858    next_inode: u64,
 859    next_mtime: SystemTime,
 860    git_event_tx: smol::channel::Sender<PathBuf>,
 861    event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
 862    events_paused: bool,
 863    buffered_events: Vec<PathEvent>,
 864    metadata_call_count: usize,
 865    read_dir_call_count: usize,
 866    moves: std::collections::HashMap<u64, PathBuf>,
 867}
 868
 869#[cfg(any(test, feature = "test-support"))]
 870#[derive(Debug)]
 871enum FakeFsEntry {
 872    File {
 873        inode: u64,
 874        mtime: MTime,
 875        len: u64,
 876        content: Vec<u8>,
 877    },
 878    Dir {
 879        inode: u64,
 880        mtime: MTime,
 881        len: u64,
 882        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 883        git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
 884    },
 885    Symlink {
 886        target: PathBuf,
 887    },
 888}
 889
 890#[cfg(any(test, feature = "test-support"))]
 891impl FakeFsState {
 892    fn get_and_increment_mtime(&mut self) -> MTime {
 893        let mtime = self.next_mtime;
 894        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
 895        MTime(mtime)
 896    }
 897
 898    fn get_and_increment_inode(&mut self) -> u64 {
 899        let inode = self.next_inode;
 900        self.next_inode += 1;
 901        inode
 902    }
 903
 904    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 905        Ok(self
 906            .try_read_path(target, true)
 907            .ok_or_else(|| {
 908                anyhow!(io::Error::new(
 909                    io::ErrorKind::NotFound,
 910                    format!("not found: {}", target.display())
 911                ))
 912            })?
 913            .0)
 914    }
 915
 916    fn try_read_path(
 917        &self,
 918        target: &Path,
 919        follow_symlink: bool,
 920    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 921        let mut path = target.to_path_buf();
 922        let mut canonical_path = PathBuf::new();
 923        let mut entry_stack = Vec::new();
 924        'outer: loop {
 925            let mut path_components = path.components().peekable();
 926            let mut prefix = None;
 927            while let Some(component) = path_components.next() {
 928                match component {
 929                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
 930                    Component::RootDir => {
 931                        entry_stack.clear();
 932                        entry_stack.push(self.root.clone());
 933                        canonical_path.clear();
 934                        match prefix {
 935                            Some(prefix_component) => {
 936                                canonical_path = PathBuf::from(prefix_component.as_os_str());
 937                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
 938                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
 939                            }
 940                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
 941                        }
 942                    }
 943                    Component::CurDir => {}
 944                    Component::ParentDir => {
 945                        entry_stack.pop()?;
 946                        canonical_path.pop();
 947                    }
 948                    Component::Normal(name) => {
 949                        let current_entry = entry_stack.last().cloned()?;
 950                        let current_entry = current_entry.lock();
 951                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 952                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 953                            if path_components.peek().is_some() || follow_symlink {
 954                                let entry = entry.lock();
 955                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 956                                    let mut target = target.clone();
 957                                    target.extend(path_components);
 958                                    path = target;
 959                                    continue 'outer;
 960                                }
 961                            }
 962                            entry_stack.push(entry.clone());
 963                            canonical_path = canonical_path.join(name);
 964                        } else {
 965                            return None;
 966                        }
 967                    }
 968                }
 969            }
 970            break;
 971        }
 972        Some((entry_stack.pop()?, canonical_path))
 973    }
 974
 975    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 976    where
 977        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 978    {
 979        let path = normalize_path(path);
 980        let filename = path
 981            .file_name()
 982            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 983        let parent_path = path.parent().unwrap();
 984
 985        let parent = self.read_path(parent_path)?;
 986        let mut parent = parent.lock();
 987        let new_entry = parent
 988            .dir_entries(parent_path)?
 989            .entry(filename.to_str().unwrap().into());
 990        callback(new_entry)
 991    }
 992
 993    fn emit_event<I, T>(&mut self, paths: I)
 994    where
 995        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
 996        T: Into<PathBuf>,
 997    {
 998        self.buffered_events
 999            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1000                path: path.into(),
1001                kind,
1002            }));
1003
1004        if !self.events_paused {
1005            self.flush_events(self.buffered_events.len());
1006        }
1007    }
1008
1009    fn flush_events(&mut self, mut count: usize) {
1010        count = count.min(self.buffered_events.len());
1011        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1012        self.event_txs.retain(|tx| {
1013            let _ = tx.try_send(events.clone());
1014            !tx.is_closed()
1015        });
1016    }
1017}
1018
1019#[cfg(any(test, feature = "test-support"))]
1020pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1021    std::sync::LazyLock::new(|| OsStr::new(".git"));
1022
1023#[cfg(any(test, feature = "test-support"))]
1024impl FakeFs {
1025    /// We need to use something large enough for Windows and Unix to consider this a new file.
1026    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1027    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1028
1029    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1030        let (tx, mut rx) = smol::channel::bounded::<PathBuf>(10);
1031
1032        let this = Arc::new_cyclic(|this| Self {
1033            this: this.clone(),
1034            executor: executor.clone(),
1035            state: Mutex::new(FakeFsState {
1036                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
1037                    inode: 0,
1038                    mtime: MTime(UNIX_EPOCH),
1039                    len: 0,
1040                    entries: Default::default(),
1041                    git_repo_state: None,
1042                })),
1043                git_event_tx: tx,
1044                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1045                next_inode: 1,
1046                event_txs: Default::default(),
1047                buffered_events: Vec::new(),
1048                events_paused: false,
1049                read_dir_call_count: 0,
1050                metadata_call_count: 0,
1051                moves: Default::default(),
1052            }),
1053        });
1054
1055        executor.spawn({
1056            let this = this.clone();
1057            async move {
1058                while let Some(git_event) = rx.next().await {
1059                    if let Some(mut state) = this.state.try_lock() {
1060                        state.emit_event([(git_event, None)]);
1061                    } else {
1062                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1063                    }
1064                }
1065            }
1066        }).detach();
1067
1068        this
1069    }
1070
1071    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1072        let mut state = self.state.lock();
1073        state.next_mtime = next_mtime;
1074    }
1075
1076    pub fn get_and_increment_mtime(&self) -> MTime {
1077        let mut state = self.state.lock();
1078        state.get_and_increment_mtime()
1079    }
1080
1081    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1082        let mut state = self.state.lock();
1083        let path = path.as_ref();
1084        let new_mtime = state.get_and_increment_mtime();
1085        let new_inode = state.get_and_increment_inode();
1086        state
1087            .write_path(path, move |entry| {
1088                match entry {
1089                    btree_map::Entry::Vacant(e) => {
1090                        e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1091                            inode: new_inode,
1092                            mtime: new_mtime,
1093                            content: Vec::new(),
1094                            len: 0,
1095                        })));
1096                    }
1097                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1098                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1099                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1100                        FakeFsEntry::Symlink { .. } => {}
1101                    },
1102                }
1103                Ok(())
1104            })
1105            .unwrap();
1106        state.emit_event([(path.to_path_buf(), None)]);
1107    }
1108
1109    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1110        self.write_file_internal(path, content).unwrap()
1111    }
1112
1113    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1114        let mut state = self.state.lock();
1115        let path = path.as_ref();
1116        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1117        state
1118            .write_path(path.as_ref(), move |e| match e {
1119                btree_map::Entry::Vacant(e) => {
1120                    e.insert(file);
1121                    Ok(())
1122                }
1123                btree_map::Entry::Occupied(mut e) => {
1124                    *e.get_mut() = file;
1125                    Ok(())
1126                }
1127            })
1128            .unwrap();
1129        state.emit_event([(path, None)]);
1130    }
1131
1132    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1133        let mut state = self.state.lock();
1134        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1135            inode: state.get_and_increment_inode(),
1136            mtime: state.get_and_increment_mtime(),
1137            len: content.len() as u64,
1138            content,
1139        }));
1140        let mut kind = None;
1141        state.write_path(path.as_ref(), {
1142            let kind = &mut kind;
1143            move |entry| {
1144                match entry {
1145                    btree_map::Entry::Vacant(e) => {
1146                        *kind = Some(PathEventKind::Created);
1147                        e.insert(file);
1148                    }
1149                    btree_map::Entry::Occupied(mut e) => {
1150                        *kind = Some(PathEventKind::Changed);
1151                        *e.get_mut() = file;
1152                    }
1153                }
1154                Ok(())
1155            }
1156        })?;
1157        state.emit_event([(path.as_ref(), kind)]);
1158        Ok(())
1159    }
1160
1161    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1162        let path = path.as_ref();
1163        let path = normalize_path(path);
1164        let state = self.state.lock();
1165        let entry = state.read_path(&path)?;
1166        let entry = entry.lock();
1167        entry.file_content(&path).cloned()
1168    }
1169
1170    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1171        let path = path.as_ref();
1172        let path = normalize_path(path);
1173        self.simulate_random_delay().await;
1174        let state = self.state.lock();
1175        let entry = state.read_path(&path)?;
1176        let entry = entry.lock();
1177        entry.file_content(&path).cloned()
1178    }
1179
1180    pub fn pause_events(&self) {
1181        self.state.lock().events_paused = true;
1182    }
1183
1184    pub fn buffered_event_count(&self) -> usize {
1185        self.state.lock().buffered_events.len()
1186    }
1187
1188    pub fn flush_events(&self, count: usize) {
1189        self.state.lock().flush_events(count);
1190    }
1191
1192    #[must_use]
1193    pub fn insert_tree<'a>(
1194        &'a self,
1195        path: impl 'a + AsRef<Path> + Send,
1196        tree: serde_json::Value,
1197    ) -> futures::future::BoxFuture<'a, ()> {
1198        use futures::FutureExt as _;
1199        use serde_json::Value::*;
1200
1201        async move {
1202            let path = path.as_ref();
1203
1204            match tree {
1205                Object(map) => {
1206                    self.create_dir(path).await.unwrap();
1207                    for (name, contents) in map {
1208                        let mut path = PathBuf::from(path);
1209                        path.push(name);
1210                        self.insert_tree(&path, contents).await;
1211                    }
1212                }
1213                Null => {
1214                    self.create_dir(path).await.unwrap();
1215                }
1216                String(contents) => {
1217                    self.insert_file(&path, contents.into_bytes()).await;
1218                }
1219                _ => {
1220                    panic!("JSON object must contain only objects, strings, or null");
1221                }
1222            }
1223        }
1224        .boxed()
1225    }
1226
1227    pub fn insert_tree_from_real_fs<'a>(
1228        &'a self,
1229        path: impl 'a + AsRef<Path> + Send,
1230        src_path: impl 'a + AsRef<Path> + Send,
1231    ) -> futures::future::BoxFuture<'a, ()> {
1232        use futures::FutureExt as _;
1233
1234        async move {
1235            let path = path.as_ref();
1236            if std::fs::metadata(&src_path).unwrap().is_file() {
1237                let contents = std::fs::read(src_path).unwrap();
1238                self.insert_file(path, contents).await;
1239            } else {
1240                self.create_dir(path).await.unwrap();
1241                for entry in std::fs::read_dir(&src_path).unwrap() {
1242                    let entry = entry.unwrap();
1243                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1244                        .await;
1245                }
1246            }
1247        }
1248        .boxed()
1249    }
1250
1251    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1252    where
1253        F: FnOnce(&mut FakeGitRepositoryState),
1254    {
1255        let mut state = self.state.lock();
1256        let entry = state.read_path(dot_git).unwrap();
1257        let mut entry = entry.lock();
1258
1259        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1260            let repo_state = git_repo_state.get_or_insert_with(|| {
1261                Arc::new(Mutex::new(FakeGitRepositoryState::new(
1262                    dot_git.to_path_buf(),
1263                    state.git_event_tx.clone(),
1264                )))
1265            });
1266            let mut repo_state = repo_state.lock();
1267
1268            f(&mut repo_state);
1269
1270            if emit_git_event {
1271                state.emit_event([(dot_git, None)]);
1272            }
1273        } else {
1274            panic!("not a directory");
1275        }
1276    }
1277
1278    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1279        self.with_git_state(dot_git, true, |state| {
1280            let branch = branch.map(Into::into);
1281            state.branches.extend(branch.clone());
1282            state.current_branch_name = branch.map(Into::into)
1283        })
1284    }
1285
1286    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1287        self.with_git_state(dot_git, true, |state| {
1288            if let Some(first) = branches.first() {
1289                if state.current_branch_name.is_none() {
1290                    state.current_branch_name = Some(first.to_string())
1291                }
1292            }
1293            state
1294                .branches
1295                .extend(branches.iter().map(ToString::to_string));
1296        })
1297    }
1298
1299    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1300        self.with_git_state(dot_git, true, |state| {
1301            state.index_contents.clear();
1302            state.index_contents.extend(
1303                head_state
1304                    .iter()
1305                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
1306            );
1307        });
1308    }
1309
1310    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1311        self.with_git_state(dot_git, true, |state| {
1312            state.blames.clear();
1313            state.blames.extend(
1314                blames
1315                    .into_iter()
1316                    .map(|(path, blame)| (path.to_path_buf(), blame)),
1317            );
1318        });
1319    }
1320
1321    pub fn set_status_for_repo_via_working_copy_change(
1322        &self,
1323        dot_git: &Path,
1324        statuses: &[(&Path, GitFileStatus)],
1325    ) {
1326        self.with_git_state(dot_git, false, |state| {
1327            state.worktree_statuses.clear();
1328            state.worktree_statuses.extend(
1329                statuses
1330                    .iter()
1331                    .map(|(path, content)| ((**path).into(), *content)),
1332            );
1333        });
1334        self.state.lock().emit_event(
1335            statuses
1336                .iter()
1337                .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1338        );
1339    }
1340
1341    pub fn set_status_for_repo_via_git_operation(
1342        &self,
1343        dot_git: &Path,
1344        statuses: &[(&Path, GitFileStatus)],
1345    ) {
1346        self.with_git_state(dot_git, true, |state| {
1347            state.worktree_statuses.clear();
1348            state.worktree_statuses.extend(
1349                statuses
1350                    .iter()
1351                    .map(|(path, content)| ((**path).into(), *content)),
1352            );
1353        });
1354    }
1355
1356    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1357        let mut result = Vec::new();
1358        let mut queue = collections::VecDeque::new();
1359        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1360        while let Some((path, entry)) = queue.pop_front() {
1361            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1362                for (name, entry) in entries {
1363                    queue.push_back((path.join(name), entry.clone()));
1364                }
1365            }
1366            if include_dot_git
1367                || !path
1368                    .components()
1369                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1370            {
1371                result.push(path);
1372            }
1373        }
1374        result
1375    }
1376
1377    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1378        let mut result = Vec::new();
1379        let mut queue = collections::VecDeque::new();
1380        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1381        while let Some((path, entry)) = queue.pop_front() {
1382            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1383                for (name, entry) in entries {
1384                    queue.push_back((path.join(name), entry.clone()));
1385                }
1386                if include_dot_git
1387                    || !path
1388                        .components()
1389                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1390                {
1391                    result.push(path);
1392                }
1393            }
1394        }
1395        result
1396    }
1397
1398    pub fn files(&self) -> Vec<PathBuf> {
1399        let mut result = Vec::new();
1400        let mut queue = collections::VecDeque::new();
1401        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1402        while let Some((path, entry)) = queue.pop_front() {
1403            let e = entry.lock();
1404            match &*e {
1405                FakeFsEntry::File { .. } => result.push(path),
1406                FakeFsEntry::Dir { entries, .. } => {
1407                    for (name, entry) in entries {
1408                        queue.push_back((path.join(name), entry.clone()));
1409                    }
1410                }
1411                FakeFsEntry::Symlink { .. } => {}
1412            }
1413        }
1414        result
1415    }
1416
1417    /// How many `read_dir` calls have been issued.
1418    pub fn read_dir_call_count(&self) -> usize {
1419        self.state.lock().read_dir_call_count
1420    }
1421
1422    /// How many `metadata` calls have been issued.
1423    pub fn metadata_call_count(&self) -> usize {
1424        self.state.lock().metadata_call_count
1425    }
1426
1427    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1428        self.executor.simulate_random_delay()
1429    }
1430}
1431
1432#[cfg(any(test, feature = "test-support"))]
1433impl FakeFsEntry {
1434    fn is_file(&self) -> bool {
1435        matches!(self, Self::File { .. })
1436    }
1437
1438    fn is_symlink(&self) -> bool {
1439        matches!(self, Self::Symlink { .. })
1440    }
1441
1442    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1443        if let Self::File { content, .. } = self {
1444            Ok(content)
1445        } else {
1446            Err(anyhow!("not a file: {}", path.display()))
1447        }
1448    }
1449
1450    fn dir_entries(
1451        &mut self,
1452        path: &Path,
1453    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1454        if let Self::Dir { entries, .. } = self {
1455            Ok(entries)
1456        } else {
1457            Err(anyhow!("not a directory: {}", path.display()))
1458        }
1459    }
1460}
1461
1462#[cfg(any(test, feature = "test-support"))]
1463struct FakeWatcher {}
1464
1465#[cfg(any(test, feature = "test-support"))]
1466impl Watcher for FakeWatcher {
1467    fn add(&self, _: &Path) -> Result<()> {
1468        Ok(())
1469    }
1470
1471    fn remove(&self, _: &Path) -> Result<()> {
1472        Ok(())
1473    }
1474}
1475
1476#[cfg(any(test, feature = "test-support"))]
1477#[derive(Debug)]
1478struct FakeHandle {
1479    inode: u64,
1480}
1481
1482#[cfg(any(test, feature = "test-support"))]
1483impl FileHandle for FakeHandle {
1484    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1485        let fs = fs.as_fake();
1486        let state = fs.state.lock();
1487        let Some(target) = state.moves.get(&self.inode) else {
1488            anyhow::bail!("fake fd not moved")
1489        };
1490
1491        if state.try_read_path(&target, false).is_some() {
1492            return Ok(target.clone());
1493        }
1494        anyhow::bail!("fake fd target not found")
1495    }
1496}
1497
1498#[cfg(any(test, feature = "test-support"))]
1499#[async_trait::async_trait]
1500impl Fs for FakeFs {
1501    async fn create_dir(&self, path: &Path) -> Result<()> {
1502        self.simulate_random_delay().await;
1503
1504        let mut created_dirs = Vec::new();
1505        let mut cur_path = PathBuf::new();
1506        for component in path.components() {
1507            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1508            cur_path.push(component);
1509            if should_skip {
1510                continue;
1511            }
1512            let mut state = self.state.lock();
1513
1514            let inode = state.get_and_increment_inode();
1515            let mtime = state.get_and_increment_mtime();
1516            state.write_path(&cur_path, |entry| {
1517                entry.or_insert_with(|| {
1518                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1519                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1520                        inode,
1521                        mtime,
1522                        len: 0,
1523                        entries: Default::default(),
1524                        git_repo_state: None,
1525                    }))
1526                });
1527                Ok(())
1528            })?
1529        }
1530
1531        self.state.lock().emit_event(created_dirs);
1532        Ok(())
1533    }
1534
1535    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1536        self.simulate_random_delay().await;
1537        let mut state = self.state.lock();
1538        let inode = state.get_and_increment_inode();
1539        let mtime = state.get_and_increment_mtime();
1540        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1541            inode,
1542            mtime,
1543            len: 0,
1544            content: Vec::new(),
1545        }));
1546        let mut kind = Some(PathEventKind::Created);
1547        state.write_path(path, |entry| {
1548            match entry {
1549                btree_map::Entry::Occupied(mut e) => {
1550                    if options.overwrite {
1551                        kind = Some(PathEventKind::Changed);
1552                        *e.get_mut() = file;
1553                    } else if !options.ignore_if_exists {
1554                        return Err(anyhow!("path already exists: {}", path.display()));
1555                    }
1556                }
1557                btree_map::Entry::Vacant(e) => {
1558                    e.insert(file);
1559                }
1560            }
1561            Ok(())
1562        })?;
1563        state.emit_event([(path, kind)]);
1564        Ok(())
1565    }
1566
1567    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1568        let mut state = self.state.lock();
1569        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1570        state
1571            .write_path(path.as_ref(), move |e| match e {
1572                btree_map::Entry::Vacant(e) => {
1573                    e.insert(file);
1574                    Ok(())
1575                }
1576                btree_map::Entry::Occupied(mut e) => {
1577                    *e.get_mut() = file;
1578                    Ok(())
1579                }
1580            })
1581            .unwrap();
1582        state.emit_event([(path, None)]);
1583
1584        Ok(())
1585    }
1586
1587    async fn create_file_with(
1588        &self,
1589        path: &Path,
1590        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1591    ) -> Result<()> {
1592        let mut bytes = Vec::new();
1593        content.read_to_end(&mut bytes).await?;
1594        self.write_file_internal(path, bytes)?;
1595        Ok(())
1596    }
1597
1598    async fn extract_tar_file(
1599        &self,
1600        path: &Path,
1601        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1602    ) -> Result<()> {
1603        let mut entries = content.entries()?;
1604        while let Some(entry) = entries.next().await {
1605            let mut entry = entry?;
1606            if entry.header().entry_type().is_file() {
1607                let path = path.join(entry.path()?.as_ref());
1608                let mut bytes = Vec::new();
1609                entry.read_to_end(&mut bytes).await?;
1610                self.create_dir(path.parent().unwrap()).await?;
1611                self.write_file_internal(&path, bytes)?;
1612            }
1613        }
1614        Ok(())
1615    }
1616
1617    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1618        self.simulate_random_delay().await;
1619
1620        let old_path = normalize_path(old_path);
1621        let new_path = normalize_path(new_path);
1622
1623        let mut state = self.state.lock();
1624        let moved_entry = state.write_path(&old_path, |e| {
1625            if let btree_map::Entry::Occupied(e) = e {
1626                Ok(e.get().clone())
1627            } else {
1628                Err(anyhow!("path does not exist: {}", &old_path.display()))
1629            }
1630        })?;
1631
1632        let inode = match *moved_entry.lock() {
1633            FakeFsEntry::File { inode, .. } => inode,
1634            FakeFsEntry::Dir { inode, .. } => inode,
1635            _ => 0,
1636        };
1637
1638        state.moves.insert(inode, new_path.clone());
1639
1640        state.write_path(&new_path, |e| {
1641            match e {
1642                btree_map::Entry::Occupied(mut e) => {
1643                    if options.overwrite {
1644                        *e.get_mut() = moved_entry;
1645                    } else if !options.ignore_if_exists {
1646                        return Err(anyhow!("path already exists: {}", new_path.display()));
1647                    }
1648                }
1649                btree_map::Entry::Vacant(e) => {
1650                    e.insert(moved_entry);
1651                }
1652            }
1653            Ok(())
1654        })?;
1655
1656        state
1657            .write_path(&old_path, |e| {
1658                if let btree_map::Entry::Occupied(e) = e {
1659                    Ok(e.remove())
1660                } else {
1661                    unreachable!()
1662                }
1663            })
1664            .unwrap();
1665
1666        state.emit_event([
1667            (old_path, Some(PathEventKind::Removed)),
1668            (new_path, Some(PathEventKind::Created)),
1669        ]);
1670        Ok(())
1671    }
1672
1673    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1674        self.simulate_random_delay().await;
1675
1676        let source = normalize_path(source);
1677        let target = normalize_path(target);
1678        let mut state = self.state.lock();
1679        let mtime = state.get_and_increment_mtime();
1680        let inode = state.get_and_increment_inode();
1681        let source_entry = state.read_path(&source)?;
1682        let content = source_entry.lock().file_content(&source)?.clone();
1683        let mut kind = Some(PathEventKind::Created);
1684        state.write_path(&target, |e| match e {
1685            btree_map::Entry::Occupied(e) => {
1686                if options.overwrite {
1687                    kind = Some(PathEventKind::Changed);
1688                    Ok(Some(e.get().clone()))
1689                } else if !options.ignore_if_exists {
1690                    return Err(anyhow!("{target:?} already exists"));
1691                } else {
1692                    Ok(None)
1693                }
1694            }
1695            btree_map::Entry::Vacant(e) => Ok(Some(
1696                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1697                    inode,
1698                    mtime,
1699                    len: content.len() as u64,
1700                    content,
1701                })))
1702                .clone(),
1703            )),
1704        })?;
1705        state.emit_event([(target, kind)]);
1706        Ok(())
1707    }
1708
1709    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1710        self.simulate_random_delay().await;
1711
1712        let path = normalize_path(path);
1713        let parent_path = path
1714            .parent()
1715            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1716        let base_name = path.file_name().unwrap();
1717
1718        let mut state = self.state.lock();
1719        let parent_entry = state.read_path(parent_path)?;
1720        let mut parent_entry = parent_entry.lock();
1721        let entry = parent_entry
1722            .dir_entries(parent_path)?
1723            .entry(base_name.to_str().unwrap().into());
1724
1725        match entry {
1726            btree_map::Entry::Vacant(_) => {
1727                if !options.ignore_if_not_exists {
1728                    return Err(anyhow!("{path:?} does not exist"));
1729                }
1730            }
1731            btree_map::Entry::Occupied(e) => {
1732                {
1733                    let mut entry = e.get().lock();
1734                    let children = entry.dir_entries(&path)?;
1735                    if !options.recursive && !children.is_empty() {
1736                        return Err(anyhow!("{path:?} is not empty"));
1737                    }
1738                }
1739                e.remove();
1740            }
1741        }
1742        state.emit_event([(path, Some(PathEventKind::Removed))]);
1743        Ok(())
1744    }
1745
1746    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1747        self.simulate_random_delay().await;
1748
1749        let path = normalize_path(path);
1750        let parent_path = path
1751            .parent()
1752            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1753        let base_name = path.file_name().unwrap();
1754        let mut state = self.state.lock();
1755        let parent_entry = state.read_path(parent_path)?;
1756        let mut parent_entry = parent_entry.lock();
1757        let entry = parent_entry
1758            .dir_entries(parent_path)?
1759            .entry(base_name.to_str().unwrap().into());
1760        match entry {
1761            btree_map::Entry::Vacant(_) => {
1762                if !options.ignore_if_not_exists {
1763                    return Err(anyhow!("{path:?} does not exist"));
1764                }
1765            }
1766            btree_map::Entry::Occupied(e) => {
1767                e.get().lock().file_content(&path)?;
1768                e.remove();
1769            }
1770        }
1771        state.emit_event([(path, Some(PathEventKind::Removed))]);
1772        Ok(())
1773    }
1774
1775    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1776        let bytes = self.load_internal(path).await?;
1777        Ok(Box::new(io::Cursor::new(bytes)))
1778    }
1779
1780    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1781        self.simulate_random_delay().await;
1782        let state = self.state.lock();
1783        let entry = state.read_path(&path)?;
1784        let entry = entry.lock();
1785        let inode = match *entry {
1786            FakeFsEntry::File { inode, .. } => inode,
1787            FakeFsEntry::Dir { inode, .. } => inode,
1788            _ => unreachable!(),
1789        };
1790        Ok(Arc::new(FakeHandle { inode }))
1791    }
1792
1793    async fn load(&self, path: &Path) -> Result<String> {
1794        let content = self.load_internal(path).await?;
1795        Ok(String::from_utf8(content.clone())?)
1796    }
1797
1798    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1799        self.load_internal(path).await
1800    }
1801
1802    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1803        self.simulate_random_delay().await;
1804        let path = normalize_path(path.as_path());
1805        self.write_file_internal(path, data.into_bytes())?;
1806        Ok(())
1807    }
1808
1809    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1810        self.simulate_random_delay().await;
1811        let path = normalize_path(path);
1812        let content = chunks(text, line_ending).collect::<String>();
1813        if let Some(path) = path.parent() {
1814            self.create_dir(path).await?;
1815        }
1816        self.write_file_internal(path, content.into_bytes())?;
1817        Ok(())
1818    }
1819
1820    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1821        let path = normalize_path(path);
1822        self.simulate_random_delay().await;
1823        let state = self.state.lock();
1824        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1825            Ok(canonical_path)
1826        } else {
1827            Err(anyhow!("path does not exist: {}", path.display()))
1828        }
1829    }
1830
1831    async fn is_file(&self, path: &Path) -> bool {
1832        let path = normalize_path(path);
1833        self.simulate_random_delay().await;
1834        let state = self.state.lock();
1835        if let Some((entry, _)) = state.try_read_path(&path, true) {
1836            entry.lock().is_file()
1837        } else {
1838            false
1839        }
1840    }
1841
1842    async fn is_dir(&self, path: &Path) -> bool {
1843        self.metadata(path)
1844            .await
1845            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1846    }
1847
1848    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1849        self.simulate_random_delay().await;
1850        let path = normalize_path(path);
1851        let mut state = self.state.lock();
1852        state.metadata_call_count += 1;
1853        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1854            let is_symlink = entry.lock().is_symlink();
1855            if is_symlink {
1856                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1857                    entry = e;
1858                } else {
1859                    return Ok(None);
1860                }
1861            }
1862
1863            let entry = entry.lock();
1864            Ok(Some(match &*entry {
1865                FakeFsEntry::File {
1866                    inode, mtime, len, ..
1867                } => Metadata {
1868                    inode: *inode,
1869                    mtime: *mtime,
1870                    len: *len,
1871                    is_dir: false,
1872                    is_symlink,
1873                    is_fifo: false,
1874                },
1875                FakeFsEntry::Dir {
1876                    inode, mtime, len, ..
1877                } => Metadata {
1878                    inode: *inode,
1879                    mtime: *mtime,
1880                    len: *len,
1881                    is_dir: true,
1882                    is_symlink,
1883                    is_fifo: false,
1884                },
1885                FakeFsEntry::Symlink { .. } => unreachable!(),
1886            }))
1887        } else {
1888            Ok(None)
1889        }
1890    }
1891
1892    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1893        self.simulate_random_delay().await;
1894        let path = normalize_path(path);
1895        let state = self.state.lock();
1896        if let Some((entry, _)) = state.try_read_path(&path, false) {
1897            let entry = entry.lock();
1898            if let FakeFsEntry::Symlink { target } = &*entry {
1899                Ok(target.clone())
1900            } else {
1901                Err(anyhow!("not a symlink: {}", path.display()))
1902            }
1903        } else {
1904            Err(anyhow!("path does not exist: {}", path.display()))
1905        }
1906    }
1907
1908    async fn read_dir(
1909        &self,
1910        path: &Path,
1911    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1912        self.simulate_random_delay().await;
1913        let path = normalize_path(path);
1914        let mut state = self.state.lock();
1915        state.read_dir_call_count += 1;
1916        let entry = state.read_path(&path)?;
1917        let mut entry = entry.lock();
1918        let children = entry.dir_entries(&path)?;
1919        let paths = children
1920            .keys()
1921            .map(|file_name| Ok(path.join(file_name)))
1922            .collect::<Vec<_>>();
1923        Ok(Box::pin(futures::stream::iter(paths)))
1924    }
1925
1926    async fn watch(
1927        &self,
1928        path: &Path,
1929        _: Duration,
1930    ) -> (
1931        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1932        Arc<dyn Watcher>,
1933    ) {
1934        self.simulate_random_delay().await;
1935        let (tx, rx) = smol::channel::unbounded();
1936        self.state.lock().event_txs.push(tx);
1937        let path = path.to_path_buf();
1938        let executor = self.executor.clone();
1939        (
1940            Box::pin(futures::StreamExt::filter(rx, move |events| {
1941                let result = events
1942                    .iter()
1943                    .any(|evt_path| evt_path.path.starts_with(&path));
1944                let executor = executor.clone();
1945                async move {
1946                    executor.simulate_random_delay().await;
1947                    result
1948                }
1949            })),
1950            Arc::new(FakeWatcher {}),
1951        )
1952    }
1953
1954    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1955        let state = self.state.lock();
1956        let entry = state.read_path(abs_dot_git).unwrap();
1957        let mut entry = entry.lock();
1958        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1959            let state = git_repo_state
1960                .get_or_insert_with(|| {
1961                    Arc::new(Mutex::new(FakeGitRepositoryState::new(
1962                        abs_dot_git.to_path_buf(),
1963                        state.git_event_tx.clone(),
1964                    )))
1965                })
1966                .clone();
1967            Some(git::repository::FakeGitRepository::open(state))
1968        } else {
1969            None
1970        }
1971    }
1972
1973    fn is_fake(&self) -> bool {
1974        true
1975    }
1976
1977    async fn is_case_sensitive(&self) -> Result<bool> {
1978        Ok(true)
1979    }
1980
1981    #[cfg(any(test, feature = "test-support"))]
1982    fn as_fake(&self) -> Arc<FakeFs> {
1983        self.this.upgrade().unwrap()
1984    }
1985}
1986
1987fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1988    rope.chunks().flat_map(move |chunk| {
1989        let mut newline = false;
1990        chunk.split('\n').flat_map(move |line| {
1991            let ending = if newline {
1992                Some(line_ending.as_str())
1993            } else {
1994                None
1995            };
1996            newline = true;
1997            ending.into_iter().chain([line])
1998        })
1999    })
2000}
2001
2002pub fn normalize_path(path: &Path) -> PathBuf {
2003    let mut components = path.components().peekable();
2004    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2005        components.next();
2006        PathBuf::from(c.as_os_str())
2007    } else {
2008        PathBuf::new()
2009    };
2010
2011    for component in components {
2012        match component {
2013            Component::Prefix(..) => unreachable!(),
2014            Component::RootDir => {
2015                ret.push(component.as_os_str());
2016            }
2017            Component::CurDir => {}
2018            Component::ParentDir => {
2019                ret.pop();
2020            }
2021            Component::Normal(c) => {
2022                ret.push(c);
2023            }
2024        }
2025    }
2026    ret
2027}
2028
2029pub fn copy_recursive<'a>(
2030    fs: &'a dyn Fs,
2031    source: &'a Path,
2032    target: &'a Path,
2033    options: CopyOptions,
2034) -> BoxFuture<'a, Result<()>> {
2035    use futures::future::FutureExt;
2036
2037    async move {
2038        let metadata = fs
2039            .metadata(source)
2040            .await?
2041            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2042        if metadata.is_dir {
2043            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
2044                if options.ignore_if_exists {
2045                    return Ok(());
2046                } else {
2047                    return Err(anyhow!("{target:?} already exists"));
2048                }
2049            }
2050
2051            let _ = fs
2052                .remove_dir(
2053                    target,
2054                    RemoveOptions {
2055                        recursive: true,
2056                        ignore_if_not_exists: true,
2057                    },
2058                )
2059                .await;
2060            fs.create_dir(target).await?;
2061            let mut children = fs.read_dir(source).await?;
2062            while let Some(child_path) = children.next().await {
2063                if let Ok(child_path) = child_path {
2064                    if let Some(file_name) = child_path.file_name() {
2065                        let child_target_path = target.join(file_name);
2066                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
2067                    }
2068                }
2069            }
2070
2071            Ok(())
2072        } else {
2073            fs.copy_file(source, target, options).await
2074        }
2075    }
2076    .boxed()
2077}
2078
2079// todo(windows)
2080// can we get file id not open the file twice?
2081// https://github.com/rust-lang/rust/issues/63010
2082#[cfg(target_os = "windows")]
2083async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2084    use std::os::windows::io::AsRawHandle;
2085
2086    use smol::fs::windows::OpenOptionsExt;
2087    use windows::Win32::{
2088        Foundation::HANDLE,
2089        Storage::FileSystem::{
2090            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2091        },
2092    };
2093
2094    let file = smol::fs::OpenOptions::new()
2095        .read(true)
2096        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2097        .open(path)
2098        .await?;
2099
2100    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2101    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2102    // This function supports Windows XP+
2103    smol::unblock(move || {
2104        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2105
2106        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2107    })
2108    .await
2109}
2110
2111#[cfg(test)]
2112mod tests {
2113    use super::*;
2114    use gpui::BackgroundExecutor;
2115    use serde_json::json;
2116
2117    #[gpui::test]
2118    async fn test_fake_fs(executor: BackgroundExecutor) {
2119        let fs = FakeFs::new(executor.clone());
2120        fs.insert_tree(
2121            "/root",
2122            json!({
2123                "dir1": {
2124                    "a": "A",
2125                    "b": "B"
2126                },
2127                "dir2": {
2128                    "c": "C",
2129                    "dir3": {
2130                        "d": "D"
2131                    }
2132                }
2133            }),
2134        )
2135        .await;
2136
2137        assert_eq!(
2138            fs.files(),
2139            vec![
2140                PathBuf::from("/root/dir1/a"),
2141                PathBuf::from("/root/dir1/b"),
2142                PathBuf::from("/root/dir2/c"),
2143                PathBuf::from("/root/dir2/dir3/d"),
2144            ]
2145        );
2146
2147        fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2148            .await
2149            .unwrap();
2150
2151        assert_eq!(
2152            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2153                .await
2154                .unwrap(),
2155            PathBuf::from("/root/dir2/dir3"),
2156        );
2157        assert_eq!(
2158            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2159                .await
2160                .unwrap(),
2161            PathBuf::from("/root/dir2/dir3/d"),
2162        );
2163        assert_eq!(
2164            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2165            "D",
2166        );
2167    }
2168}