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"))]
 797lazy_static::lazy_static! {
 798    pub static ref FS_DOT_GIT: &'static OsStr = OsStr::new(".git");
 799}
 800
 801#[cfg(any(test, feature = "test-support"))]
 802impl FakeFs {
 803    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
 804        Arc::new(Self {
 805            executor,
 806            state: Mutex::new(FakeFsState {
 807                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 808                    inode: 0,
 809                    mtime: SystemTime::UNIX_EPOCH,
 810                    entries: Default::default(),
 811                    git_repo_state: None,
 812                })),
 813                next_mtime: SystemTime::UNIX_EPOCH,
 814                next_inode: 1,
 815                event_txs: Default::default(),
 816                buffered_events: Vec::new(),
 817                events_paused: false,
 818                read_dir_call_count: 0,
 819                metadata_call_count: 0,
 820            }),
 821        })
 822    }
 823
 824    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
 825        let mut state = self.state.lock();
 826        state.next_mtime = next_mtime;
 827    }
 828
 829    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
 830        self.write_file_internal(path, content).unwrap()
 831    }
 832
 833    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 834        let mut state = self.state.lock();
 835        let path = path.as_ref();
 836        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 837        state
 838            .write_path(path.as_ref(), move |e| match e {
 839                btree_map::Entry::Vacant(e) => {
 840                    e.insert(file);
 841                    Ok(())
 842                }
 843                btree_map::Entry::Occupied(mut e) => {
 844                    *e.get_mut() = file;
 845                    Ok(())
 846                }
 847            })
 848            .unwrap();
 849        state.emit_event([path]);
 850    }
 851
 852    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
 853        let mut state = self.state.lock();
 854        let path = path.as_ref();
 855        let inode = state.next_inode;
 856        let mtime = state.next_mtime;
 857        state.next_inode += 1;
 858        state.next_mtime += Duration::from_nanos(1);
 859        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 860            inode,
 861            mtime,
 862            content,
 863        }));
 864        state.write_path(path, move |entry| {
 865            match entry {
 866                btree_map::Entry::Vacant(e) => {
 867                    e.insert(file);
 868                }
 869                btree_map::Entry::Occupied(mut e) => {
 870                    *e.get_mut() = file;
 871                }
 872            }
 873            Ok(())
 874        })?;
 875        state.emit_event([path]);
 876        Ok(())
 877    }
 878
 879    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
 880        let path = path.as_ref();
 881        let path = normalize_path(path);
 882        let state = self.state.lock();
 883        let entry = state.read_path(&path)?;
 884        let entry = entry.lock();
 885        entry.file_content(&path).cloned()
 886    }
 887
 888    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
 889        let path = path.as_ref();
 890        let path = normalize_path(path);
 891        self.simulate_random_delay().await;
 892        let state = self.state.lock();
 893        let entry = state.read_path(&path)?;
 894        let entry = entry.lock();
 895        entry.file_content(&path).cloned()
 896    }
 897
 898    pub fn pause_events(&self) {
 899        self.state.lock().events_paused = true;
 900    }
 901
 902    pub fn buffered_event_count(&self) -> usize {
 903        self.state.lock().buffered_events.len()
 904    }
 905
 906    pub fn flush_events(&self, count: usize) {
 907        self.state.lock().flush_events(count);
 908    }
 909
 910    #[must_use]
 911    pub fn insert_tree<'a>(
 912        &'a self,
 913        path: impl 'a + AsRef<Path> + Send,
 914        tree: serde_json::Value,
 915    ) -> futures::future::BoxFuture<'a, ()> {
 916        use futures::FutureExt as _;
 917        use serde_json::Value::*;
 918
 919        async move {
 920            let path = path.as_ref();
 921
 922            match tree {
 923                Object(map) => {
 924                    self.create_dir(path).await.unwrap();
 925                    for (name, contents) in map {
 926                        let mut path = PathBuf::from(path);
 927                        path.push(name);
 928                        self.insert_tree(&path, contents).await;
 929                    }
 930                }
 931                Null => {
 932                    self.create_dir(path).await.unwrap();
 933                }
 934                String(contents) => {
 935                    self.insert_file(&path, contents.into_bytes()).await;
 936                }
 937                _ => {
 938                    panic!("JSON object must contain only objects, strings, or null");
 939                }
 940            }
 941        }
 942        .boxed()
 943    }
 944
 945    pub fn insert_tree_from_real_fs<'a>(
 946        &'a self,
 947        path: impl 'a + AsRef<Path> + Send,
 948        src_path: impl 'a + AsRef<Path> + Send,
 949    ) -> futures::future::BoxFuture<'a, ()> {
 950        use futures::FutureExt as _;
 951
 952        async move {
 953            let path = path.as_ref();
 954            if std::fs::metadata(&src_path).unwrap().is_file() {
 955                let contents = std::fs::read(src_path).unwrap();
 956                self.insert_file(path, contents).await;
 957            } else {
 958                self.create_dir(path).await.unwrap();
 959                for entry in std::fs::read_dir(&src_path).unwrap() {
 960                    let entry = entry.unwrap();
 961                    self.insert_tree_from_real_fs(&path.join(entry.file_name()), &entry.path())
 962                        .await;
 963                }
 964            }
 965        }
 966        .boxed()
 967    }
 968
 969    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
 970    where
 971        F: FnOnce(&mut FakeGitRepositoryState),
 972    {
 973        let mut state = self.state.lock();
 974        let entry = state.read_path(dot_git).unwrap();
 975        let mut entry = entry.lock();
 976
 977        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
 978            let repo_state = git_repo_state.get_or_insert_with(Default::default);
 979            let mut repo_state = repo_state.lock();
 980
 981            f(&mut repo_state);
 982
 983            if emit_git_event {
 984                state.emit_event([dot_git]);
 985            }
 986        } else {
 987            panic!("not a directory");
 988        }
 989    }
 990
 991    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
 992        self.with_git_state(dot_git, true, |state| {
 993            state.branch_name = branch.map(Into::into)
 994        })
 995    }
 996
 997    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
 998        self.with_git_state(dot_git, true, |state| {
 999            state.index_contents.clear();
1000            state.index_contents.extend(
1001                head_state
1002                    .iter()
1003                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
1004            );
1005        });
1006    }
1007
1008    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1009        self.with_git_state(dot_git, true, |state| {
1010            state.blames.clear();
1011            state.blames.extend(
1012                blames
1013                    .into_iter()
1014                    .map(|(path, blame)| (path.to_path_buf(), blame)),
1015            );
1016        });
1017    }
1018
1019    pub fn set_status_for_repo_via_working_copy_change(
1020        &self,
1021        dot_git: &Path,
1022        statuses: &[(&Path, GitFileStatus)],
1023    ) {
1024        self.with_git_state(dot_git, false, |state| {
1025            state.worktree_statuses.clear();
1026            state.worktree_statuses.extend(
1027                statuses
1028                    .iter()
1029                    .map(|(path, content)| ((**path).into(), *content)),
1030            );
1031        });
1032        self.state.lock().emit_event(
1033            statuses
1034                .iter()
1035                .map(|(path, _)| dot_git.parent().unwrap().join(path)),
1036        );
1037    }
1038
1039    pub fn set_status_for_repo_via_git_operation(
1040        &self,
1041        dot_git: &Path,
1042        statuses: &[(&Path, GitFileStatus)],
1043    ) {
1044        self.with_git_state(dot_git, true, |state| {
1045            state.worktree_statuses.clear();
1046            state.worktree_statuses.extend(
1047                statuses
1048                    .iter()
1049                    .map(|(path, content)| ((**path).into(), *content)),
1050            );
1051        });
1052    }
1053
1054    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1055        let mut result = Vec::new();
1056        let mut queue = collections::VecDeque::new();
1057        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1058        while let Some((path, entry)) = queue.pop_front() {
1059            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1060                for (name, entry) in entries {
1061                    queue.push_back((path.join(name), entry.clone()));
1062                }
1063            }
1064            if include_dot_git
1065                || !path
1066                    .components()
1067                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1068            {
1069                result.push(path);
1070            }
1071        }
1072        result
1073    }
1074
1075    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1076        let mut result = Vec::new();
1077        let mut queue = collections::VecDeque::new();
1078        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1079        while let Some((path, entry)) = queue.pop_front() {
1080            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1081                for (name, entry) in entries {
1082                    queue.push_back((path.join(name), entry.clone()));
1083                }
1084                if include_dot_git
1085                    || !path
1086                        .components()
1087                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1088                {
1089                    result.push(path);
1090                }
1091            }
1092        }
1093        result
1094    }
1095
1096    pub fn files(&self) -> Vec<PathBuf> {
1097        let mut result = Vec::new();
1098        let mut queue = collections::VecDeque::new();
1099        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1100        while let Some((path, entry)) = queue.pop_front() {
1101            let e = entry.lock();
1102            match &*e {
1103                FakeFsEntry::File { .. } => result.push(path),
1104                FakeFsEntry::Dir { entries, .. } => {
1105                    for (name, entry) in entries {
1106                        queue.push_back((path.join(name), entry.clone()));
1107                    }
1108                }
1109                FakeFsEntry::Symlink { .. } => {}
1110            }
1111        }
1112        result
1113    }
1114
1115    /// How many `read_dir` calls have been issued.
1116    pub fn read_dir_call_count(&self) -> usize {
1117        self.state.lock().read_dir_call_count
1118    }
1119
1120    /// How many `metadata` calls have been issued.
1121    pub fn metadata_call_count(&self) -> usize {
1122        self.state.lock().metadata_call_count
1123    }
1124
1125    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1126        self.executor.simulate_random_delay()
1127    }
1128}
1129
1130#[cfg(any(test, feature = "test-support"))]
1131impl FakeFsEntry {
1132    fn is_file(&self) -> bool {
1133        matches!(self, Self::File { .. })
1134    }
1135
1136    fn is_symlink(&self) -> bool {
1137        matches!(self, Self::Symlink { .. })
1138    }
1139
1140    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1141        if let Self::File { content, .. } = self {
1142            Ok(content)
1143        } else {
1144            Err(anyhow!("not a file: {}", path.display()))
1145        }
1146    }
1147
1148    fn set_file_content(&mut self, path: &Path, new_content: Vec<u8>) -> Result<()> {
1149        if let Self::File { content, mtime, .. } = self {
1150            *mtime = SystemTime::now();
1151            *content = new_content;
1152            Ok(())
1153        } else {
1154            Err(anyhow!("not a file: {}", path.display()))
1155        }
1156    }
1157
1158    fn dir_entries(
1159        &mut self,
1160        path: &Path,
1161    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1162        if let Self::Dir { entries, .. } = self {
1163            Ok(entries)
1164        } else {
1165            Err(anyhow!("not a directory: {}", path.display()))
1166        }
1167    }
1168}
1169
1170#[cfg(any(test, feature = "test-support"))]
1171struct FakeWatcher {}
1172
1173#[cfg(any(test, feature = "test-support"))]
1174impl Watcher for FakeWatcher {
1175    fn add(&self, _: &Path) -> Result<()> {
1176        Ok(())
1177    }
1178
1179    fn remove(&self, _: &Path) -> Result<()> {
1180        Ok(())
1181    }
1182}
1183
1184#[cfg(any(test, feature = "test-support"))]
1185#[async_trait::async_trait]
1186impl Fs for FakeFs {
1187    async fn create_dir(&self, path: &Path) -> Result<()> {
1188        self.simulate_random_delay().await;
1189
1190        let mut created_dirs = Vec::new();
1191        let mut cur_path = PathBuf::new();
1192        for component in path.components() {
1193            let mut state = self.state.lock();
1194            cur_path.push(component);
1195            if cur_path == Path::new("/") {
1196                continue;
1197            }
1198
1199            let inode = state.next_inode;
1200            let mtime = state.next_mtime;
1201            state.next_mtime += Duration::from_nanos(1);
1202            state.next_inode += 1;
1203            state.write_path(&cur_path, |entry| {
1204                entry.or_insert_with(|| {
1205                    created_dirs.push(cur_path.clone());
1206                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1207                        inode,
1208                        mtime,
1209                        entries: Default::default(),
1210                        git_repo_state: None,
1211                    }))
1212                });
1213                Ok(())
1214            })?
1215        }
1216
1217        self.state.lock().emit_event(&created_dirs);
1218        Ok(())
1219    }
1220
1221    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1222        self.simulate_random_delay().await;
1223        let mut state = self.state.lock();
1224        let inode = state.next_inode;
1225        let mtime = state.next_mtime;
1226        state.next_mtime += Duration::from_nanos(1);
1227        state.next_inode += 1;
1228        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1229            inode,
1230            mtime,
1231            content: Vec::new(),
1232        }));
1233        state.write_path(path, |entry| {
1234            match entry {
1235                btree_map::Entry::Occupied(mut e) => {
1236                    if options.overwrite {
1237                        *e.get_mut() = file;
1238                    } else if !options.ignore_if_exists {
1239                        return Err(anyhow!("path already exists: {}", path.display()));
1240                    }
1241                }
1242                btree_map::Entry::Vacant(e) => {
1243                    e.insert(file);
1244                }
1245            }
1246            Ok(())
1247        })?;
1248        state.emit_event([path]);
1249        Ok(())
1250    }
1251
1252    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1253        let mut state = self.state.lock();
1254        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1255        state
1256            .write_path(path.as_ref(), move |e| match e {
1257                btree_map::Entry::Vacant(e) => {
1258                    e.insert(file);
1259                    Ok(())
1260                }
1261                btree_map::Entry::Occupied(mut e) => {
1262                    *e.get_mut() = file;
1263                    Ok(())
1264                }
1265            })
1266            .unwrap();
1267        state.emit_event(&[path]);
1268        Ok(())
1269    }
1270
1271    async fn create_file_with(
1272        &self,
1273        path: &Path,
1274        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1275    ) -> Result<()> {
1276        let mut bytes = Vec::new();
1277        content.read_to_end(&mut bytes).await?;
1278        self.write_file_internal(path, bytes)?;
1279        Ok(())
1280    }
1281
1282    async fn extract_tar_file(
1283        &self,
1284        path: &Path,
1285        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1286    ) -> Result<()> {
1287        let mut entries = content.entries()?;
1288        while let Some(entry) = entries.next().await {
1289            let mut entry = entry?;
1290            if entry.header().entry_type().is_file() {
1291                let path = path.join(entry.path()?.as_ref());
1292                let mut bytes = Vec::new();
1293                entry.read_to_end(&mut bytes).await?;
1294                self.create_dir(path.parent().unwrap()).await?;
1295                self.write_file_internal(&path, bytes)?;
1296            }
1297        }
1298        Ok(())
1299    }
1300
1301    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1302        self.simulate_random_delay().await;
1303
1304        let old_path = normalize_path(old_path);
1305        let new_path = normalize_path(new_path);
1306
1307        let mut state = self.state.lock();
1308        let moved_entry = state.write_path(&old_path, |e| {
1309            if let btree_map::Entry::Occupied(e) = e {
1310                Ok(e.get().clone())
1311            } else {
1312                Err(anyhow!("path does not exist: {}", &old_path.display()))
1313            }
1314        })?;
1315
1316        state.write_path(&new_path, |e| {
1317            match e {
1318                btree_map::Entry::Occupied(mut e) => {
1319                    if options.overwrite {
1320                        *e.get_mut() = moved_entry;
1321                    } else if !options.ignore_if_exists {
1322                        return Err(anyhow!("path already exists: {}", new_path.display()));
1323                    }
1324                }
1325                btree_map::Entry::Vacant(e) => {
1326                    e.insert(moved_entry);
1327                }
1328            }
1329            Ok(())
1330        })?;
1331
1332        state
1333            .write_path(&old_path, |e| {
1334                if let btree_map::Entry::Occupied(e) = e {
1335                    Ok(e.remove())
1336                } else {
1337                    unreachable!()
1338                }
1339            })
1340            .unwrap();
1341
1342        state.emit_event(&[old_path, new_path]);
1343        Ok(())
1344    }
1345
1346    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1347        self.simulate_random_delay().await;
1348
1349        let source = normalize_path(source);
1350        let target = normalize_path(target);
1351        let mut state = self.state.lock();
1352        let mtime = state.next_mtime;
1353        let inode = util::post_inc(&mut state.next_inode);
1354        state.next_mtime += Duration::from_nanos(1);
1355        let source_entry = state.read_path(&source)?;
1356        let content = source_entry.lock().file_content(&source)?.clone();
1357        let entry = state.write_path(&target, |e| match e {
1358            btree_map::Entry::Occupied(e) => {
1359                if options.overwrite {
1360                    Ok(Some(e.get().clone()))
1361                } else if !options.ignore_if_exists {
1362                    return Err(anyhow!("{target:?} already exists"));
1363                } else {
1364                    Ok(None)
1365                }
1366            }
1367            btree_map::Entry::Vacant(e) => Ok(Some(
1368                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1369                    inode,
1370                    mtime,
1371                    content: Vec::new(),
1372                })))
1373                .clone(),
1374            )),
1375        })?;
1376        if let Some(entry) = entry {
1377            entry.lock().set_file_content(&target, content)?;
1378        }
1379        state.emit_event(&[target]);
1380        Ok(())
1381    }
1382
1383    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1384        self.simulate_random_delay().await;
1385
1386        let path = normalize_path(path);
1387        let parent_path = path
1388            .parent()
1389            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1390        let base_name = path.file_name().unwrap();
1391
1392        let mut state = self.state.lock();
1393        let parent_entry = state.read_path(parent_path)?;
1394        let mut parent_entry = parent_entry.lock();
1395        let entry = parent_entry
1396            .dir_entries(parent_path)?
1397            .entry(base_name.to_str().unwrap().into());
1398
1399        match entry {
1400            btree_map::Entry::Vacant(_) => {
1401                if !options.ignore_if_not_exists {
1402                    return Err(anyhow!("{path:?} does not exist"));
1403                }
1404            }
1405            btree_map::Entry::Occupied(e) => {
1406                {
1407                    let mut entry = e.get().lock();
1408                    let children = entry.dir_entries(&path)?;
1409                    if !options.recursive && !children.is_empty() {
1410                        return Err(anyhow!("{path:?} is not empty"));
1411                    }
1412                }
1413                e.remove();
1414            }
1415        }
1416        state.emit_event(&[path]);
1417        Ok(())
1418    }
1419
1420    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1421        self.simulate_random_delay().await;
1422
1423        let path = normalize_path(path);
1424        let parent_path = path
1425            .parent()
1426            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1427        let base_name = path.file_name().unwrap();
1428        let mut state = self.state.lock();
1429        let parent_entry = state.read_path(parent_path)?;
1430        let mut parent_entry = parent_entry.lock();
1431        let entry = parent_entry
1432            .dir_entries(parent_path)?
1433            .entry(base_name.to_str().unwrap().into());
1434        match entry {
1435            btree_map::Entry::Vacant(_) => {
1436                if !options.ignore_if_not_exists {
1437                    return Err(anyhow!("{path:?} does not exist"));
1438                }
1439            }
1440            btree_map::Entry::Occupied(e) => {
1441                e.get().lock().file_content(&path)?;
1442                e.remove();
1443            }
1444        }
1445        state.emit_event(&[path]);
1446        Ok(())
1447    }
1448
1449    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1450        let bytes = self.load_internal(path).await?;
1451        Ok(Box::new(io::Cursor::new(bytes)))
1452    }
1453
1454    async fn load(&self, path: &Path) -> Result<String> {
1455        let content = self.load_internal(path).await?;
1456        Ok(String::from_utf8(content.clone())?)
1457    }
1458
1459    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1460        self.load_internal(path).await
1461    }
1462
1463    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1464        self.simulate_random_delay().await;
1465        let path = normalize_path(path.as_path());
1466        self.write_file_internal(path, data.into_bytes())?;
1467        Ok(())
1468    }
1469
1470    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1471        self.simulate_random_delay().await;
1472        let path = normalize_path(path);
1473        let content = chunks(text, line_ending).collect::<String>();
1474        if let Some(path) = path.parent() {
1475            self.create_dir(path).await?;
1476        }
1477        self.write_file_internal(path, content.into_bytes())?;
1478        Ok(())
1479    }
1480
1481    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1482        let path = normalize_path(path);
1483        self.simulate_random_delay().await;
1484        let state = self.state.lock();
1485        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1486            Ok(canonical_path)
1487        } else {
1488            Err(anyhow!("path does not exist: {}", path.display()))
1489        }
1490    }
1491
1492    async fn is_file(&self, path: &Path) -> bool {
1493        let path = normalize_path(path);
1494        self.simulate_random_delay().await;
1495        let state = self.state.lock();
1496        if let Some((entry, _)) = state.try_read_path(&path, true) {
1497            entry.lock().is_file()
1498        } else {
1499            false
1500        }
1501    }
1502
1503    async fn is_dir(&self, path: &Path) -> bool {
1504        self.metadata(path)
1505            .await
1506            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1507    }
1508
1509    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1510        self.simulate_random_delay().await;
1511        let path = normalize_path(path);
1512        let mut state = self.state.lock();
1513        state.metadata_call_count += 1;
1514        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1515            let is_symlink = entry.lock().is_symlink();
1516            if is_symlink {
1517                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1518                    entry = e;
1519                } else {
1520                    return Ok(None);
1521                }
1522            }
1523
1524            let entry = entry.lock();
1525            Ok(Some(match &*entry {
1526                FakeFsEntry::File { inode, mtime, .. } => Metadata {
1527                    inode: *inode,
1528                    mtime: *mtime,
1529                    is_dir: false,
1530                    is_symlink,
1531                },
1532                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1533                    inode: *inode,
1534                    mtime: *mtime,
1535                    is_dir: true,
1536                    is_symlink,
1537                },
1538                FakeFsEntry::Symlink { .. } => unreachable!(),
1539            }))
1540        } else {
1541            Ok(None)
1542        }
1543    }
1544
1545    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1546        self.simulate_random_delay().await;
1547        let path = normalize_path(path);
1548        let state = self.state.lock();
1549        if let Some((entry, _)) = state.try_read_path(&path, false) {
1550            let entry = entry.lock();
1551            if let FakeFsEntry::Symlink { target } = &*entry {
1552                Ok(target.clone())
1553            } else {
1554                Err(anyhow!("not a symlink: {}", path.display()))
1555            }
1556        } else {
1557            Err(anyhow!("path does not exist: {}", path.display()))
1558        }
1559    }
1560
1561    async fn read_dir(
1562        &self,
1563        path: &Path,
1564    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1565        self.simulate_random_delay().await;
1566        let path = normalize_path(path);
1567        let mut state = self.state.lock();
1568        state.read_dir_call_count += 1;
1569        let entry = state.read_path(&path)?;
1570        let mut entry = entry.lock();
1571        let children = entry.dir_entries(&path)?;
1572        let paths = children
1573            .keys()
1574            .map(|file_name| Ok(path.join(file_name)))
1575            .collect::<Vec<_>>();
1576        Ok(Box::pin(futures::stream::iter(paths)))
1577    }
1578
1579    async fn watch(
1580        &self,
1581        path: &Path,
1582        _: Duration,
1583    ) -> (
1584        Pin<Box<dyn Send + Stream<Item = Vec<PathBuf>>>>,
1585        Arc<dyn Watcher>,
1586    ) {
1587        self.simulate_random_delay().await;
1588        let (tx, rx) = smol::channel::unbounded();
1589        self.state.lock().event_txs.push(tx);
1590        let path = path.to_path_buf();
1591        let executor = self.executor.clone();
1592        (
1593            Box::pin(futures::StreamExt::filter(rx, move |events| {
1594                let result = events.iter().any(|evt_path| evt_path.starts_with(&path));
1595                let executor = executor.clone();
1596                async move {
1597                    executor.simulate_random_delay().await;
1598                    result
1599                }
1600            })),
1601            Arc::new(FakeWatcher {}),
1602        )
1603    }
1604
1605    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1606        let state = self.state.lock();
1607        let entry = state.read_path(abs_dot_git).unwrap();
1608        let mut entry = entry.lock();
1609        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1610            let state = git_repo_state
1611                .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
1612                .clone();
1613            Some(git::repository::FakeGitRepository::open(state))
1614        } else {
1615            None
1616        }
1617    }
1618
1619    fn is_fake(&self) -> bool {
1620        true
1621    }
1622
1623    async fn is_case_sensitive(&self) -> Result<bool> {
1624        Ok(true)
1625    }
1626
1627    #[cfg(any(test, feature = "test-support"))]
1628    fn as_fake(&self) -> &FakeFs {
1629        self
1630    }
1631}
1632
1633fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1634    rope.chunks().flat_map(move |chunk| {
1635        let mut newline = false;
1636        chunk.split('\n').flat_map(move |line| {
1637            let ending = if newline {
1638                Some(line_ending.as_str())
1639            } else {
1640                None
1641            };
1642            newline = true;
1643            ending.into_iter().chain([line])
1644        })
1645    })
1646}
1647
1648pub fn normalize_path(path: &Path) -> PathBuf {
1649    let mut components = path.components().peekable();
1650    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1651        components.next();
1652        PathBuf::from(c.as_os_str())
1653    } else {
1654        PathBuf::new()
1655    };
1656
1657    for component in components {
1658        match component {
1659            Component::Prefix(..) => unreachable!(),
1660            Component::RootDir => {
1661                ret.push(component.as_os_str());
1662            }
1663            Component::CurDir => {}
1664            Component::ParentDir => {
1665                ret.pop();
1666            }
1667            Component::Normal(c) => {
1668                ret.push(c);
1669            }
1670        }
1671    }
1672    ret
1673}
1674
1675pub fn copy_recursive<'a>(
1676    fs: &'a dyn Fs,
1677    source: &'a Path,
1678    target: &'a Path,
1679    options: CopyOptions,
1680) -> BoxFuture<'a, Result<()>> {
1681    use futures::future::FutureExt;
1682
1683    async move {
1684        let metadata = fs
1685            .metadata(source)
1686            .await?
1687            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1688        if metadata.is_dir {
1689            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1690                if options.ignore_if_exists {
1691                    return Ok(());
1692                } else {
1693                    return Err(anyhow!("{target:?} already exists"));
1694                }
1695            }
1696
1697            let _ = fs
1698                .remove_dir(
1699                    target,
1700                    RemoveOptions {
1701                        recursive: true,
1702                        ignore_if_not_exists: true,
1703                    },
1704                )
1705                .await;
1706            fs.create_dir(target).await?;
1707            let mut children = fs.read_dir(source).await?;
1708            while let Some(child_path) = children.next().await {
1709                if let Ok(child_path) = child_path {
1710                    if let Some(file_name) = child_path.file_name() {
1711                        let child_target_path = target.join(file_name);
1712                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1713                    }
1714                }
1715            }
1716
1717            Ok(())
1718        } else {
1719            fs.copy_file(source, target, options).await
1720        }
1721    }
1722    .boxed()
1723}
1724
1725// todo(windows)
1726// can we get file id not open the file twice?
1727// https://github.com/rust-lang/rust/issues/63010
1728#[cfg(target_os = "windows")]
1729async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
1730    use std::os::windows::io::AsRawHandle;
1731
1732    use smol::fs::windows::OpenOptionsExt;
1733    use windows::Win32::{
1734        Foundation::HANDLE,
1735        Storage::FileSystem::{
1736            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
1737        },
1738    };
1739
1740    let file = smol::fs::OpenOptions::new()
1741        .read(true)
1742        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
1743        .open(path)
1744        .await?;
1745
1746    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
1747    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
1748    // This function supports Windows XP+
1749    smol::unblock(move || {
1750        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
1751
1752        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
1753    })
1754    .await
1755}
1756
1757#[cfg(test)]
1758mod tests {
1759    use super::*;
1760    use gpui::BackgroundExecutor;
1761    use serde_json::json;
1762
1763    #[gpui::test]
1764    async fn test_fake_fs(executor: BackgroundExecutor) {
1765        let fs = FakeFs::new(executor.clone());
1766        fs.insert_tree(
1767            "/root",
1768            json!({
1769                "dir1": {
1770                    "a": "A",
1771                    "b": "B"
1772                },
1773                "dir2": {
1774                    "c": "C",
1775                    "dir3": {
1776                        "d": "D"
1777                    }
1778                }
1779            }),
1780        )
1781        .await;
1782
1783        assert_eq!(
1784            fs.files(),
1785            vec![
1786                PathBuf::from("/root/dir1/a"),
1787                PathBuf::from("/root/dir1/b"),
1788                PathBuf::from("/root/dir2/c"),
1789                PathBuf::from("/root/dir2/dir3/d"),
1790            ]
1791        );
1792
1793        fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
1794            .await
1795            .unwrap();
1796
1797        assert_eq!(
1798            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1799                .await
1800                .unwrap(),
1801            PathBuf::from("/root/dir2/dir3"),
1802        );
1803        assert_eq!(
1804            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1805                .await
1806                .unwrap(),
1807            PathBuf::from("/root/dir2/dir3/d"),
1808        );
1809        assert_eq!(
1810            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1811            "D",
1812        );
1813    }
1814}
1815
1816#[cfg(target_os = "linux")]
1817pub mod watcher {
1818    use std::sync::OnceLock;
1819
1820    use parking_lot::Mutex;
1821    use util::ResultExt;
1822
1823    pub struct GlobalWatcher {
1824        // two mutexes because calling inotify.add triggers an inotify.event, which needs watchers.
1825        pub(super) inotify: Mutex<notify::INotifyWatcher>,
1826        pub(super) watchers: Mutex<Vec<Box<dyn Fn(&notify::Event) + Send + Sync>>>,
1827    }
1828
1829    impl GlobalWatcher {
1830        pub(super) fn add(&self, cb: impl Fn(&notify::Event) + Send + Sync + 'static) {
1831            self.watchers.lock().push(Box::new(cb))
1832        }
1833    }
1834
1835    static INOTIFY_INSTANCE: OnceLock<anyhow::Result<GlobalWatcher, notify::Error>> =
1836        OnceLock::new();
1837
1838    fn handle_event(event: Result<notify::Event, notify::Error>) {
1839        let Some(event) = event.log_err() else { return };
1840        global::<()>(move |watcher| {
1841            for f in watcher.watchers.lock().iter() {
1842                f(&event)
1843            }
1844        })
1845        .log_err();
1846    }
1847
1848    pub fn global<T>(f: impl FnOnce(&GlobalWatcher) -> T) -> anyhow::Result<T> {
1849        let result = INOTIFY_INSTANCE.get_or_init(|| {
1850            notify::recommended_watcher(handle_event).map(|file_watcher| GlobalWatcher {
1851                inotify: Mutex::new(file_watcher),
1852                watchers: Default::default(),
1853            })
1854        });
1855        match result {
1856            Ok(g) => Ok(f(g)),
1857            Err(e) => Err(anyhow::anyhow!("{}", e)),
1858        }
1859    }
1860}