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        // Check if root path is a symlink
 591        let target_path = self.read_link(&path).await.ok();
 592
 593        watcher::global({
 594            let target_path = target_path.clone();
 595            |g| {
 596                let tx = tx.clone();
 597                let pending_paths = pending_paths.clone();
 598                g.add(move |event: &notify::Event| {
 599                    let kind = match event.kind {
 600                        EventKind::Create(_) => Some(PathEventKind::Created),
 601                        EventKind::Modify(_) => Some(PathEventKind::Changed),
 602                        EventKind::Remove(_) => Some(PathEventKind::Removed),
 603                        _ => None,
 604                    };
 605                    let mut paths = event
 606                        .paths
 607                        .iter()
 608                        .filter_map(|path| {
 609                            if let Some(target) = target_path.clone() {
 610                                if path.starts_with(target) {
 611                                    return Some(PathEvent {
 612                                        path: path.clone(),
 613                                        kind,
 614                                    });
 615                                }
 616                            } else if path.starts_with(&root_path) {
 617                                return Some(PathEvent {
 618                                    path: path.clone(),
 619                                    kind,
 620                                });
 621                            }
 622                            None
 623                        })
 624                        .collect::<Vec<_>>();
 625
 626                    if !paths.is_empty() {
 627                        paths.sort();
 628                        let mut pending_paths = pending_paths.lock();
 629                        if pending_paths.is_empty() {
 630                            tx.try_send(()).ok();
 631                        }
 632                        util::extend_sorted(&mut *pending_paths, paths, usize::MAX, |a, b| {
 633                            a.path.cmp(&b.path)
 634                        });
 635                    }
 636                })
 637            }
 638        })
 639        .log_err();
 640
 641        let watcher = Arc::new(RealWatcher {});
 642
 643        watcher.add(path).ok(); // Ignore "file doesn't exist error" and rely on parent watcher.
 644
 645        // Check if path is a symlink and follow the target parent
 646        if let Some(target) = target_path {
 647            watcher.add(&target).ok();
 648            if let Some(parent) = target.parent() {
 649                watcher.add(parent).log_err();
 650            }
 651        }
 652
 653        // watch the parent dir so we can tell when settings.json is created
 654        if let Some(parent) = path.parent() {
 655            watcher.add(parent).log_err();
 656        }
 657
 658        (
 659            Box::pin(rx.filter_map({
 660                let watcher = watcher.clone();
 661                move |_| {
 662                    let _ = watcher.clone();
 663                    let pending_paths = pending_paths.clone();
 664                    async move {
 665                        smol::Timer::after(latency).await;
 666                        let paths = std::mem::take(&mut *pending_paths.lock());
 667                        (!paths.is_empty()).then_some(paths)
 668                    }
 669                }
 670            })),
 671            watcher,
 672        )
 673    }
 674
 675    #[cfg(target_os = "windows")]
 676    async fn watch(
 677        &self,
 678        path: &Path,
 679        _latency: Duration,
 680    ) -> (
 681        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
 682        Arc<dyn Watcher>,
 683    ) {
 684        use notify::{EventKind, Watcher};
 685
 686        let (tx, rx) = smol::channel::unbounded();
 687
 688        let mut file_watcher = notify::recommended_watcher({
 689            let tx = tx.clone();
 690            move |event: Result<notify::Event, _>| {
 691                if let Some(event) = event.log_err() {
 692                    let kind = match event.kind {
 693                        EventKind::Create(_) => Some(PathEventKind::Created),
 694                        EventKind::Modify(_) => Some(PathEventKind::Changed),
 695                        EventKind::Remove(_) => Some(PathEventKind::Removed),
 696                        _ => None,
 697                    };
 698
 699                    tx.try_send(
 700                        event
 701                            .paths
 702                            .into_iter()
 703                            .map(|path| PathEvent { path, kind })
 704                            .collect::<Vec<_>>(),
 705                    )
 706                    .ok();
 707                }
 708            }
 709        })
 710        .expect("Could not start file watcher");
 711
 712        file_watcher
 713            .watch(path, notify::RecursiveMode::Recursive)
 714            .log_err();
 715
 716        (
 717            Box::pin(rx.chain(futures::stream::once(async move {
 718                drop(file_watcher);
 719                vec![]
 720            }))),
 721            Arc::new(RealWatcher {}),
 722        )
 723    }
 724
 725    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<dyn GitRepository>> {
 726        let repo = git2::Repository::open(dotgit_path).log_err()?;
 727        Some(Arc::new(RealGitRepository::new(
 728            repo,
 729            self.git_binary_path.clone(),
 730            self.git_hosting_provider_registry.clone(),
 731        )))
 732    }
 733
 734    fn is_fake(&self) -> bool {
 735        false
 736    }
 737
 738    /// Checks whether the file system is case sensitive by attempting to create two files
 739    /// that have the same name except for the casing.
 740    ///
 741    /// It creates both files in a temporary directory it removes at the end.
 742    async fn is_case_sensitive(&self) -> Result<bool> {
 743        let temp_dir = TempDir::new()?;
 744        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 745        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 746
 747        let create_opts = CreateOptions {
 748            overwrite: false,
 749            ignore_if_exists: false,
 750        };
 751
 752        // Create file1
 753        self.create_file(&test_file_1, create_opts).await?;
 754
 755        // Now check whether it's possible to create file2
 756        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 757            Ok(_) => Ok(true),
 758            Err(e) => {
 759                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 760                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 761                        Ok(false)
 762                    } else {
 763                        Err(e)
 764                    }
 765                } else {
 766                    Err(e)
 767                }
 768            }
 769        };
 770
 771        temp_dir.close()?;
 772        case_sensitive
 773    }
 774}
 775
 776#[cfg(not(target_os = "linux"))]
 777impl Watcher for RealWatcher {
 778    fn add(&self, _: &Path) -> Result<()> {
 779        Ok(())
 780    }
 781
 782    fn remove(&self, _: &Path) -> Result<()> {
 783        Ok(())
 784    }
 785}
 786
 787#[cfg(target_os = "linux")]
 788impl Watcher for RealWatcher {
 789    fn add(&self, path: &Path) -> Result<()> {
 790        use notify::Watcher;
 791        Ok(watcher::global(|w| {
 792            w.inotify
 793                .lock()
 794                .watch(path, notify::RecursiveMode::NonRecursive)
 795        })??)
 796    }
 797
 798    fn remove(&self, path: &Path) -> Result<()> {
 799        use notify::Watcher;
 800        Ok(watcher::global(|w| w.inotify.lock().unwatch(path))??)
 801    }
 802}
 803
 804#[cfg(any(test, feature = "test-support"))]
 805pub struct FakeFs {
 806    // Use an unfair lock to ensure tests are deterministic.
 807    state: Mutex<FakeFsState>,
 808    executor: gpui::BackgroundExecutor,
 809}
 810
 811#[cfg(any(test, feature = "test-support"))]
 812struct FakeFsState {
 813    root: Arc<Mutex<FakeFsEntry>>,
 814    next_inode: u64,
 815    next_mtime: SystemTime,
 816    git_event_tx: smol::channel::Sender<PathBuf>,
 817    event_txs: Vec<smol::channel::Sender<Vec<PathEvent>>>,
 818    events_paused: bool,
 819    buffered_events: Vec<PathEvent>,
 820    metadata_call_count: usize,
 821    read_dir_call_count: usize,
 822}
 823
 824#[cfg(any(test, feature = "test-support"))]
 825#[derive(Debug)]
 826enum FakeFsEntry {
 827    File {
 828        inode: u64,
 829        mtime: SystemTime,
 830        len: u64,
 831        content: Vec<u8>,
 832    },
 833    Dir {
 834        inode: u64,
 835        mtime: SystemTime,
 836        len: u64,
 837        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 838        git_repo_state: Option<Arc<Mutex<git::repository::FakeGitRepositoryState>>>,
 839    },
 840    Symlink {
 841        target: PathBuf,
 842    },
 843}
 844
 845#[cfg(any(test, feature = "test-support"))]
 846impl FakeFsState {
 847    fn read_path(&self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 848        Ok(self
 849            .try_read_path(target, true)
 850            .ok_or_else(|| {
 851                anyhow!(io::Error::new(
 852                    io::ErrorKind::NotFound,
 853                    format!("not found: {}", target.display())
 854                ))
 855            })?
 856            .0)
 857    }
 858
 859    fn try_read_path(
 860        &self,
 861        target: &Path,
 862        follow_symlink: bool,
 863    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 864        let mut path = target.to_path_buf();
 865        let mut canonical_path = PathBuf::new();
 866        let mut entry_stack = Vec::new();
 867        'outer: loop {
 868            let mut path_components = path.components().peekable();
 869            let mut prefix = None;
 870            while let Some(component) = path_components.next() {
 871                match component {
 872                    Component::Prefix(prefix_component) => prefix = Some(prefix_component),
 873                    Component::RootDir => {
 874                        entry_stack.clear();
 875                        entry_stack.push(self.root.clone());
 876                        canonical_path.clear();
 877                        match prefix {
 878                            Some(prefix_component) => {
 879                                canonical_path = PathBuf::from(prefix_component.as_os_str());
 880                                // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
 881                                canonical_path.push(std::path::MAIN_SEPARATOR_STR);
 882                            }
 883                            None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
 884                        }
 885                    }
 886                    Component::CurDir => {}
 887                    Component::ParentDir => {
 888                        entry_stack.pop()?;
 889                        canonical_path.pop();
 890                    }
 891                    Component::Normal(name) => {
 892                        let current_entry = entry_stack.last().cloned()?;
 893                        let current_entry = current_entry.lock();
 894                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 895                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 896                            if path_components.peek().is_some() || follow_symlink {
 897                                let entry = entry.lock();
 898                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 899                                    let mut target = target.clone();
 900                                    target.extend(path_components);
 901                                    path = target;
 902                                    continue 'outer;
 903                                }
 904                            }
 905                            entry_stack.push(entry.clone());
 906                            canonical_path = canonical_path.join(name);
 907                        } else {
 908                            return None;
 909                        }
 910                    }
 911                }
 912            }
 913            break;
 914        }
 915        Some((entry_stack.pop()?, canonical_path))
 916    }
 917
 918    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 919    where
 920        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 921    {
 922        let path = normalize_path(path);
 923        let filename = path
 924            .file_name()
 925            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 926        let parent_path = path.parent().unwrap();
 927
 928        let parent = self.read_path(parent_path)?;
 929        let mut parent = parent.lock();
 930        let new_entry = parent
 931            .dir_entries(parent_path)?
 932            .entry(filename.to_str().unwrap().into());
 933        callback(new_entry)
 934    }
 935
 936    fn emit_event<I, T>(&mut self, paths: I)
 937    where
 938        I: IntoIterator<Item = (T, Option<PathEventKind>)>,
 939        T: Into<PathBuf>,
 940    {
 941        self.buffered_events
 942            .extend(paths.into_iter().map(|(path, kind)| PathEvent {
 943                path: path.into(),
 944                kind,
 945            }));
 946
 947        if !self.events_paused {
 948            self.flush_events(self.buffered_events.len());
 949        }
 950    }
 951
 952    fn flush_events(&mut self, mut count: usize) {
 953        count = count.min(self.buffered_events.len());
 954        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 955        self.event_txs.retain(|tx| {
 956            let _ = tx.try_send(events.clone());
 957            !tx.is_closed()
 958        });
 959    }
 960}
 961
 962#[cfg(any(test, feature = "test-support"))]
 963pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
 964    std::sync::LazyLock::new(|| OsStr::new(".git"));
 965
 966#[cfg(any(test, feature = "test-support"))]
 967impl FakeFs {
 968    /// We need to use something large enough for Windows and Unix to consider this a new file.
 969    /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
 970    const SYSTEMTIME_INTERVAL: u64 = 100;
 971
 972    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
 973        let (tx, mut rx) = smol::channel::bounded::<PathBuf>(10);
 974
 975        let this = Arc::new(Self {
 976            executor: executor.clone(),
 977            state: Mutex::new(FakeFsState {
 978                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 979                    inode: 0,
 980                    mtime: SystemTime::UNIX_EPOCH,
 981                    len: 0,
 982                    entries: Default::default(),
 983                    git_repo_state: None,
 984                })),
 985                git_event_tx: tx,
 986                next_mtime: SystemTime::UNIX_EPOCH,
 987                next_inode: 1,
 988                event_txs: Default::default(),
 989                buffered_events: Vec::new(),
 990                events_paused: false,
 991                read_dir_call_count: 0,
 992                metadata_call_count: 0,
 993            }),
 994        });
 995
 996        executor.spawn({
 997            let this = this.clone();
 998            async move {
 999                while let Some(git_event) = rx.next().await {
1000                    if let Some(mut state) = this.state.try_lock() {
1001                        state.emit_event([(git_event, None)]);
1002                    } else {
1003                        panic!("Failed to lock file system state, this execution would have caused a test hang");
1004                    }
1005                }
1006            }
1007        }).detach();
1008
1009        this
1010    }
1011
1012    pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1013        let mut state = self.state.lock();
1014        state.next_mtime = next_mtime;
1015    }
1016
1017    pub async fn touch_path(&self, path: impl AsRef<Path>) {
1018        let mut state = self.state.lock();
1019        let path = path.as_ref();
1020        let new_mtime = state.next_mtime;
1021        let new_inode = state.next_inode;
1022        state.next_inode += 1;
1023        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1024        state
1025            .write_path(path, move |entry| {
1026                match entry {
1027                    btree_map::Entry::Vacant(e) => {
1028                        e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1029                            inode: new_inode,
1030                            mtime: new_mtime,
1031                            content: Vec::new(),
1032                            len: 0,
1033                        })));
1034                    }
1035                    btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut().lock() {
1036                        FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1037                        FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1038                        FakeFsEntry::Symlink { .. } => {}
1039                    },
1040                }
1041                Ok(())
1042            })
1043            .unwrap();
1044        state.emit_event([(path.to_path_buf(), None)]);
1045    }
1046
1047    pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1048        self.write_file_internal(path, content).unwrap()
1049    }
1050
1051    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1052        let mut state = self.state.lock();
1053        let path = path.as_ref();
1054        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1055        state
1056            .write_path(path.as_ref(), move |e| match e {
1057                btree_map::Entry::Vacant(e) => {
1058                    e.insert(file);
1059                    Ok(())
1060                }
1061                btree_map::Entry::Occupied(mut e) => {
1062                    *e.get_mut() = file;
1063                    Ok(())
1064                }
1065            })
1066            .unwrap();
1067        state.emit_event([(path, None)]);
1068    }
1069
1070    fn write_file_internal(&self, path: impl AsRef<Path>, content: Vec<u8>) -> Result<()> {
1071        let mut state = self.state.lock();
1072        let path = path.as_ref();
1073        let inode = state.next_inode;
1074        let mtime = state.next_mtime;
1075        state.next_inode += 1;
1076        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1077        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1078            inode,
1079            mtime,
1080            len: content.len() as u64,
1081            content,
1082        }));
1083        let mut kind = None;
1084        state.write_path(path, {
1085            let kind = &mut kind;
1086            move |entry| {
1087                match entry {
1088                    btree_map::Entry::Vacant(e) => {
1089                        *kind = Some(PathEventKind::Created);
1090                        e.insert(file);
1091                    }
1092                    btree_map::Entry::Occupied(mut e) => {
1093                        *kind = Some(PathEventKind::Changed);
1094                        *e.get_mut() = file;
1095                    }
1096                }
1097                Ok(())
1098            }
1099        })?;
1100        state.emit_event([(path, kind)]);
1101        Ok(())
1102    }
1103
1104    pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1105        let path = path.as_ref();
1106        let path = normalize_path(path);
1107        let state = self.state.lock();
1108        let entry = state.read_path(&path)?;
1109        let entry = entry.lock();
1110        entry.file_content(&path).cloned()
1111    }
1112
1113    async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1114        let path = path.as_ref();
1115        let path = normalize_path(path);
1116        self.simulate_random_delay().await;
1117        let state = self.state.lock();
1118        let entry = state.read_path(&path)?;
1119        let entry = entry.lock();
1120        entry.file_content(&path).cloned()
1121    }
1122
1123    pub fn pause_events(&self) {
1124        self.state.lock().events_paused = true;
1125    }
1126
1127    pub fn buffered_event_count(&self) -> usize {
1128        self.state.lock().buffered_events.len()
1129    }
1130
1131    pub fn flush_events(&self, count: usize) {
1132        self.state.lock().flush_events(count);
1133    }
1134
1135    #[must_use]
1136    pub fn insert_tree<'a>(
1137        &'a self,
1138        path: impl 'a + AsRef<Path> + Send,
1139        tree: serde_json::Value,
1140    ) -> futures::future::BoxFuture<'a, ()> {
1141        use futures::FutureExt as _;
1142        use serde_json::Value::*;
1143
1144        async move {
1145            let path = path.as_ref();
1146
1147            match tree {
1148                Object(map) => {
1149                    self.create_dir(path).await.unwrap();
1150                    for (name, contents) in map {
1151                        let mut path = PathBuf::from(path);
1152                        path.push(name);
1153                        self.insert_tree(&path, contents).await;
1154                    }
1155                }
1156                Null => {
1157                    self.create_dir(path).await.unwrap();
1158                }
1159                String(contents) => {
1160                    self.insert_file(&path, contents.into_bytes()).await;
1161                }
1162                _ => {
1163                    panic!("JSON object must contain only objects, strings, or null");
1164                }
1165            }
1166        }
1167        .boxed()
1168    }
1169
1170    pub fn insert_tree_from_real_fs<'a>(
1171        &'a self,
1172        path: impl 'a + AsRef<Path> + Send,
1173        src_path: impl 'a + AsRef<Path> + Send,
1174    ) -> futures::future::BoxFuture<'a, ()> {
1175        use futures::FutureExt as _;
1176
1177        async move {
1178            let path = path.as_ref();
1179            if std::fs::metadata(&src_path).unwrap().is_file() {
1180                let contents = std::fs::read(src_path).unwrap();
1181                self.insert_file(path, contents).await;
1182            } else {
1183                self.create_dir(path).await.unwrap();
1184                for entry in std::fs::read_dir(&src_path).unwrap() {
1185                    let entry = entry.unwrap();
1186                    self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1187                        .await;
1188                }
1189            }
1190        }
1191        .boxed()
1192    }
1193
1194    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
1195    where
1196        F: FnOnce(&mut FakeGitRepositoryState),
1197    {
1198        let mut state = self.state.lock();
1199        let entry = state.read_path(dot_git).unwrap();
1200        let mut entry = entry.lock();
1201
1202        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1203            let repo_state = git_repo_state.get_or_insert_with(|| {
1204                Arc::new(Mutex::new(FakeGitRepositoryState::new(
1205                    dot_git.to_path_buf(),
1206                    state.git_event_tx.clone(),
1207                )))
1208            });
1209            let mut repo_state = repo_state.lock();
1210
1211            f(&mut repo_state);
1212
1213            if emit_git_event {
1214                state.emit_event([(dot_git, None)]);
1215            }
1216        } else {
1217            panic!("not a directory");
1218        }
1219    }
1220
1221    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1222        self.with_git_state(dot_git, true, |state| {
1223            let branch = branch.map(Into::into);
1224            state.branches.extend(branch.clone());
1225            state.current_branch_name = branch.map(Into::into)
1226        })
1227    }
1228
1229    pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1230        self.with_git_state(dot_git, true, |state| {
1231            if let Some(first) = branches.first() {
1232                if state.current_branch_name.is_none() {
1233                    state.current_branch_name = Some(first.to_string())
1234                }
1235            }
1236            state
1237                .branches
1238                .extend(branches.iter().map(ToString::to_string));
1239        })
1240    }
1241
1242    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
1243        self.with_git_state(dot_git, true, |state| {
1244            state.index_contents.clear();
1245            state.index_contents.extend(
1246                head_state
1247                    .iter()
1248                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
1249            );
1250        });
1251    }
1252
1253    pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(&Path, git::blame::Blame)>) {
1254        self.with_git_state(dot_git, true, |state| {
1255            state.blames.clear();
1256            state.blames.extend(
1257                blames
1258                    .into_iter()
1259                    .map(|(path, blame)| (path.to_path_buf(), blame)),
1260            );
1261        });
1262    }
1263
1264    pub fn set_status_for_repo_via_working_copy_change(
1265        &self,
1266        dot_git: &Path,
1267        statuses: &[(&Path, GitFileStatus)],
1268    ) {
1269        self.with_git_state(dot_git, false, |state| {
1270            state.worktree_statuses.clear();
1271            state.worktree_statuses.extend(
1272                statuses
1273                    .iter()
1274                    .map(|(path, content)| ((**path).into(), *content)),
1275            );
1276        });
1277        self.state.lock().emit_event(
1278            statuses
1279                .iter()
1280                .map(|(path, _)| (dot_git.parent().unwrap().join(path), None)),
1281        );
1282    }
1283
1284    pub fn set_status_for_repo_via_git_operation(
1285        &self,
1286        dot_git: &Path,
1287        statuses: &[(&Path, GitFileStatus)],
1288    ) {
1289        self.with_git_state(dot_git, true, |state| {
1290            state.worktree_statuses.clear();
1291            state.worktree_statuses.extend(
1292                statuses
1293                    .iter()
1294                    .map(|(path, content)| ((**path).into(), *content)),
1295            );
1296        });
1297    }
1298
1299    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
1300        let mut result = Vec::new();
1301        let mut queue = collections::VecDeque::new();
1302        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1303        while let Some((path, entry)) = queue.pop_front() {
1304            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1305                for (name, entry) in entries {
1306                    queue.push_back((path.join(name), entry.clone()));
1307                }
1308            }
1309            if include_dot_git
1310                || !path
1311                    .components()
1312                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
1313            {
1314                result.push(path);
1315            }
1316        }
1317        result
1318    }
1319
1320    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
1321        let mut result = Vec::new();
1322        let mut queue = collections::VecDeque::new();
1323        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1324        while let Some((path, entry)) = queue.pop_front() {
1325            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
1326                for (name, entry) in entries {
1327                    queue.push_back((path.join(name), entry.clone()));
1328                }
1329                if include_dot_git
1330                    || !path
1331                        .components()
1332                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
1333                {
1334                    result.push(path);
1335                }
1336            }
1337        }
1338        result
1339    }
1340
1341    pub fn files(&self) -> Vec<PathBuf> {
1342        let mut result = Vec::new();
1343        let mut queue = collections::VecDeque::new();
1344        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
1345        while let Some((path, entry)) = queue.pop_front() {
1346            let e = entry.lock();
1347            match &*e {
1348                FakeFsEntry::File { .. } => result.push(path),
1349                FakeFsEntry::Dir { entries, .. } => {
1350                    for (name, entry) in entries {
1351                        queue.push_back((path.join(name), entry.clone()));
1352                    }
1353                }
1354                FakeFsEntry::Symlink { .. } => {}
1355            }
1356        }
1357        result
1358    }
1359
1360    /// How many `read_dir` calls have been issued.
1361    pub fn read_dir_call_count(&self) -> usize {
1362        self.state.lock().read_dir_call_count
1363    }
1364
1365    /// How many `metadata` calls have been issued.
1366    pub fn metadata_call_count(&self) -> usize {
1367        self.state.lock().metadata_call_count
1368    }
1369
1370    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
1371        self.executor.simulate_random_delay()
1372    }
1373}
1374
1375#[cfg(any(test, feature = "test-support"))]
1376impl FakeFsEntry {
1377    fn is_file(&self) -> bool {
1378        matches!(self, Self::File { .. })
1379    }
1380
1381    fn is_symlink(&self) -> bool {
1382        matches!(self, Self::Symlink { .. })
1383    }
1384
1385    fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
1386        if let Self::File { content, .. } = self {
1387            Ok(content)
1388        } else {
1389            Err(anyhow!("not a file: {}", path.display()))
1390        }
1391    }
1392
1393    fn set_file_content(&mut self, path: &Path, new_content: Vec<u8>) -> Result<()> {
1394        if let Self::File { content, mtime, .. } = self {
1395            *mtime = SystemTime::now();
1396            *content = new_content;
1397            Ok(())
1398        } else {
1399            Err(anyhow!("not a file: {}", path.display()))
1400        }
1401    }
1402
1403    fn dir_entries(
1404        &mut self,
1405        path: &Path,
1406    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
1407        if let Self::Dir { entries, .. } = self {
1408            Ok(entries)
1409        } else {
1410            Err(anyhow!("not a directory: {}", path.display()))
1411        }
1412    }
1413}
1414
1415#[cfg(any(test, feature = "test-support"))]
1416struct FakeWatcher {}
1417
1418#[cfg(any(test, feature = "test-support"))]
1419impl Watcher for FakeWatcher {
1420    fn add(&self, _: &Path) -> Result<()> {
1421        Ok(())
1422    }
1423
1424    fn remove(&self, _: &Path) -> Result<()> {
1425        Ok(())
1426    }
1427}
1428
1429#[cfg(any(test, feature = "test-support"))]
1430#[async_trait::async_trait]
1431impl Fs for FakeFs {
1432    async fn create_dir(&self, path: &Path) -> Result<()> {
1433        self.simulate_random_delay().await;
1434
1435        let mut created_dirs = Vec::new();
1436        let mut cur_path = PathBuf::new();
1437        for component in path.components() {
1438            let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
1439            cur_path.push(component);
1440            if should_skip {
1441                continue;
1442            }
1443            let mut state = self.state.lock();
1444
1445            let inode = state.next_inode;
1446            let mtime = state.next_mtime;
1447            state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1448            state.next_inode += 1;
1449            state.write_path(&cur_path, |entry| {
1450                entry.or_insert_with(|| {
1451                    created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
1452                    Arc::new(Mutex::new(FakeFsEntry::Dir {
1453                        inode,
1454                        mtime,
1455                        len: 0,
1456                        entries: Default::default(),
1457                        git_repo_state: None,
1458                    }))
1459                });
1460                Ok(())
1461            })?
1462        }
1463
1464        self.state.lock().emit_event(created_dirs);
1465        Ok(())
1466    }
1467
1468    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
1469        self.simulate_random_delay().await;
1470        let mut state = self.state.lock();
1471        let inode = state.next_inode;
1472        let mtime = state.next_mtime;
1473        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1474        state.next_inode += 1;
1475        let file = Arc::new(Mutex::new(FakeFsEntry::File {
1476            inode,
1477            mtime,
1478            len: 0,
1479            content: Vec::new(),
1480        }));
1481        let mut kind = Some(PathEventKind::Created);
1482        state.write_path(path, |entry| {
1483            match entry {
1484                btree_map::Entry::Occupied(mut e) => {
1485                    if options.overwrite {
1486                        kind = Some(PathEventKind::Changed);
1487                        *e.get_mut() = file;
1488                    } else if !options.ignore_if_exists {
1489                        return Err(anyhow!("path already exists: {}", path.display()));
1490                    }
1491                }
1492                btree_map::Entry::Vacant(e) => {
1493                    e.insert(file);
1494                }
1495            }
1496            Ok(())
1497        })?;
1498        state.emit_event([(path, kind)]);
1499        Ok(())
1500    }
1501
1502    async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
1503        let mut state = self.state.lock();
1504        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
1505        state
1506            .write_path(path.as_ref(), move |e| match e {
1507                btree_map::Entry::Vacant(e) => {
1508                    e.insert(file);
1509                    Ok(())
1510                }
1511                btree_map::Entry::Occupied(mut e) => {
1512                    *e.get_mut() = file;
1513                    Ok(())
1514                }
1515            })
1516            .unwrap();
1517        state.emit_event([(path, None)]);
1518
1519        Ok(())
1520    }
1521
1522    async fn create_file_with(
1523        &self,
1524        path: &Path,
1525        mut content: Pin<&mut (dyn AsyncRead + Send)>,
1526    ) -> Result<()> {
1527        let mut bytes = Vec::new();
1528        content.read_to_end(&mut bytes).await?;
1529        self.write_file_internal(path, bytes)?;
1530        Ok(())
1531    }
1532
1533    async fn extract_tar_file(
1534        &self,
1535        path: &Path,
1536        content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
1537    ) -> Result<()> {
1538        let mut entries = content.entries()?;
1539        while let Some(entry) = entries.next().await {
1540            let mut entry = entry?;
1541            if entry.header().entry_type().is_file() {
1542                let path = path.join(entry.path()?.as_ref());
1543                let mut bytes = Vec::new();
1544                entry.read_to_end(&mut bytes).await?;
1545                self.create_dir(path.parent().unwrap()).await?;
1546                self.write_file_internal(&path, bytes)?;
1547            }
1548        }
1549        Ok(())
1550    }
1551
1552    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
1553        self.simulate_random_delay().await;
1554
1555        let old_path = normalize_path(old_path);
1556        let new_path = normalize_path(new_path);
1557
1558        let mut state = self.state.lock();
1559        let moved_entry = state.write_path(&old_path, |e| {
1560            if let btree_map::Entry::Occupied(e) = e {
1561                Ok(e.get().clone())
1562            } else {
1563                Err(anyhow!("path does not exist: {}", &old_path.display()))
1564            }
1565        })?;
1566
1567        state.write_path(&new_path, |e| {
1568            match e {
1569                btree_map::Entry::Occupied(mut e) => {
1570                    if options.overwrite {
1571                        *e.get_mut() = moved_entry;
1572                    } else if !options.ignore_if_exists {
1573                        return Err(anyhow!("path already exists: {}", new_path.display()));
1574                    }
1575                }
1576                btree_map::Entry::Vacant(e) => {
1577                    e.insert(moved_entry);
1578                }
1579            }
1580            Ok(())
1581        })?;
1582
1583        state
1584            .write_path(&old_path, |e| {
1585                if let btree_map::Entry::Occupied(e) = e {
1586                    Ok(e.remove())
1587                } else {
1588                    unreachable!()
1589                }
1590            })
1591            .unwrap();
1592
1593        state.emit_event([
1594            (old_path, Some(PathEventKind::Removed)),
1595            (new_path, Some(PathEventKind::Created)),
1596        ]);
1597        Ok(())
1598    }
1599
1600    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
1601        self.simulate_random_delay().await;
1602
1603        let source = normalize_path(source);
1604        let target = normalize_path(target);
1605        let mut state = self.state.lock();
1606        let mtime = state.next_mtime;
1607        let inode = util::post_inc(&mut state.next_inode);
1608        state.next_mtime += Duration::from_nanos(Self::SYSTEMTIME_INTERVAL);
1609        let source_entry = state.read_path(&source)?;
1610        let content = source_entry.lock().file_content(&source)?.clone();
1611        let mut kind = Some(PathEventKind::Created);
1612        let entry = state.write_path(&target, |e| match e {
1613            btree_map::Entry::Occupied(e) => {
1614                if options.overwrite {
1615                    kind = Some(PathEventKind::Changed);
1616                    Ok(Some(e.get().clone()))
1617                } else if !options.ignore_if_exists {
1618                    return Err(anyhow!("{target:?} already exists"));
1619                } else {
1620                    Ok(None)
1621                }
1622            }
1623            btree_map::Entry::Vacant(e) => Ok(Some(
1624                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
1625                    inode,
1626                    mtime,
1627                    len: content.len() as u64,
1628                    content: Vec::new(),
1629                })))
1630                .clone(),
1631            )),
1632        })?;
1633        if let Some(entry) = entry {
1634            entry.lock().set_file_content(&target, content)?;
1635        }
1636        state.emit_event([(target, kind)]);
1637        Ok(())
1638    }
1639
1640    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1641        self.simulate_random_delay().await;
1642
1643        let path = normalize_path(path);
1644        let parent_path = path
1645            .parent()
1646            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1647        let base_name = path.file_name().unwrap();
1648
1649        let mut state = self.state.lock();
1650        let parent_entry = state.read_path(parent_path)?;
1651        let mut parent_entry = parent_entry.lock();
1652        let entry = parent_entry
1653            .dir_entries(parent_path)?
1654            .entry(base_name.to_str().unwrap().into());
1655
1656        match entry {
1657            btree_map::Entry::Vacant(_) => {
1658                if !options.ignore_if_not_exists {
1659                    return Err(anyhow!("{path:?} does not exist"));
1660                }
1661            }
1662            btree_map::Entry::Occupied(e) => {
1663                {
1664                    let mut entry = e.get().lock();
1665                    let children = entry.dir_entries(&path)?;
1666                    if !options.recursive && !children.is_empty() {
1667                        return Err(anyhow!("{path:?} is not empty"));
1668                    }
1669                }
1670                e.remove();
1671            }
1672        }
1673        state.emit_event([(path, Some(PathEventKind::Removed))]);
1674        Ok(())
1675    }
1676
1677    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1678        self.simulate_random_delay().await;
1679
1680        let path = normalize_path(path);
1681        let parent_path = path
1682            .parent()
1683            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1684        let base_name = path.file_name().unwrap();
1685        let mut state = self.state.lock();
1686        let parent_entry = state.read_path(parent_path)?;
1687        let mut parent_entry = parent_entry.lock();
1688        let entry = parent_entry
1689            .dir_entries(parent_path)?
1690            .entry(base_name.to_str().unwrap().into());
1691        match entry {
1692            btree_map::Entry::Vacant(_) => {
1693                if !options.ignore_if_not_exists {
1694                    return Err(anyhow!("{path:?} does not exist"));
1695                }
1696            }
1697            btree_map::Entry::Occupied(e) => {
1698                e.get().lock().file_content(&path)?;
1699                e.remove();
1700            }
1701        }
1702        state.emit_event([(path, Some(PathEventKind::Removed))]);
1703        Ok(())
1704    }
1705
1706    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1707        let bytes = self.load_internal(path).await?;
1708        Ok(Box::new(io::Cursor::new(bytes)))
1709    }
1710
1711    async fn load(&self, path: &Path) -> Result<String> {
1712        let content = self.load_internal(path).await?;
1713        Ok(String::from_utf8(content.clone())?)
1714    }
1715
1716    async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
1717        self.load_internal(path).await
1718    }
1719
1720    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1721        self.simulate_random_delay().await;
1722        let path = normalize_path(path.as_path());
1723        self.write_file_internal(path, data.into_bytes())?;
1724        Ok(())
1725    }
1726
1727    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1728        self.simulate_random_delay().await;
1729        let path = normalize_path(path);
1730        let content = chunks(text, line_ending).collect::<String>();
1731        if let Some(path) = path.parent() {
1732            self.create_dir(path).await?;
1733        }
1734        self.write_file_internal(path, content.into_bytes())?;
1735        Ok(())
1736    }
1737
1738    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1739        let path = normalize_path(path);
1740        self.simulate_random_delay().await;
1741        let state = self.state.lock();
1742        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1743            Ok(canonical_path)
1744        } else {
1745            Err(anyhow!("path does not exist: {}", path.display()))
1746        }
1747    }
1748
1749    async fn is_file(&self, path: &Path) -> bool {
1750        let path = normalize_path(path);
1751        self.simulate_random_delay().await;
1752        let state = self.state.lock();
1753        if let Some((entry, _)) = state.try_read_path(&path, true) {
1754            entry.lock().is_file()
1755        } else {
1756            false
1757        }
1758    }
1759
1760    async fn is_dir(&self, path: &Path) -> bool {
1761        self.metadata(path)
1762            .await
1763            .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
1764    }
1765
1766    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1767        self.simulate_random_delay().await;
1768        let path = normalize_path(path);
1769        let mut state = self.state.lock();
1770        state.metadata_call_count += 1;
1771        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1772            let is_symlink = entry.lock().is_symlink();
1773            if is_symlink {
1774                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1775                    entry = e;
1776                } else {
1777                    return Ok(None);
1778                }
1779            }
1780
1781            let entry = entry.lock();
1782            Ok(Some(match &*entry {
1783                FakeFsEntry::File {
1784                    inode, mtime, len, ..
1785                } => Metadata {
1786                    inode: *inode,
1787                    mtime: *mtime,
1788                    len: *len,
1789                    is_dir: false,
1790                    is_symlink,
1791                    is_fifo: false,
1792                },
1793                FakeFsEntry::Dir {
1794                    inode, mtime, len, ..
1795                } => Metadata {
1796                    inode: *inode,
1797                    mtime: *mtime,
1798                    len: *len,
1799                    is_dir: true,
1800                    is_symlink,
1801                    is_fifo: false,
1802                },
1803                FakeFsEntry::Symlink { .. } => unreachable!(),
1804            }))
1805        } else {
1806            Ok(None)
1807        }
1808    }
1809
1810    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1811        self.simulate_random_delay().await;
1812        let path = normalize_path(path);
1813        let state = self.state.lock();
1814        if let Some((entry, _)) = state.try_read_path(&path, false) {
1815            let entry = entry.lock();
1816            if let FakeFsEntry::Symlink { target } = &*entry {
1817                Ok(target.clone())
1818            } else {
1819                Err(anyhow!("not a symlink: {}", path.display()))
1820            }
1821        } else {
1822            Err(anyhow!("path does not exist: {}", path.display()))
1823        }
1824    }
1825
1826    async fn read_dir(
1827        &self,
1828        path: &Path,
1829    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1830        self.simulate_random_delay().await;
1831        let path = normalize_path(path);
1832        let mut state = self.state.lock();
1833        state.read_dir_call_count += 1;
1834        let entry = state.read_path(&path)?;
1835        let mut entry = entry.lock();
1836        let children = entry.dir_entries(&path)?;
1837        let paths = children
1838            .keys()
1839            .map(|file_name| Ok(path.join(file_name)))
1840            .collect::<Vec<_>>();
1841        Ok(Box::pin(futures::stream::iter(paths)))
1842    }
1843
1844    async fn watch(
1845        &self,
1846        path: &Path,
1847        _: Duration,
1848    ) -> (
1849        Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1850        Arc<dyn Watcher>,
1851    ) {
1852        self.simulate_random_delay().await;
1853        let (tx, rx) = smol::channel::unbounded();
1854        self.state.lock().event_txs.push(tx);
1855        let path = path.to_path_buf();
1856        let executor = self.executor.clone();
1857        (
1858            Box::pin(futures::StreamExt::filter(rx, move |events| {
1859                let result = events
1860                    .iter()
1861                    .any(|evt_path| evt_path.path.starts_with(&path));
1862                let executor = executor.clone();
1863                async move {
1864                    executor.simulate_random_delay().await;
1865                    result
1866                }
1867            })),
1868            Arc::new(FakeWatcher {}),
1869        )
1870    }
1871
1872    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<dyn GitRepository>> {
1873        let state = self.state.lock();
1874        let entry = state.read_path(abs_dot_git).unwrap();
1875        let mut entry = entry.lock();
1876        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1877            let state = git_repo_state
1878                .get_or_insert_with(|| {
1879                    Arc::new(Mutex::new(FakeGitRepositoryState::new(
1880                        abs_dot_git.to_path_buf(),
1881                        state.git_event_tx.clone(),
1882                    )))
1883                })
1884                .clone();
1885            Some(git::repository::FakeGitRepository::open(state))
1886        } else {
1887            None
1888        }
1889    }
1890
1891    fn is_fake(&self) -> bool {
1892        true
1893    }
1894
1895    async fn is_case_sensitive(&self) -> Result<bool> {
1896        Ok(true)
1897    }
1898
1899    #[cfg(any(test, feature = "test-support"))]
1900    fn as_fake(&self) -> &FakeFs {
1901        self
1902    }
1903}
1904
1905fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1906    rope.chunks().flat_map(move |chunk| {
1907        let mut newline = false;
1908        chunk.split('\n').flat_map(move |line| {
1909            let ending = if newline {
1910                Some(line_ending.as_str())
1911            } else {
1912                None
1913            };
1914            newline = true;
1915            ending.into_iter().chain([line])
1916        })
1917    })
1918}
1919
1920pub fn normalize_path(path: &Path) -> PathBuf {
1921    let mut components = path.components().peekable();
1922    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1923        components.next();
1924        PathBuf::from(c.as_os_str())
1925    } else {
1926        PathBuf::new()
1927    };
1928
1929    for component in components {
1930        match component {
1931            Component::Prefix(..) => unreachable!(),
1932            Component::RootDir => {
1933                ret.push(component.as_os_str());
1934            }
1935            Component::CurDir => {}
1936            Component::ParentDir => {
1937                ret.pop();
1938            }
1939            Component::Normal(c) => {
1940                ret.push(c);
1941            }
1942        }
1943    }
1944    ret
1945}
1946
1947pub fn copy_recursive<'a>(
1948    fs: &'a dyn Fs,
1949    source: &'a Path,
1950    target: &'a Path,
1951    options: CopyOptions,
1952) -> BoxFuture<'a, Result<()>> {
1953    use futures::future::FutureExt;
1954
1955    async move {
1956        let metadata = fs
1957            .metadata(source)
1958            .await?
1959            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1960        if metadata.is_dir {
1961            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1962                if options.ignore_if_exists {
1963                    return Ok(());
1964                } else {
1965                    return Err(anyhow!("{target:?} already exists"));
1966                }
1967            }
1968
1969            let _ = fs
1970                .remove_dir(
1971                    target,
1972                    RemoveOptions {
1973                        recursive: true,
1974                        ignore_if_not_exists: true,
1975                    },
1976                )
1977                .await;
1978            fs.create_dir(target).await?;
1979            let mut children = fs.read_dir(source).await?;
1980            while let Some(child_path) = children.next().await {
1981                if let Ok(child_path) = child_path {
1982                    if let Some(file_name) = child_path.file_name() {
1983                        let child_target_path = target.join(file_name);
1984                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1985                    }
1986                }
1987            }
1988
1989            Ok(())
1990        } else {
1991            fs.copy_file(source, target, options).await
1992        }
1993    }
1994    .boxed()
1995}
1996
1997// todo(windows)
1998// can we get file id not open the file twice?
1999// https://github.com/rust-lang/rust/issues/63010
2000#[cfg(target_os = "windows")]
2001async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2002    use std::os::windows::io::AsRawHandle;
2003
2004    use smol::fs::windows::OpenOptionsExt;
2005    use windows::Win32::{
2006        Foundation::HANDLE,
2007        Storage::FileSystem::{
2008            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
2009        },
2010    };
2011
2012    let file = smol::fs::OpenOptions::new()
2013        .read(true)
2014        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2015        .open(path)
2016        .await?;
2017
2018    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2019    // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2020    // This function supports Windows XP+
2021    smol::unblock(move || {
2022        unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2023
2024        Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2025    })
2026    .await
2027}
2028
2029#[cfg(test)]
2030mod tests {
2031    use super::*;
2032    use gpui::BackgroundExecutor;
2033    use serde_json::json;
2034
2035    #[gpui::test]
2036    async fn test_fake_fs(executor: BackgroundExecutor) {
2037        let fs = FakeFs::new(executor.clone());
2038        fs.insert_tree(
2039            "/root",
2040            json!({
2041                "dir1": {
2042                    "a": "A",
2043                    "b": "B"
2044                },
2045                "dir2": {
2046                    "c": "C",
2047                    "dir3": {
2048                        "d": "D"
2049                    }
2050                }
2051            }),
2052        )
2053        .await;
2054
2055        assert_eq!(
2056            fs.files(),
2057            vec![
2058                PathBuf::from("/root/dir1/a"),
2059                PathBuf::from("/root/dir1/b"),
2060                PathBuf::from("/root/dir2/c"),
2061                PathBuf::from("/root/dir2/dir3/d"),
2062            ]
2063        );
2064
2065        fs.create_symlink("/root/dir2/link-to-dir3".as_ref(), "./dir3".into())
2066            .await
2067            .unwrap();
2068
2069        assert_eq!(
2070            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
2071                .await
2072                .unwrap(),
2073            PathBuf::from("/root/dir2/dir3"),
2074        );
2075        assert_eq!(
2076            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
2077                .await
2078                .unwrap(),
2079            PathBuf::from("/root/dir2/dir3/d"),
2080        );
2081        assert_eq!(
2082            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
2083            "D",
2084        );
2085    }
2086}
2087
2088#[cfg(target_os = "linux")]
2089pub mod watcher {
2090    use std::sync::OnceLock;
2091
2092    use parking_lot::Mutex;
2093    use util::ResultExt;
2094
2095    pub struct GlobalWatcher {
2096        // two mutexes because calling inotify.add triggers an inotify.event, which needs watchers.
2097        pub(super) inotify: Mutex<notify::INotifyWatcher>,
2098        pub(super) watchers: Mutex<Vec<Box<dyn Fn(&notify::Event) + Send + Sync>>>,
2099    }
2100
2101    impl GlobalWatcher {
2102        pub(super) fn add(&self, cb: impl Fn(&notify::Event) + Send + Sync + 'static) {
2103            self.watchers.lock().push(Box::new(cb))
2104        }
2105    }
2106
2107    static INOTIFY_INSTANCE: OnceLock<anyhow::Result<GlobalWatcher, notify::Error>> =
2108        OnceLock::new();
2109
2110    fn handle_event(event: Result<notify::Event, notify::Error>) {
2111        let Some(event) = event.log_err() else { return };
2112        global::<()>(move |watcher| {
2113            for f in watcher.watchers.lock().iter() {
2114                f(&event)
2115            }
2116        })
2117        .log_err();
2118    }
2119
2120    pub fn global<T>(f: impl FnOnce(&GlobalWatcher) -> T) -> anyhow::Result<T> {
2121        let result = INOTIFY_INSTANCE.get_or_init(|| {
2122            notify::recommended_watcher(handle_event).map(|file_watcher| GlobalWatcher {
2123                inotify: Mutex::new(file_watcher),
2124                watchers: Default::default(),
2125            })
2126        });
2127        match result {
2128            Ok(g) => Ok(f(g)),
2129            Err(e) => Err(anyhow::anyhow!("{}", e)),
2130        }
2131    }
2132}