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