fs.rs

   1#[cfg(target_os = "macos")]
   2mod mac_watcher;
   3
   4#[cfg(not(target_os = "macos"))]
   5pub mod fs_watcher;
   6
   7use anyhow::{anyhow, Context as _, Result};
   8use git::GitHostingProviderRegistry;
   9#[cfg(any(test, feature = "test-support"))]
  10use git::{repository::RepoPath, status::FileStatus};
  11
  12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  13use ashpd::desktop::trash;
  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::{App, 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;
  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 + Send + Sync>>;
 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: &App) -> 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 App) {
 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        if let Ok(Some(metadata)) = self.metadata(path).await {
 447            if metadata.is_symlink {
 448                // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
 449                return self.remove_file(path, RemoveOptions::default()).await;
 450            }
 451        }
 452        let file = smol::fs::File::open(path).await?;
 453        match trash::trash_file(&file.as_fd()).await {
 454            Ok(_) => Ok(()),
 455            Err(err) => Err(anyhow::Error::new(err)),
 456        }
 457    }
 458
 459    #[cfg(target_os = "windows")]
 460    async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 461        use util::paths::SanitizedPath;
 462        use windows::{
 463            core::HSTRING,
 464            Storage::{StorageDeleteOption, StorageFile},
 465        };
 466        // todo(windows)
 467        // When new version of `windows-rs` release, make this operation `async`
 468        let path = SanitizedPath::from(path.canonicalize()?);
 469        let path_string = path.to_string();
 470        let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
 471        file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 472        Ok(())
 473    }
 474
 475    #[cfg(target_os = "macos")]
 476    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 477        self.trash_file(path, options).await
 478    }
 479
 480    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 481    async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 482        self.trash_file(path, options).await
 483    }
 484
 485    #[cfg(target_os = "windows")]
 486    async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
 487        use util::paths::SanitizedPath;
 488        use windows::{
 489            core::HSTRING,
 490            Storage::{StorageDeleteOption, StorageFolder},
 491        };
 492
 493        // todo(windows)
 494        // When new version of `windows-rs` release, make this operation `async`
 495        let path = SanitizedPath::from(path.canonicalize()?);
 496        let path_string = path.to_string();
 497        let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
 498        folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
 499        Ok(())
 500    }
 501
 502    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
 503        Ok(Box::new(std::fs::File::open(path)?))
 504    }
 505
 506    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
 507        Ok(Arc::new(std::fs::File::open(path)?))
 508    }
 509
 510    async fn load(&self, path: &Path) -> Result<String> {
 511        let path = path.to_path_buf();
 512        let text = smol::unblock(|| std::fs::read_to_string(path)).await?;
 513        Ok(text)
 514    }
 515    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
 516        let path = path.to_path_buf();
 517        let bytes = smol::unblock(|| std::fs::read(path)).await?;
 518        Ok(bytes)
 519    }
 520
 521    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 522        smol::unblock(move || {
 523            let mut tmp_file = if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 524                // Use the directory of the destination as temp dir to avoid
 525                // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
 526                // See https://github.com/zed-industries/zed/pull/8437 for more details.
 527                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 528            } else if cfg!(target_os = "windows") {
 529                // If temp dir is set to a different drive than the destination,
 530                // we receive error:
 531                //
 532                // failed to persist temporary file:
 533                // The system cannot move the file to a different disk drive. (os error 17)
 534                //
 535                // So we use the directory of the destination as a temp dir to avoid it.
 536                // https://github.com/zed-industries/zed/issues/16571
 537                NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))
 538            } else {
 539                NamedTempFile::new()
 540            }?;
 541            tmp_file.write_all(data.as_bytes())?;
 542            tmp_file.persist(path)?;
 543            Ok::<(), anyhow::Error>(())
 544        })
 545        .await?;
 546
 547        Ok(())
 548    }
 549
 550    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 551        let buffer_size = text.summary().len.min(10 * 1024);
 552        if let Some(path) = path.parent() {
 553            self.create_dir(path).await?;
 554        }
 555        let file = smol::fs::File::create(path).await?;
 556        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 557        for chunk in chunks(text, line_ending) {
 558            writer.write_all(chunk.as_bytes()).await?;
 559        }
 560        writer.flush().await?;
 561        Ok(())
 562    }
 563
 564    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 565        Ok(smol::fs::canonicalize(path).await?)
 566    }
 567
 568    async fn is_file(&self, path: &Path) -> bool {
 569        smol::fs::metadata(path)
 570            .await
 571            .map_or(false, |metadata| metadata.is_file())
 572    }
 573
 574    async fn is_dir(&self, path: &Path) -> bool {
 575        smol::fs::metadata(path)
 576            .await
 577            .map_or(false, |metadata| metadata.is_dir())
 578    }
 579
 580    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 581        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 582            Ok(metadata) => metadata,
 583            Err(err) => {
 584                return match (err.kind(), err.raw_os_error()) {
 585                    (io::ErrorKind::NotFound, _) => Ok(None),
 586                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 587                    _ => Err(anyhow::Error::new(err)),
 588                }
 589            }
 590        };
 591
 592        let path_buf = path.to_path_buf();
 593        let path_exists = smol::unblock(move || {
 594            path_buf
 595                .try_exists()
 596                .with_context(|| format!("checking existence for path {path_buf:?}"))
 597        })
 598        .await?;
 599        let is_symlink = symlink_metadata.file_type().is_symlink();
 600        let metadata = match (is_symlink, path_exists) {
 601            (true, true) => smol::fs::metadata(path)
 602                .await
 603                .with_context(|| "accessing symlink for path {path}")?,
 604            _ => symlink_metadata,
 605        };
 606
 607        #[cfg(unix)]
 608        let inode = metadata.ino();
 609
 610        #[cfg(windows)]
 611        let inode = file_id(path).await?;
 612
 613        #[cfg(windows)]
 614        let is_fifo = false;
 615
 616        #[cfg(unix)]
 617        let is_fifo = metadata.file_type().is_fifo();
 618
 619        Ok(Some(Metadata {
 620            inode,
 621            mtime: MTime(metadata.modified().unwrap()),
 622            len: metadata.len(),
 623            is_symlink,
 624            is_dir: metadata.file_type().is_dir(),
 625            is_fifo,
 626        }))
 627    }
 628
 629    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 630        let path = smol::fs::read_link(path).await?;
 631        Ok(path)
 632    }
 633
 634    async fn read_dir(
 635        &self,
 636        path: &Path,
 637    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 638        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 639            Ok(entry) => Ok(entry.path()),
 640            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 641        });
 642        Ok(Box::pin(result))
 643    }
 644
 645    #[cfg(target_os = "macos")]
 646    async fn watch(
 647        &self,
 648        path: &Path,
 649        latency: Duration,
 650    ) -> (
 651        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 652        Arc<dyn Watcher>,
 653    ) {
 654        use fsevent::StreamFlags;
 655
 656        let (events_tx, events_rx) = smol::channel::unbounded();
 657        let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
 658        let watcher = Arc::new(mac_watcher::MacWatcher::new(
 659            events_tx,
 660            Arc::downgrade(&handles),
 661            latency,
 662        ));
 663        watcher.add(path).expect("handles can't be dropped");
 664
 665        (
 666            Box::pin(
 667                events_rx
 668                    .map(|events| {
 669                        events
 670                            .into_iter()
 671                            .map(|event| {
 672                                let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
 673                                    Some(PathEventKind::Removed)
 674                                } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
 675                                    Some(PathEventKind::Created)
 676                                } else if event.flags.contains(StreamFlags::ITEM_MODIFIED) {
 677                                    Some(PathEventKind::Changed)
 678                                } else {
 679                                    None
 680                                };
 681                                PathEvent {
 682                                    path: event.path,
 683                                    kind,
 684                                }
 685                            })
 686                            .collect()
 687                    })
 688                    .chain(futures::stream::once(async move {
 689                        drop(handles);
 690                        vec![]
 691                    })),
 692            ),
 693            watcher,
 694        )
 695    }
 696
 697    #[cfg(not(target_os = "macos"))]
 698    async fn watch(
 699        &self,
 700        path: &Path,
 701        latency: Duration,
 702    ) -> (
 703        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 704        Arc<dyn Watcher>,
 705    ) {
 706        use parking_lot::Mutex;
 707        use util::paths::SanitizedPath;
 708
 709        let (tx, rx) = smol::channel::unbounded();
 710        let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
 711        let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
 712
 713        if watcher.add(path).is_err() {
 714            // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
 715            if let Some(parent) = path.parent() {
 716                if let Err(e) = watcher.add(parent) {
 717                    log::warn!("Failed to watch: {e}");
 718                }
 719            }
 720        }
 721
 722        // Check if path is a symlink and follow the target parent
 723        if let Some(mut target) = self.read_link(&path).await.ok() {
 724            // Check if symlink target is relative path, if so make it absolute
 725            if target.is_relative() {
 726                if let Some(parent) = path.parent() {
 727                    target = parent.join(target);
 728                    if let Ok(canonical) = self.canonicalize(&target).await {
 729                        target = SanitizedPath::from(canonical).as_path().to_path_buf();
 730                    }
 731                }
 732            }
 733            watcher.add(&target).ok();
 734            if let Some(parent) = target.parent() {
 735                watcher.add(parent).log_err();
 736            }
 737        }
 738
 739        (
 740            Box::pin(rx.filter_map({
 741                let watcher = watcher.clone();
 742                move |_| {
 743                    let _ = watcher.clone();
 744                    let pending_paths = pending_paths.clone();
 745                    async move {
 746                        smol::Timer::after(latency).await;
 747                        let paths = std::mem::take(&mut *pending_paths.lock());
 748                        (!paths.is_empty()).then_some(paths)
 749                    }
 750                }
 751            })),
 752            watcher,
 753        )
 754    }
 755
 756    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
 757        // with libgit2, we can open git repo from an existing work dir
 758        // https://libgit2.org/docs/reference/main/repository/git_repository_open.html
 759        let workdir_root = dotgit_path.parent()?;
 760        let repo = git2::Repository::open(workdir_root).log_err()?;
 761        Some(Arc::new(RealGitRepository::new(
 762            repo,
 763            self.git_binary_path.clone(),
 764            self.git_hosting_provider_registry.clone(),
 765        )))
 766    }
 767
 768    fn is_fake(&self) -> bool {
 769        false
 770    }
 771
 772    /// Checks whether the file system is case sensitive by attempting to create two files
 773    /// that have the same name except for the casing.
 774    ///
 775    /// It creates both files in a temporary directory it removes at the end.
 776    async fn is_case_sensitive(&self) -> Result<bool> {
 777        let temp_dir = TempDir::new()?;
 778        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 779        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 780
 781        let create_opts = CreateOptions {
 782            overwrite: false,
 783            ignore_if_exists: false,
 784        };
 785
 786        // Create file1
 787        self.create_file(&test_file_1, create_opts).await?;
 788
 789        // Now check whether it's possible to create file2
 790        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 791            Ok(_) => Ok(true),
 792            Err(e) => {
 793                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 794                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 795                        Ok(false)
 796                    } else {
 797                        Err(e)
 798                    }
 799                } else {
 800                    Err(e)
 801                }
 802            }
 803        };
 804
 805        temp_dir.close()?;
 806        case_sensitive
 807    }
 808}
 809
 810#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
 811impl Watcher for RealWatcher {
 812    fn add(&self, _: &Path) -> Result<()> {
 813        Ok(())
 814    }
 815
 816    fn remove(&self, _: &Path) -> Result<()> {
 817        Ok(())
 818    }
 819}
 820
 821#[cfg(any(test, feature = "test-support"))]
 822pub struct FakeFs {
 823    this: std::sync::Weak<Self>,
 824    // Use an unfair lock to ensure tests are deterministic.
 825    state: Mutex<FakeFsState>,
 826    executor: gpui::BackgroundExecutor,
 827}
 828
 829#[cfg(any(test, feature = "test-support"))]
 830struct FakeFsState {
 831    root: Arc<Mutex<FakeFsEntry>>,
 832    next_inode: u64,
 833    next_mtime: SystemTime,
 834    git_event_tx: smol::channel::Sender<PathBuf>,
 835    event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
 836    events_paused: bool,
 837    buffered_events: Vec<PathEvent>,
 838    metadata_call_count: usize,
 839    read_dir_call_count: usize,
 840    moves: std::collections::HashMap<u64, PathBuf>,
 841}
 842
 843#[cfg(any(test, feature = "test-support"))]
 844#[derive(Debug)]
 845enum FakeFsEntry {
 846    File {
 847        inode: u64,
 848        mtime: MTime,
 849        len: u64,
 850        content: Vec<u8>,
 851    },
 852    Dir {
 853        inode: u64,
 854        mtime: MTime,
 855        len: u64,
 856        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 857        git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
 858    },
 859    Symlink {
 860        target: PathBuf,
 861    },
 862}
 863
 864#[cfg(any(test, feature = "test-support"))]
 865impl FakeFsState {
 866    fn get_and_increment_mtime(&mut self) -> MTime {
 867        let mtime = self.next_mtime;
 868        self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
 869        MTime(mtime)
 870    }
 871
 872    fn get_and_increment_inode(&mut self) -> u64 {
 873        let inode = self.next_inode;
 874        self.next_inode += 1;
 875        inode
 876    }
 877
 878    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 879        Ok(self
 880            .try_read_path(target, true)
 881            .ok_or_else(|| {
 882                anyhow!(io::Error::new(
 883                    io::ErrorKind::NotFound,
 884                    format!("not found: {}", target.display())
 885                ))
 886            })?
 887            .0)
 888    }
 889
 890    fn try_read_path(
 891        &self,
 892        target: &Path,
 893        follow_symlink: bool,
 894    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 895        let mut path = target.to_path_buf();
 896        let mut canonical_path = PathBuf::new();
 897        let mut entry_stack = Vec::new();
 898        'outer: loop {
 899            let mut path_components = path.components().peekable();
 900            let mut prefix = None;
 901            while let Some(component) = path_components.next() {
 902                match component {
 903                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
 904                    Component::RootDir => {
 905                        entry_stack.clear();
 906                        entry_stack.push(self.root.clone());
 907                        canonical_path.clear();
 908                        match prefix {
 909                            Some(prefix_component) => {
 910                                canonical_path = PathBuf::from(prefix_component.as_os_str());
 911                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
 912                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
 913                            }
 914                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
 915                        }
 916                    }
 917                    Component::CurDir => {}
 918                    Component::ParentDir => {
 919                        entry_stack.pop()?;
 920                        canonical_path.pop();
 921                    }
 922                    Component::Normal(name) => {
 923                        let current_entry = entry_stack.last().cloned()?;
 924                        let current_entry = current_entry.lock();
 925                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 926                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 927                            if path_components.peek().is_some() || follow_symlink {
 928                                let entry = entry.lock();
 929                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 930                                    let mut target = target.clone();
 931                                    target.extend(path_components);
 932                                    path = target;
 933                                    continue 'outer;
 934                                }
 935                            }
 936                            entry_stack.push(entry.clone());
 937                            canonical_path = canonical_path.join(name);
 938                        } else {
 939                            return None;
 940                        }
 941                    }
 942                }
 943            }
 944            break;
 945        }
 946        Some((entry_stack.pop()?, canonical_path))
 947    }
 948
 949    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 950    where
 951        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 952    {
 953        let path = normalize_path(path);
 954        let filename = path
 955            .file_name()
 956            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 957        let parent_path = path.parent().unwrap();
 958
 959        let parent = self.read_path(parent_path)?;
 960        let mut parent = parent.lock();
 961        let new_entry = parent
 962            .dir_entries(parent_path)?
 963            .entry(filename.to_str().unwrap().into());
 964        callback(new_entry)
 965    }
 966
 967    fn emit_event<I, T>(&mut self, paths: I)
 968    where
 969        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
 970        T: Into<PathBuf>,
 971    {
 972        self.buffered_events
 973            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
 974                path: path.into(),
 975                kind,
 976            }));
 977
 978        if !self.events_paused {
 979            self.flush_events(self.buffered_events.len());
 980        }
 981    }
 982
 983    fn flush_events(&mut self, mut count: usize) {
 984        count = count.min(self.buffered_events.len());
 985        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 986        self.event_txs.retain(|tx| {
 987            let _ = tx.try_send(events.clone());
 988            !tx.is_closed()
 989        });
 990    }
 991}
 992
 993#[cfg(any(test, feature = "test-support"))]
 994pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
 995    std::sync::LazyLock::new(|| OsStr::new(".git"));
 996
 997#[cfg(any(test, feature = "test-support"))]
 998impl FakeFs {
 999    /// We need to use something large enough for Windows and Unix to consider this a new file.
1000    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1001    const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1002
1003    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1004        let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1005
1006        let this = Arc::new_cyclic(|this| Self {
1007            this: this.clone(),
1008            executor: executor.clone(),
1009            state: Mutex::new(FakeFsState {
1010                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
1011                    inode: 0,
1012                    mtime: MTime(UNIX_EPOCH),
1013                    len: 0,
1014                    entries: Default::default(),
1015                    git_repo_state: None,
1016                })),
1017                git_event_tx: tx,
1018                next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1019                next_inode: 1,
1020                event_txs: Default::default(),
1021                buffered_events: Vec::new(),
1022                events_paused: false,
1023                read_dir_call_count: 0,
1024                metadata_call_count: 0,
1025                moves: Default::default(),
1026            }),
1027        });
1028
1029        executor.spawn({
1030            let this = this.clone();
1031            async move {
1032                while let Ok(git_event) = rx.recv().await {
1033                    if let Some(mut state) = this.state.try_lock() {
1034                        state.emit_event([(git_event, None)]);
1035                    } else {
1036                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1037                    }
1038                }
1039            }
1040        }).detach();
1041
1042        this
1043    }
1044
1045    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1046        let mut state = self.state.lock();
1047        state.next_mtime = next_mtime;
1048    }
1049
1050    pub fn get_and_increment_mtime(&self) -> MTime {
1051        let mut state = self.state.lock();
1052        state.get_and_increment_mtime()
1053    }
1054
1055    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1056        let mut state = self.state.lock();
1057        let path = path.as_ref();
1058        let new_mtime = state.get_and_increment_mtime();
1059        let new_inode = state.get_and_increment_inode();
1060        state
1061            .write_path(path, move |entry| {
1062                match entry {
1063                    btree_map::Entry::Vacant(e) => {
1064                        e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1065                            inode: new_inode,
1066                            mtime: new_mtime,
1067                            content: Vec::new(),
1068                            len: 0,
1069                        })));
1070                    }
1071                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1072                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1073                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1074                        FakeFsEntry::Symlink { .. } => {}
1075                    },
1076                }
1077                Ok(())
1078            })
1079            .unwrap();
1080        state.emit_event([(path.to_path_buf(), None)]);
1081    }
1082
1083    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1084        self.write_file_internal(path, content).unwrap()
1085    }
1086
1087    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1088        let mut state = self.state.lock();
1089        let path = path.as_ref();
1090        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1091        state
1092            .write_path(path.as_ref(), move |e| match e {
1093                btree_map::Entry::Vacant(e) => {
1094                    e.insert(file);
1095                    Ok(())
1096                }
1097                btree_map::Entry::Occupied(mut e) => {
1098                    *e.get_mut() = file;
1099                    Ok(())
1100                }
1101            })
1102            .unwrap();
1103        state.emit_event([(path, None)]);
1104    }
1105
1106    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1107        let mut state = self.state.lock();
1108        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1109            inode: state.get_and_increment_inode(),
1110            mtime: state.get_and_increment_mtime(),
1111            len: content.len() as u64,
1112            content,
1113        }));
1114        let mut kind = None;
1115        state.write_path(path.as_ref(), {
1116            let kind = &mut kind;
1117            move |entry| {
1118                match entry {
1119                    btree_map::Entry::Vacant(e) => {
1120                        *kind = Some(PathEventKind::Created);
1121                        e.insert(file);
1122                    }
1123                    btree_map::Entry::Occupied(mut e) => {
1124                        *kind = Some(PathEventKind::Changed);
1125                        *e.get_mut() = file;
1126                    }
1127                }
1128                Ok(())
1129            }
1130        })?;
1131        state.emit_event([(path.as_ref(), kind)]);
1132        Ok(())
1133    }
1134
1135    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1136        let path = path.as_ref();
1137        let path = normalize_path(path);
1138        let state = self.state.lock();
1139        let entry = state.read_path(&path)?;
1140        let entry = entry.lock();
1141        entry.file_content(&path).cloned()
1142    }
1143
1144    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1145        let path = path.as_ref();
1146        let path = normalize_path(path);
1147        self.simulate_random_delay().await;
1148        let state = self.state.lock();
1149        let entry = state.read_path(&path)?;
1150        let entry = entry.lock();
1151        entry.file_content(&path).cloned()
1152    }
1153
1154    pub fn pause_events(&self) {
1155        self.state.lock().events_paused = true;
1156    }
1157
1158    pub fn buffered_event_count(&self) -> usize {
1159        self.state.lock().buffered_events.len()
1160    }
1161
1162    pub fn flush_events(&self, count: usize) {
1163        self.state.lock().flush_events(count);
1164    }
1165
1166    #[must_use]
1167    pub fn insert_tree<'a>(
1168        &'a self,
1169        path: impl 'a + AsRef<Path> + Send,
1170        tree: serde_json::Value,
1171    ) -> futures::future::BoxFuture<'a, ()> {
1172        use futures::FutureExt as _;
1173        use serde_json::Value::*;
1174
1175        async move {
1176            let path = path.as_ref();
1177
1178            match tree {
1179                Object(map) => {
1180                    self.create_dir(path).await.unwrap();
1181                    for (name, contents) in map {
1182                        let mut path = PathBuf::from(path);
1183                        path.push(name);
1184                        self.insert_tree(&path, contents).await;
1185                    }
1186                }
1187                Null => {
1188                    self.create_dir(path).await.unwrap();
1189                }
1190                String(contents) => {
1191                    self.insert_file(&path, contents.into_bytes()).await;
1192                }
1193                _ => {
1194                    panic!("JSON object must contain only objects, strings, or null");
1195                }
1196            }
1197        }
1198        .boxed()
1199    }
1200
1201    pub fn insert_tree_from_real_fs<'a>(
1202        &'a self,
1203        path: impl 'a + AsRef<Path> + Send,
1204        src_path: impl 'a + AsRef<Path> + Send,
1205    ) -> futures::future::BoxFuture<'a, ()> {
1206        use futures::FutureExt as _;
1207
1208        async move {
1209            let path = path.as_ref();
1210            if std::fs::metadata(&src_path).unwrap().is_file() {
1211                let contents = std::fs::read(src_path).unwrap();
1212                self.insert_file(path, contents).await;
1213            } else {
1214                self.create_dir(path).await.unwrap();
1215                for entry in std::fs::read_dir(&src_path).unwrap() {
1216                    let entry = entry.unwrap();
1217                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1218                        .await;
1219                }
1220            }
1221        }
1222        .boxed()
1223    }
1224
1225    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1226    where
1227        F: FnOnce(&mut FakeGitRepositoryState),
1228    {
1229        let mut state = self.state.lock();
1230        let entry = state.read_path(dot_git).unwrap();
1231        let mut entry = entry.lock();
1232
1233        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1234            let repo_state = git_repo_state.get_or_insert_with(|| {
1235                Arc::new(Mutex::new(FakeGitRepositoryState::new(
1236                    dot_git.to_path_buf(),
1237                    state.git_event_tx.clone(),
1238                )))
1239            });
1240            let mut repo_state = repo_state.lock();
1241
1242            f(&mut repo_state);
1243
1244            if emit_git_event {
1245                state.emit_event([(dot_git, None)]);
1246            }
1247        } else {
1248            panic!("not a directory");
1249        }
1250    }
1251
1252    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1253        self.with_git_state(dot_git, true, |state| {
1254            let branch = branch.map(Into::into);
1255            state.branches.extend(branch.clone());
1256            state.current_branch_name = branch.map(Into::into)
1257        })
1258    }
1259
1260    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1261        self.with_git_state(dot_git, true, |state| {
1262            if let Some(first) = branches.first() {
1263                if state.current_branch_name.is_none() {
1264                    state.current_branch_name = Some(first.to_string())
1265                }
1266            }
1267            state
1268                .branches
1269                .extend(branches.iter().map(ToString::to_string));
1270        })
1271    }
1272
1273    pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(RepoPath, String)]) {
1274        self.with_git_state(dot_git, true, |state| {
1275            state.index_contents.clear();
1276            state.index_contents.extend(
1277                index_state
1278                    .iter()
1279                    .map(|(path, content)| (path.clone(), content.clone())),
1280            );
1281        });
1282    }
1283
1284    pub fn set_head_for_repo(&self, dot_git: &Path, head_state: &[(RepoPath, String)]) {
1285        self.with_git_state(dot_git, true, |state| {
1286            state.head_contents.clear();
1287            state.head_contents.extend(
1288                head_state
1289                    .iter()
1290                    .map(|(path, content)| (path.clone(), content.clone())),
1291            );
1292        });
1293    }
1294
1295    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1296        self.with_git_state(dot_git, true, |state| {
1297            state.blames.clear();
1298            state.blames.extend(blames);
1299        });
1300    }
1301
1302    pub fn set_status_for_repo_via_working_copy_change(
1303        &self,
1304        dot_git: &Path,
1305        statuses: &[(&Path, FileStatus)],
1306    ) {
1307        self.with_git_state(dot_git, false, |state| {
1308            state.statuses.clear();
1309            state.statuses.extend(
1310                statuses
1311                    .iter()
1312                    .map(|(path, content)| ((**path).into(), *content)),
1313            );
1314        });
1315        self.state.lock().emit_event(
1316            statuses
1317                .iter()
1318                .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1319        );
1320    }
1321
1322    pub fn set_status_for_repo_via_git_operation(
1323        &self,
1324        dot_git: &Path,
1325        statuses: &[(&Path, FileStatus)],
1326    ) {
1327        self.with_git_state(dot_git, true, |state| {
1328            state.statuses.clear();
1329            state.statuses.extend(
1330                statuses
1331                    .iter()
1332                    .map(|(path, content)| ((**path).into(), *content)),
1333            );
1334        });
1335    }
1336
1337    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1338        let mut result = Vec::new();
1339        let mut queue = collections::VecDeque::new();
1340        queue.push_back((
1341            PathBuf::from(util::path!("/")),
1342            self.state.lock().root.clone(),
1343        ));
1344        while let Some((path, entry)) = queue.pop_front() {
1345            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1346                for (name, entry) in entries {
1347                    queue.push_back((path.join(name), entry.clone()));
1348                }
1349            }
1350            if include_dot_git
1351                || !path
1352                    .components()
1353                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1354            {
1355                result.push(path);
1356            }
1357        }
1358        result
1359    }
1360
1361    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1362        let mut result = Vec::new();
1363        let mut queue = collections::VecDeque::new();
1364        queue.push_back((
1365            PathBuf::from(util::path!("/")),
1366            self.state.lock().root.clone(),
1367        ));
1368        while let Some((path, entry)) = queue.pop_front() {
1369            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1370                for (name, entry) in entries {
1371                    queue.push_back((path.join(name), entry.clone()));
1372                }
1373                if include_dot_git
1374                    || !path
1375                        .components()
1376                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1377                {
1378                    result.push(path);
1379                }
1380            }
1381        }
1382        result
1383    }
1384
1385    pub fn files(&self) -> Vec<PathBuf> {
1386        let mut result = Vec::new();
1387        let mut queue = collections::VecDeque::new();
1388        queue.push_back((
1389            PathBuf::from(util::path!("/")),
1390            self.state.lock().root.clone(),
1391        ));
1392        while let Some((path, entry)) = queue.pop_front() {
1393            let e = entry.lock();
1394            match &*e {
1395                FakeFsEntry::File { .. } => result.push(path),
1396                FakeFsEntry::Dir { entries, .. } => {
1397                    for (name, entry) in entries {
1398                        queue.push_back((path.join(name), entry.clone()));
1399                    }
1400                }
1401                FakeFsEntry::Symlink { .. } => {}
1402            }
1403        }
1404        result
1405    }
1406
1407    /// How many `read_dir` calls have been issued.
1408    pub fn read_dir_call_count(&self) -> usize {
1409        self.state.lock().read_dir_call_count
1410    }
1411
1412    /// How many `metadata` calls have been issued.
1413    pub fn metadata_call_count(&self) -> usize {
1414        self.state.lock().metadata_call_count
1415    }
1416
1417    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1418        self.executor.simulate_random_delay()
1419    }
1420}
1421
1422#[cfg(any(test, feature = "test-support"))]
1423impl FakeFsEntry {
1424    fn is_file(&self) -> bool {
1425        matches!(self, Self::File { .. })
1426    }
1427
1428    fn is_symlink(&self) -> bool {
1429        matches!(self, Self::Symlink { .. })
1430    }
1431
1432    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1433        if let Self::File { content, .. } = self {
1434            Ok(content)
1435        } else {
1436            Err(anyhow!("not a file: {}", path.display()))
1437        }
1438    }
1439
1440    fn dir_entries(
1441        &mut self,
1442        path: &Path,
1443    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1444        if let Self::Dir { entries, .. } = self {
1445            Ok(entries)
1446        } else {
1447            Err(anyhow!("not a directory: {}", path.display()))
1448        }
1449    }
1450}
1451
1452#[cfg(any(test, feature = "test-support"))]
1453struct FakeWatcher {}
1454
1455#[cfg(any(test, feature = "test-support"))]
1456impl Watcher for FakeWatcher {
1457    fn add(&self, _: &Path) -> Result<()> {
1458        Ok(())
1459    }
1460
1461    fn remove(&self, _: &Path) -> Result<()> {
1462        Ok(())
1463    }
1464}
1465
1466#[cfg(any(test, feature = "test-support"))]
1467#[derive(Debug)]
1468struct FakeHandle {
1469    inode: u64,
1470}
1471
1472#[cfg(any(test, feature = "test-support"))]
1473impl FileHandle for FakeHandle {
1474    fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
1475        let fs = fs.as_fake();
1476        let state = fs.state.lock();
1477        let Some(target) = state.moves.get(&self.inode) else {
1478            anyhow::bail!("fake fd not moved")
1479        };
1480
1481        if state.try_read_path(&target, false).is_some() {
1482            return Ok(target.clone());
1483        }
1484        anyhow::bail!("fake fd target not found")
1485    }
1486}
1487
1488#[cfg(any(test, feature = "test-support"))]
1489#[async_trait::async_trait]
1490impl Fs for FakeFs {
1491    async fn create_dir(&self, path: &Path) -> Result<()> {
1492        self.simulate_random_delay().await;
1493
1494        let mut created_dirs = Vec::new();
1495        let mut cur_path = PathBuf::new();
1496        for component in path.components() {
1497            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1498            cur_path.push(component);
1499            if should_skip {
1500                continue;
1501            }
1502            let mut state = self.state.lock();
1503
1504            let inode = state.get_and_increment_inode();
1505            let mtime = state.get_and_increment_mtime();
1506            state.write_path(&cur_path, |entry| {
1507                entry.or_insert_with(|| {
1508                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1509                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1510                        inode,
1511                        mtime,
1512                        len: 0,
1513                        entries: Default::default(),
1514                        git_repo_state: None,
1515                    }))
1516                });
1517                Ok(())
1518            })?
1519        }
1520
1521        self.state.lock().emit_event(created_dirs);
1522        Ok(())
1523    }
1524
1525    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1526        self.simulate_random_delay().await;
1527        let mut state = self.state.lock();
1528        let inode = state.get_and_increment_inode();
1529        let mtime = state.get_and_increment_mtime();
1530        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1531            inode,
1532            mtime,
1533            len: 0,
1534            content: Vec::new(),
1535        }));
1536        let mut kind = Some(PathEventKind::Created);
1537        state.write_path(path, |entry| {
1538            match entry {
1539                btree_map::Entry::Occupied(mut e) => {
1540                    if options.overwrite {
1541                        kind = Some(PathEventKind::Changed);
1542                        *e.get_mut() = file;
1543                    } else if !options.ignore_if_exists {
1544                        return Err(anyhow!("path already exists: {}", path.display()));
1545                    }
1546                }
1547                btree_map::Entry::Vacant(e) => {
1548                    e.insert(file);
1549                }
1550            }
1551            Ok(())
1552        })?;
1553        state.emit_event([(path, kind)]);
1554        Ok(())
1555    }
1556
1557    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1558        let mut state = self.state.lock();
1559        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1560        state
1561            .write_path(path.as_ref(), move |e| match e {
1562                btree_map::Entry::Vacant(e) => {
1563                    e.insert(file);
1564                    Ok(())
1565                }
1566                btree_map::Entry::Occupied(mut e) => {
1567                    *e.get_mut() = file;
1568                    Ok(())
1569                }
1570            })
1571            .unwrap();
1572        state.emit_event([(path, None)]);
1573
1574        Ok(())
1575    }
1576
1577    async fn create_file_with(
1578        &self,
1579        path: &Path,
1580        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1581    ) -> Result<()> {
1582        let mut bytes = Vec::new();
1583        content.read_to_end(&mut bytes).await?;
1584        self.write_file_internal(path, bytes)?;
1585        Ok(())
1586    }
1587
1588    async fn extract_tar_file(
1589        &self,
1590        path: &Path,
1591        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1592    ) -> Result<()> {
1593        let mut entries = content.entries()?;
1594        while let Some(entry) = entries.next().await {
1595            let mut entry = entry?;
1596            if entry.header().entry_type().is_file() {
1597                let path = path.join(entry.path()?.as_ref());
1598                let mut bytes = Vec::new();
1599                entry.read_to_end(&mut bytes).await?;
1600                self.create_dir(path.parent().unwrap()).await?;
1601                self.write_file_internal(&path, bytes)?;
1602            }
1603        }
1604        Ok(())
1605    }
1606
1607    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1608        self.simulate_random_delay().await;
1609
1610        let old_path = normalize_path(old_path);
1611        let new_path = normalize_path(new_path);
1612
1613        let mut state = self.state.lock();
1614        let moved_entry = state.write_path(&old_path, |e| {
1615            if let btree_map::Entry::Occupied(e) = e {
1616                Ok(e.get().clone())
1617            } else {
1618                Err(anyhow!("path does not exist: {}", &old_path.display()))
1619            }
1620        })?;
1621
1622        let inode = match *moved_entry.lock() {
1623            FakeFsEntry::File { inode, .. } => inode,
1624            FakeFsEntry::Dir { inode, .. } => inode,
1625            _ => 0,
1626        };
1627
1628        state.moves.insert(inode, new_path.clone());
1629
1630        state.write_path(&new_path, |e| {
1631            match e {
1632                btree_map::Entry::Occupied(mut e) => {
1633                    if options.overwrite {
1634                        *e.get_mut() = moved_entry;
1635                    } else if !options.ignore_if_exists {
1636                        return Err(anyhow!("path already exists: {}", new_path.display()));
1637                    }
1638                }
1639                btree_map::Entry::Vacant(e) => {
1640                    e.insert(moved_entry);
1641                }
1642            }
1643            Ok(())
1644        })?;
1645
1646        state
1647            .write_path(&old_path, |e| {
1648                if let btree_map::Entry::Occupied(e) = e {
1649                    Ok(e.remove())
1650                } else {
1651                    unreachable!()
1652                }
1653            })
1654            .unwrap();
1655
1656        state.emit_event([
1657            (old_path, Some(PathEventKind::Removed)),
1658            (new_path, Some(PathEventKind::Created)),
1659        ]);
1660        Ok(())
1661    }
1662
1663    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1664        self.simulate_random_delay().await;
1665
1666        let source = normalize_path(source);
1667        let target = normalize_path(target);
1668        let mut state = self.state.lock();
1669        let mtime = state.get_and_increment_mtime();
1670        let inode = state.get_and_increment_inode();
1671        let source_entry = state.read_path(&source)?;
1672        let content = source_entry.lock().file_content(&source)?.clone();
1673        let mut kind = Some(PathEventKind::Created);
1674        state.write_path(&target, |e| match e {
1675            btree_map::Entry::Occupied(e) => {
1676                if options.overwrite {
1677                    kind = Some(PathEventKind::Changed);
1678                    Ok(Some(e.get().clone()))
1679                } else if !options.ignore_if_exists {
1680                    return Err(anyhow!("{target:?} already exists"));
1681                } else {
1682                    Ok(None)
1683                }
1684            }
1685            btree_map::Entry::Vacant(e) => Ok(Some(
1686                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1687                    inode,
1688                    mtime,
1689                    len: content.len() as u64,
1690                    content,
1691                })))
1692                .clone(),
1693            )),
1694        })?;
1695        state.emit_event([(target, kind)]);
1696        Ok(())
1697    }
1698
1699    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1700        self.simulate_random_delay().await;
1701
1702        let path = normalize_path(path);
1703        let parent_path = path
1704            .parent()
1705            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1706        let base_name = path.file_name().unwrap();
1707
1708        let mut state = self.state.lock();
1709        let parent_entry = state.read_path(parent_path)?;
1710        let mut parent_entry = parent_entry.lock();
1711        let entry = parent_entry
1712            .dir_entries(parent_path)?
1713            .entry(base_name.to_str().unwrap().into());
1714
1715        match entry {
1716            btree_map::Entry::Vacant(_) => {
1717                if !options.ignore_if_not_exists {
1718                    return Err(anyhow!("{path:?} does not exist"));
1719                }
1720            }
1721            btree_map::Entry::Occupied(e) => {
1722                {
1723                    let mut entry = e.get().lock();
1724                    let children = entry.dir_entries(&path)?;
1725                    if !options.recursive && !children.is_empty() {
1726                        return Err(anyhow!("{path:?} is not empty"));
1727                    }
1728                }
1729                e.remove();
1730            }
1731        }
1732        state.emit_event([(path, Some(PathEventKind::Removed))]);
1733        Ok(())
1734    }
1735
1736    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1737        self.simulate_random_delay().await;
1738
1739        let path = normalize_path(path);
1740        let parent_path = path
1741            .parent()
1742            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1743        let base_name = path.file_name().unwrap();
1744        let mut state = self.state.lock();
1745        let parent_entry = state.read_path(parent_path)?;
1746        let mut parent_entry = parent_entry.lock();
1747        let entry = parent_entry
1748            .dir_entries(parent_path)?
1749            .entry(base_name.to_str().unwrap().into());
1750        match entry {
1751            btree_map::Entry::Vacant(_) => {
1752                if !options.ignore_if_not_exists {
1753                    return Err(anyhow!("{path:?} does not exist"));
1754                }
1755            }
1756            btree_map::Entry::Occupied(e) => {
1757                e.get().lock().file_content(&path)?;
1758                e.remove();
1759            }
1760        }
1761        state.emit_event([(path, Some(PathEventKind::Removed))]);
1762        Ok(())
1763    }
1764
1765    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
1766        let bytes = self.load_internal(path).await?;
1767        Ok(Box::new(io::Cursor::new(bytes)))
1768    }
1769
1770    async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
1771        self.simulate_random_delay().await;
1772        let state = self.state.lock();
1773        let entry = state.read_path(&path)?;
1774        let entry = entry.lock();
1775        let inode = match *entry {
1776            FakeFsEntry::File { inode, .. } => inode,
1777            FakeFsEntry::Dir { inode, .. } => inode,
1778            _ => unreachable!(),
1779        };
1780        Ok(Arc::new(FakeHandle { inode }))
1781    }
1782
1783    async fn load(&self, path: &Path) -> Result<String> {
1784        let content = self.load_internal(path).await?;
1785        Ok(String::from_utf8(content.clone())?)
1786    }
1787
1788    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1789        self.load_internal(path).await
1790    }
1791
1792    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1793        self.simulate_random_delay().await;
1794        let path = normalize_path(path.as_path());
1795        self.write_file_internal(path, data.into_bytes())?;
1796        Ok(())
1797    }
1798
1799    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1800        self.simulate_random_delay().await;
1801        let path = normalize_path(path);
1802        let content = chunks(text, line_ending).collect::<String>();
1803        if let Some(path) = path.parent() {
1804            self.create_dir(path).await?;
1805        }
1806        self.write_file_internal(path, content.into_bytes())?;
1807        Ok(())
1808    }
1809
1810    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1811        let path = normalize_path(path);
1812        self.simulate_random_delay().await;
1813        let state = self.state.lock();
1814        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1815            Ok(canonical_path)
1816        } else {
1817            Err(anyhow!("path does not exist: {}", path.display()))
1818        }
1819    }
1820
1821    async fn is_file(&self, path: &Path) -> bool {
1822        let path = normalize_path(path);
1823        self.simulate_random_delay().await;
1824        let state = self.state.lock();
1825        if let Some((entry, _)) = state.try_read_path(&path, true) {
1826            entry.lock().is_file()
1827        } else {
1828            false
1829        }
1830    }
1831
1832    async fn is_dir(&self, path: &Path) -> bool {
1833        self.metadata(path)
1834            .await
1835            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1836    }
1837
1838    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1839        self.simulate_random_delay().await;
1840        let path = normalize_path(path);
1841        let mut state = self.state.lock();
1842        state.metadata_call_count += 1;
1843        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1844            let is_symlink = entry.lock().is_symlink();
1845            if is_symlink {
1846                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1847                    entry = e;
1848                } else {
1849                    return Ok(None);
1850                }
1851            }
1852
1853            let entry = entry.lock();
1854            Ok(Some(match &*entry {
1855                FakeFsEntry::File {
1856                    inode, mtime, len, ..
1857                } => Metadata {
1858                    inode: *inode,
1859                    mtime: *mtime,
1860                    len: *len,
1861                    is_dir: false,
1862                    is_symlink,
1863                    is_fifo: false,
1864                },
1865                FakeFsEntry::Dir {
1866                    inode, mtime, len, ..
1867                } => Metadata {
1868                    inode: *inode,
1869                    mtime: *mtime,
1870                    len: *len,
1871                    is_dir: true,
1872                    is_symlink,
1873                    is_fifo: false,
1874                },
1875                FakeFsEntry::Symlink { .. } => unreachable!(),
1876            }))
1877        } else {
1878            Ok(None)
1879        }
1880    }
1881
1882    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1883        self.simulate_random_delay().await;
1884        let path = normalize_path(path);
1885        let state = self.state.lock();
1886        if let Some((entry, _)) = state.try_read_path(&path, false) {
1887            let entry = entry.lock();
1888            if let FakeFsEntry::Symlink { target } = &*entry {
1889                Ok(target.clone())
1890            } else {
1891                Err(anyhow!("not a symlink: {}", path.display()))
1892            }
1893        } else {
1894            Err(anyhow!("path does not exist: {}", path.display()))
1895        }
1896    }
1897
1898    async fn read_dir(
1899        &self,
1900        path: &Path,
1901    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1902        self.simulate_random_delay().await;
1903        let path = normalize_path(path);
1904        let mut state = self.state.lock();
1905        state.read_dir_call_count += 1;
1906        let entry = state.read_path(&path)?;
1907        let mut entry = entry.lock();
1908        let children = entry.dir_entries(&path)?;
1909        let paths = children
1910            .keys()
1911            .map(|file_name| Ok(path.join(file_name)))
1912            .collect::<Vec<_>>();
1913        Ok(Box::pin(futures::stream::iter(paths)))
1914    }
1915
1916    async fn watch(
1917        &self,
1918        path: &Path,
1919        _: Duration,
1920    ) -> (
1921        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1922        Arc<dyn Watcher>,
1923    ) {
1924        self.simulate_random_delay().await;
1925        let (tx, rx) = smol::channel::unbounded();
1926        self.state.lock().event_txs.push(tx);
1927        let path = path.to_path_buf();
1928        let executor = self.executor.clone();
1929        (
1930            Box::pin(futures::StreamExt::filter(rx, move |events| {
1931                let result = events
1932                    .iter()
1933                    .any(|evt_path| evt_path.path.starts_with(&path));
1934                let executor = executor.clone();
1935                async move {
1936                    executor.simulate_random_delay().await;
1937                    result
1938                }
1939            })),
1940            Arc::new(FakeWatcher {}),
1941        )
1942    }
1943
1944    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1945        let state = self.state.lock();
1946        let entry = state.read_path(abs_dot_git).unwrap();
1947        let mut entry = entry.lock();
1948        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1949            let state = git_repo_state
1950                .get_or_insert_with(|| {
1951                    Arc::new(Mutex::new(FakeGitRepositoryState::new(
1952                        abs_dot_git.to_path_buf(),
1953                        state.git_event_tx.clone(),
1954                    )))
1955                })
1956                .clone();
1957            Some(git::repository::FakeGitRepository::open(state))
1958        } else {
1959            None
1960        }
1961    }
1962
1963    fn is_fake(&self) -> bool {
1964        true
1965    }
1966
1967    async fn is_case_sensitive(&self) -> Result<bool> {
1968        Ok(true)
1969    }
1970
1971    #[cfg(any(test, feature = "test-support"))]
1972    fn as_fake(&self) -> Arc<FakeFs> {
1973        self.this.upgrade().unwrap()
1974    }
1975}
1976
1977fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1978    rope.chunks().flat_map(move |chunk| {
1979        let mut newline = false;
1980        chunk.split('\n').flat_map(move |line| {
1981            let ending = if newline {
1982                Some(line_ending.as_str())
1983            } else {
1984                None
1985            };
1986            newline = true;
1987            ending.into_iter().chain([line])
1988        })
1989    })
1990}
1991
1992pub fn normalize_path(path: &Path) -> PathBuf {
1993    let mut components = path.components().peekable();
1994    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1995        components.next();
1996        PathBuf::from(c.as_os_str())
1997    } else {
1998        PathBuf::new()
1999    };
2000
2001    for component in components {
2002        match component {
2003            Component::Prefix(..) => unreachable!(),
2004            Component::RootDir => {
2005                ret.push(component.as_os_str());
2006            }
2007            Component::CurDir => {}
2008            Component::ParentDir => {
2009                ret.pop();
2010            }
2011            Component::Normal(c) => {
2012                ret.push(c);
2013            }
2014        }
2015    }
2016    ret
2017}
2018
2019pub async fn copy_recursive<'a>(
2020    fs: &'a dyn Fs,
2021    source: &'a Path,
2022    target: &'a Path,
2023    options: CopyOptions,
2024) -> Result<()> {
2025    for (is_dir, item) in read_dir_items(fs, source).await? {
2026        let Ok(item_relative_path) = item.strip_prefix(source) else {
2027            continue;
2028        };
2029        let target_item = if item_relative_path == Path::new("") {
2030            target.to_path_buf()
2031        } else {
2032            target.join(item_relative_path)
2033        };
2034        if is_dir {
2035            if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2036                if options.ignore_if_exists {
2037                    continue;
2038                } else {
2039                    return Err(anyhow!("{target_item:?} already exists"));
2040                }
2041            }
2042            let _ = fs
2043                .remove_dir(
2044                    &target_item,
2045                    RemoveOptions {
2046                        recursive: true,
2047                        ignore_if_not_exists: true,
2048                    },
2049                )
2050                .await;
2051            fs.create_dir(&target_item).await?;
2052        } else {
2053            fs.copy_file(&item, &target_item, options).await?;
2054        }
2055    }
2056    Ok(())
2057}
2058
2059async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(bool, PathBuf)>> {
2060    let mut items = Vec::new();
2061    read_recursive(fs, source, &mut items).await?;
2062    Ok(items)
2063}
2064
2065fn read_recursive<'a>(
2066    fs: &'a dyn Fs,
2067    source: &'a Path,
2068    output: &'a mut Vec<(bool, PathBuf)>,
2069) -> BoxFuture<'a, Result<()>> {
2070    use futures::future::FutureExt;
2071
2072    async move {
2073        let metadata = fs
2074            .metadata(source)
2075            .await?
2076            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
2077
2078        if metadata.is_dir {
2079            output.push((true, source.to_path_buf()));
2080            let mut children = fs.read_dir(source).await?;
2081            while let Some(child_path) = children.next().await {
2082                if let Ok(child_path) = child_path {
2083                    read_recursive(fs, &child_path, output).await?;
2084                }
2085            }
2086        } else {
2087            output.push((false, source.to_path_buf()));
2088        }
2089        Ok(())
2090    }
2091    .boxed()
2092}
2093
2094// todo(windows)
2095// can we get file id not open the file twice?
2096// https://github.com/rust-lang/rust/issues/63010
2097#[cfg(target_os = "windows")]
2098async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2099    use std::os::windows::io::AsRawHandle;
2100
2101    use smol::fs::windows::OpenOptionsExt;
2102    use windows::Win32::{
2103        Foundation::HANDLE,
2104        Storage::FileSystem::{
2105            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2106        },
2107    };
2108
2109    let file = smol::fs::OpenOptions::new()
2110        .read(true)
2111        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2112        .open(path)
2113        .await?;
2114
2115    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2116    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2117    // This function supports Windows XP+
2118    smol::unblock(move || {
2119        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2120
2121        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2122    })
2123    .await
2124}
2125
2126#[cfg(test)]
2127mod tests {
2128    use super::*;
2129    use gpui::BackgroundExecutor;
2130    use serde_json::json;
2131    use util::path;
2132
2133    #[gpui::test]
2134    async fn test_fake_fs(executor: BackgroundExecutor) {
2135        let fs = FakeFs::new(executor.clone());
2136        fs.insert_tree(
2137            path!("/root"),
2138            json!({
2139                "dir1": {
2140                    "a": "A",
2141                    "b": "B"
2142                },
2143                "dir2": {
2144                    "c": "C",
2145                    "dir3": {
2146                        "d": "D"
2147                    }
2148                }
2149            }),
2150        )
2151        .await;
2152
2153        assert_eq!(
2154            fs.files(),
2155            vec![
2156                PathBuf::from(path!("/root/dir1/a")),
2157                PathBuf::from(path!("/root/dir1/b")),
2158                PathBuf::from(path!("/root/dir2/c")),
2159                PathBuf::from(path!("/root/dir2/dir3/d")),
2160            ]
2161        );
2162
2163        fs.create_symlink(path!("/root/dir2/link-to-dir3").as_ref(), "./dir3".into())
2164            .await
2165            .unwrap();
2166
2167        assert_eq!(
2168            fs.canonicalize(path!("/root/dir2/link-to-dir3").as_ref())
2169                .await
2170                .unwrap(),
2171            PathBuf::from(path!("/root/dir2/dir3")),
2172        );
2173        assert_eq!(
2174            fs.canonicalize(path!("/root/dir2/link-to-dir3/d").as_ref())
2175                .await
2176                .unwrap(),
2177            PathBuf::from(path!("/root/dir2/dir3/d")),
2178        );
2179        assert_eq!(
2180            fs.load(path!("/root/dir2/link-to-dir3/d").as_ref())
2181                .await
2182                .unwrap(),
2183            "D",
2184        );
2185    }
2186
2187    #[gpui::test]
2188    async fn test_copy_recursive_with_single_file(executor: BackgroundExecutor) {
2189        let fs = FakeFs::new(executor.clone());
2190        fs.insert_tree(
2191            path!("/outer"),
2192            json!({
2193                "a": "A",
2194                "b": "B",
2195                "inner": {}
2196            }),
2197        )
2198        .await;
2199
2200        assert_eq!(
2201            fs.files(),
2202            vec![
2203                PathBuf::from(path!("/outer/a")),
2204                PathBuf::from(path!("/outer/b")),
2205            ]
2206        );
2207
2208        let source = Path::new(path!("/outer/a"));
2209        let target = Path::new(path!("/outer/a copy"));
2210        copy_recursive(fs.as_ref(), source, target, Default::default())
2211            .await
2212            .unwrap();
2213
2214        assert_eq!(
2215            fs.files(),
2216            vec![
2217                PathBuf::from(path!("/outer/a")),
2218                PathBuf::from(path!("/outer/a copy")),
2219                PathBuf::from(path!("/outer/b")),
2220            ]
2221        );
2222
2223        let source = Path::new(path!("/outer/a"));
2224        let target = Path::new(path!("/outer/inner/a copy"));
2225        copy_recursive(fs.as_ref(), source, target, Default::default())
2226            .await
2227            .unwrap();
2228
2229        assert_eq!(
2230            fs.files(),
2231            vec![
2232                PathBuf::from(path!("/outer/a")),
2233                PathBuf::from(path!("/outer/a copy")),
2234                PathBuf::from(path!("/outer/b")),
2235                PathBuf::from(path!("/outer/inner/a copy")),
2236            ]
2237        );
2238    }
2239
2240    #[gpui::test]
2241    async fn test_copy_recursive_with_single_dir(executor: BackgroundExecutor) {
2242        let fs = FakeFs::new(executor.clone());
2243        fs.insert_tree(
2244            path!("/outer"),
2245            json!({
2246                "a": "A",
2247                "empty": {},
2248                "non-empty": {
2249                    "b": "B",
2250                }
2251            }),
2252        )
2253        .await;
2254
2255        assert_eq!(
2256            fs.files(),
2257            vec![
2258                PathBuf::from(path!("/outer/a")),
2259                PathBuf::from(path!("/outer/non-empty/b")),
2260            ]
2261        );
2262        assert_eq!(
2263            fs.directories(false),
2264            vec![
2265                PathBuf::from(path!("/")),
2266                PathBuf::from(path!("/outer")),
2267                PathBuf::from(path!("/outer/empty")),
2268                PathBuf::from(path!("/outer/non-empty")),
2269            ]
2270        );
2271
2272        let source = Path::new(path!("/outer/empty"));
2273        let target = Path::new(path!("/outer/empty copy"));
2274        copy_recursive(fs.as_ref(), source, target, Default::default())
2275            .await
2276            .unwrap();
2277
2278        assert_eq!(
2279            fs.files(),
2280            vec![
2281                PathBuf::from(path!("/outer/a")),
2282                PathBuf::from(path!("/outer/non-empty/b")),
2283            ]
2284        );
2285        assert_eq!(
2286            fs.directories(false),
2287            vec![
2288                PathBuf::from(path!("/")),
2289                PathBuf::from(path!("/outer")),
2290                PathBuf::from(path!("/outer/empty")),
2291                PathBuf::from(path!("/outer/empty copy")),
2292                PathBuf::from(path!("/outer/non-empty")),
2293            ]
2294        );
2295
2296        let source = Path::new(path!("/outer/non-empty"));
2297        let target = Path::new(path!("/outer/non-empty copy"));
2298        copy_recursive(fs.as_ref(), source, target, Default::default())
2299            .await
2300            .unwrap();
2301
2302        assert_eq!(
2303            fs.files(),
2304            vec![
2305                PathBuf::from(path!("/outer/a")),
2306                PathBuf::from(path!("/outer/non-empty/b")),
2307                PathBuf::from(path!("/outer/non-empty copy/b")),
2308            ]
2309        );
2310        assert_eq!(
2311            fs.directories(false),
2312            vec![
2313                PathBuf::from(path!("/")),
2314                PathBuf::from(path!("/outer")),
2315                PathBuf::from(path!("/outer/empty")),
2316                PathBuf::from(path!("/outer/empty copy")),
2317                PathBuf::from(path!("/outer/non-empty")),
2318                PathBuf::from(path!("/outer/non-empty copy")),
2319            ]
2320        );
2321    }
2322
2323    #[gpui::test]
2324    async fn test_copy_recursive(executor: BackgroundExecutor) {
2325        let fs = FakeFs::new(executor.clone());
2326        fs.insert_tree(
2327            path!("/outer"),
2328            json!({
2329                "inner1": {
2330                    "a": "A",
2331                    "b": "B",
2332                    "inner3": {
2333                        "d": "D",
2334                    },
2335                    "inner4": {}
2336                },
2337                "inner2": {
2338                    "c": "C",
2339                }
2340            }),
2341        )
2342        .await;
2343
2344        assert_eq!(
2345            fs.files(),
2346            vec![
2347                PathBuf::from(path!("/outer/inner1/a")),
2348                PathBuf::from(path!("/outer/inner1/b")),
2349                PathBuf::from(path!("/outer/inner2/c")),
2350                PathBuf::from(path!("/outer/inner1/inner3/d")),
2351            ]
2352        );
2353        assert_eq!(
2354            fs.directories(false),
2355            vec![
2356                PathBuf::from(path!("/")),
2357                PathBuf::from(path!("/outer")),
2358                PathBuf::from(path!("/outer/inner1")),
2359                PathBuf::from(path!("/outer/inner2")),
2360                PathBuf::from(path!("/outer/inner1/inner3")),
2361                PathBuf::from(path!("/outer/inner1/inner4")),
2362            ]
2363        );
2364
2365        let source = Path::new(path!("/outer"));
2366        let target = Path::new(path!("/outer/inner1/outer"));
2367        copy_recursive(fs.as_ref(), source, target, Default::default())
2368            .await
2369            .unwrap();
2370
2371        assert_eq!(
2372            fs.files(),
2373            vec![
2374                PathBuf::from(path!("/outer/inner1/a")),
2375                PathBuf::from(path!("/outer/inner1/b")),
2376                PathBuf::from(path!("/outer/inner2/c")),
2377                PathBuf::from(path!("/outer/inner1/inner3/d")),
2378                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2379                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2380                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2381                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3/d")),
2382            ]
2383        );
2384        assert_eq!(
2385            fs.directories(false),
2386            vec![
2387                PathBuf::from(path!("/")),
2388                PathBuf::from(path!("/outer")),
2389                PathBuf::from(path!("/outer/inner1")),
2390                PathBuf::from(path!("/outer/inner2")),
2391                PathBuf::from(path!("/outer/inner1/inner3")),
2392                PathBuf::from(path!("/outer/inner1/inner4")),
2393                PathBuf::from(path!("/outer/inner1/outer")),
2394                PathBuf::from(path!("/outer/inner1/outer/inner1")),
2395                PathBuf::from(path!("/outer/inner1/outer/inner2")),
2396                PathBuf::from(path!("/outer/inner1/outer/inner1/inner3")),
2397                PathBuf::from(path!("/outer/inner1/outer/inner1/inner4")),
2398            ]
2399        );
2400    }
2401
2402    #[gpui::test]
2403    async fn test_copy_recursive_with_overwriting(executor: BackgroundExecutor) {
2404        let fs = FakeFs::new(executor.clone());
2405        fs.insert_tree(
2406            path!("/outer"),
2407            json!({
2408                "inner1": {
2409                    "a": "A",
2410                    "b": "B",
2411                    "outer": {
2412                        "inner1": {
2413                            "a": "B"
2414                        }
2415                    }
2416                },
2417                "inner2": {
2418                    "c": "C",
2419                }
2420            }),
2421        )
2422        .await;
2423
2424        assert_eq!(
2425            fs.files(),
2426            vec![
2427                PathBuf::from(path!("/outer/inner1/a")),
2428                PathBuf::from(path!("/outer/inner1/b")),
2429                PathBuf::from(path!("/outer/inner2/c")),
2430                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2431            ]
2432        );
2433        assert_eq!(
2434            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2435                .await
2436                .unwrap(),
2437            "B",
2438        );
2439
2440        let source = Path::new(path!("/outer"));
2441        let target = Path::new(path!("/outer/inner1/outer"));
2442        copy_recursive(
2443            fs.as_ref(),
2444            source,
2445            target,
2446            CopyOptions {
2447                overwrite: true,
2448                ..Default::default()
2449            },
2450        )
2451        .await
2452        .unwrap();
2453
2454        assert_eq!(
2455            fs.files(),
2456            vec![
2457                PathBuf::from(path!("/outer/inner1/a")),
2458                PathBuf::from(path!("/outer/inner1/b")),
2459                PathBuf::from(path!("/outer/inner2/c")),
2460                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2461                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2462                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2463                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2464            ]
2465        );
2466        assert_eq!(
2467            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2468                .await
2469                .unwrap(),
2470            "A"
2471        );
2472    }
2473
2474    #[gpui::test]
2475    async fn test_copy_recursive_with_ignoring(executor: BackgroundExecutor) {
2476        let fs = FakeFs::new(executor.clone());
2477        fs.insert_tree(
2478            path!("/outer"),
2479            json!({
2480                "inner1": {
2481                    "a": "A",
2482                    "b": "B",
2483                    "outer": {
2484                        "inner1": {
2485                            "a": "B"
2486                        }
2487                    }
2488                },
2489                "inner2": {
2490                    "c": "C",
2491                }
2492            }),
2493        )
2494        .await;
2495
2496        assert_eq!(
2497            fs.files(),
2498            vec![
2499                PathBuf::from(path!("/outer/inner1/a")),
2500                PathBuf::from(path!("/outer/inner1/b")),
2501                PathBuf::from(path!("/outer/inner2/c")),
2502                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2503            ]
2504        );
2505        assert_eq!(
2506            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2507                .await
2508                .unwrap(),
2509            "B",
2510        );
2511
2512        let source = Path::new(path!("/outer"));
2513        let target = Path::new(path!("/outer/inner1/outer"));
2514        copy_recursive(
2515            fs.as_ref(),
2516            source,
2517            target,
2518            CopyOptions {
2519                ignore_if_exists: true,
2520                ..Default::default()
2521            },
2522        )
2523        .await
2524        .unwrap();
2525
2526        assert_eq!(
2527            fs.files(),
2528            vec![
2529                PathBuf::from(path!("/outer/inner1/a")),
2530                PathBuf::from(path!("/outer/inner1/b")),
2531                PathBuf::from(path!("/outer/inner2/c")),
2532                PathBuf::from(path!("/outer/inner1/outer/inner1/a")),
2533                PathBuf::from(path!("/outer/inner1/outer/inner1/b")),
2534                PathBuf::from(path!("/outer/inner1/outer/inner2/c")),
2535                PathBuf::from(path!("/outer/inner1/outer/inner1/outer/inner1/a")),
2536            ]
2537        );
2538        assert_eq!(
2539            fs.load(path!("/outer/inner1/outer/inner1/a").as_ref())
2540                .await
2541                .unwrap(),
2542            "B"
2543        );
2544    }
2545}