fs.rs

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