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