fs.rs

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