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