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