fs.rs

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