fs.rs

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