fs.rs

   1pub mod repository;
   2
   3use anyhow::{anyhow, Result};
   4use fsevent::EventStream;
   5use futures::{future::BoxFuture, Stream, StreamExt};
   6use git2::Repository as LibGitRepository;
   7use lazy_static::lazy_static;
   8use parking_lot::Mutex;
   9use regex::Regex;
  10use repository::GitRepository;
  11use rope::Rope;
  12use smol::io::{AsyncReadExt, AsyncWriteExt};
  13use std::borrow::Cow;
  14use std::cmp;
  15use std::io::Write;
  16use std::sync::Arc;
  17use std::{
  18    io,
  19    os::unix::fs::MetadataExt,
  20    path::{Component, Path, PathBuf},
  21    pin::Pin,
  22    time::{Duration, SystemTime},
  23};
  24use tempfile::NamedTempFile;
  25use util::ResultExt;
  26
  27#[cfg(any(test, feature = "test-support"))]
  28use collections::{btree_map, BTreeMap};
  29#[cfg(any(test, feature = "test-support"))]
  30use repository::{FakeGitRepositoryState, GitFileStatus};
  31#[cfg(any(test, feature = "test-support"))]
  32use std::ffi::OsStr;
  33#[cfg(any(test, feature = "test-support"))]
  34use std::sync::Weak;
  35
  36lazy_static! {
  37    static ref LINE_SEPARATORS_REGEX: Regex = Regex::new("\r\n|\r|\u{2028}|\u{2029}").unwrap();
  38}
  39
  40#[derive(Clone, Copy, Debug, PartialEq)]
  41pub enum LineEnding {
  42    Unix,
  43    Windows,
  44}
  45
  46impl Default for LineEnding {
  47    fn default() -> Self {
  48        #[cfg(unix)]
  49        return Self::Unix;
  50
  51        #[cfg(not(unix))]
  52        return Self::CRLF;
  53    }
  54}
  55
  56impl LineEnding {
  57    pub fn as_str(&self) -> &'static str {
  58        match self {
  59            LineEnding::Unix => "\n",
  60            LineEnding::Windows => "\r\n",
  61        }
  62    }
  63
  64    pub fn detect(text: &str) -> Self {
  65        let mut max_ix = cmp::min(text.len(), 1000);
  66        while !text.is_char_boundary(max_ix) {
  67            max_ix -= 1;
  68        }
  69
  70        if let Some(ix) = text[..max_ix].find(&['\n']) {
  71            if ix > 0 && text.as_bytes()[ix - 1] == b'\r' {
  72                Self::Windows
  73            } else {
  74                Self::Unix
  75            }
  76        } else {
  77            Self::default()
  78        }
  79    }
  80
  81    pub fn normalize(text: &mut String) {
  82        if let Cow::Owned(replaced) = LINE_SEPARATORS_REGEX.replace_all(text, "\n") {
  83            *text = replaced;
  84        }
  85    }
  86
  87    pub fn normalize_arc(text: Arc<str>) -> Arc<str> {
  88        if let Cow::Owned(replaced) = LINE_SEPARATORS_REGEX.replace_all(&text, "\n") {
  89            replaced.into()
  90        } else {
  91            text
  92        }
  93    }
  94}
  95
  96#[async_trait::async_trait]
  97pub trait Fs: Send + Sync {
  98    async fn create_dir(&self, path: &Path) -> Result<()>;
  99    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
 100    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
 101    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
 102    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 103    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
 104    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
 105    async fn load(&self, path: &Path) -> Result<String>;
 106    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
 107    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
 108    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
 109    async fn is_file(&self, path: &Path) -> bool;
 110    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
 111    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
 112    async fn read_dir(
 113        &self,
 114        path: &Path,
 115    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
 116    async fn watch(
 117        &self,
 118        path: &Path,
 119        latency: Duration,
 120    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>;
 121    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>>;
 122    fn is_fake(&self) -> bool;
 123    #[cfg(any(test, feature = "test-support"))]
 124    fn as_fake(&self) -> &FakeFs;
 125}
 126
 127#[derive(Copy, Clone, Default)]
 128pub struct CreateOptions {
 129    pub overwrite: bool,
 130    pub ignore_if_exists: bool,
 131}
 132
 133#[derive(Copy, Clone, Default)]
 134pub struct CopyOptions {
 135    pub overwrite: bool,
 136    pub ignore_if_exists: bool,
 137}
 138
 139#[derive(Copy, Clone, Default)]
 140pub struct RenameOptions {
 141    pub overwrite: bool,
 142    pub ignore_if_exists: bool,
 143}
 144
 145#[derive(Copy, Clone, Default)]
 146pub struct RemoveOptions {
 147    pub recursive: bool,
 148    pub ignore_if_not_exists: bool,
 149}
 150
 151#[derive(Clone, Debug)]
 152pub struct Metadata {
 153    pub inode: u64,
 154    pub mtime: SystemTime,
 155    pub is_symlink: bool,
 156    pub is_dir: bool,
 157}
 158
 159impl From<lsp::CreateFileOptions> for CreateOptions {
 160    fn from(options: lsp::CreateFileOptions) -> Self {
 161        Self {
 162            overwrite: options.overwrite.unwrap_or(false),
 163            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 164        }
 165    }
 166}
 167
 168impl From<lsp::RenameFileOptions> for RenameOptions {
 169    fn from(options: lsp::RenameFileOptions) -> Self {
 170        Self {
 171            overwrite: options.overwrite.unwrap_or(false),
 172            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 173        }
 174    }
 175}
 176
 177impl From<lsp::DeleteFileOptions> for RemoveOptions {
 178    fn from(options: lsp::DeleteFileOptions) -> Self {
 179        Self {
 180            recursive: options.recursive.unwrap_or(false),
 181            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 182        }
 183    }
 184}
 185
 186pub struct RealFs;
 187
 188#[async_trait::async_trait]
 189impl Fs for RealFs {
 190    async fn create_dir(&self, path: &Path) -> Result<()> {
 191        Ok(smol::fs::create_dir_all(path).await?)
 192    }
 193
 194    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 195        let mut open_options = smol::fs::OpenOptions::new();
 196        open_options.write(true).create(true);
 197        if options.overwrite {
 198            open_options.truncate(true);
 199        } else if !options.ignore_if_exists {
 200            open_options.create_new(true);
 201        }
 202        open_options.open(path).await?;
 203        Ok(())
 204    }
 205
 206    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 207        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 208            if options.ignore_if_exists {
 209                return Ok(());
 210            } else {
 211                return Err(anyhow!("{target:?} already exists"));
 212            }
 213        }
 214
 215        smol::fs::copy(source, target).await?;
 216        Ok(())
 217    }
 218
 219    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 220        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 221            if options.ignore_if_exists {
 222                return Ok(());
 223            } else {
 224                return Err(anyhow!("{target:?} already exists"));
 225            }
 226        }
 227
 228        smol::fs::rename(source, target).await?;
 229        Ok(())
 230    }
 231
 232    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 233        let result = if options.recursive {
 234            smol::fs::remove_dir_all(path).await
 235        } else {
 236            smol::fs::remove_dir(path).await
 237        };
 238        match result {
 239            Ok(()) => Ok(()),
 240            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 241                Ok(())
 242            }
 243            Err(err) => Err(err)?,
 244        }
 245    }
 246
 247    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 248        match smol::fs::remove_file(path).await {
 249            Ok(()) => Ok(()),
 250            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 251                Ok(())
 252            }
 253            Err(err) => Err(err)?,
 254        }
 255    }
 256
 257    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 258        Ok(Box::new(std::fs::File::open(path)?))
 259    }
 260
 261    async fn load(&self, path: &Path) -> Result<String> {
 262        let mut file = smol::fs::File::open(path).await?;
 263        let mut text = String::new();
 264        file.read_to_string(&mut text).await?;
 265        Ok(text)
 266    }
 267
 268    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 269        smol::unblock(move || {
 270            let mut tmp_file = NamedTempFile::new()?;
 271            tmp_file.write_all(data.as_bytes())?;
 272            tmp_file.persist(path)?;
 273            Ok::<(), anyhow::Error>(())
 274        })
 275        .await?;
 276
 277        Ok(())
 278    }
 279
 280    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 281        let buffer_size = text.summary().len.min(10 * 1024);
 282        let file = smol::fs::File::create(path).await?;
 283        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 284        for chunk in chunks(text, line_ending) {
 285            writer.write_all(chunk.as_bytes()).await?;
 286        }
 287        writer.flush().await?;
 288        Ok(())
 289    }
 290
 291    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 292        Ok(smol::fs::canonicalize(path).await?)
 293    }
 294
 295    async fn is_file(&self, path: &Path) -> bool {
 296        smol::fs::metadata(path)
 297            .await
 298            .map_or(false, |metadata| metadata.is_file())
 299    }
 300
 301    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 302        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 303            Ok(metadata) => metadata,
 304            Err(err) => {
 305                return match (err.kind(), err.raw_os_error()) {
 306                    (io::ErrorKind::NotFound, _) => Ok(None),
 307                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 308                    _ => Err(anyhow::Error::new(err)),
 309                }
 310            }
 311        };
 312
 313        let is_symlink = symlink_metadata.file_type().is_symlink();
 314        let metadata = if is_symlink {
 315            smol::fs::metadata(path).await?
 316        } else {
 317            symlink_metadata
 318        };
 319        Ok(Some(Metadata {
 320            inode: metadata.ino(),
 321            mtime: metadata.modified().unwrap(),
 322            is_symlink,
 323            is_dir: metadata.file_type().is_dir(),
 324        }))
 325    }
 326
 327    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 328        let path = smol::fs::read_link(path).await?;
 329        Ok(path)
 330    }
 331
 332    async fn read_dir(
 333        &self,
 334        path: &Path,
 335    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 336        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 337            Ok(entry) => Ok(entry.path()),
 338            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 339        });
 340        Ok(Box::pin(result))
 341    }
 342
 343    async fn watch(
 344        &self,
 345        path: &Path,
 346        latency: Duration,
 347    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
 348        let (tx, rx) = smol::channel::unbounded();
 349        let (stream, handle) = EventStream::new(&[path], latency);
 350        std::thread::spawn(move || {
 351            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
 352        });
 353        Box::pin(rx.chain(futures::stream::once(async move {
 354            drop(handle);
 355            vec![]
 356        })))
 357    }
 358
 359    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
 360        LibGitRepository::open(&dotgit_path)
 361            .log_err()
 362            .and_then::<Arc<Mutex<dyn GitRepository>>, _>(|libgit_repository| {
 363                Some(Arc::new(Mutex::new(libgit_repository)))
 364            })
 365    }
 366
 367    fn is_fake(&self) -> bool {
 368        false
 369    }
 370    #[cfg(any(test, feature = "test-support"))]
 371    fn as_fake(&self) -> &FakeFs {
 372        panic!("called `RealFs::as_fake`")
 373    }
 374}
 375
 376#[cfg(any(test, feature = "test-support"))]
 377pub struct FakeFs {
 378    // Use an unfair lock to ensure tests are deterministic.
 379    state: Mutex<FakeFsState>,
 380    executor: Weak<gpui::executor::Background>,
 381}
 382
 383#[cfg(any(test, feature = "test-support"))]
 384struct FakeFsState {
 385    root: Arc<Mutex<FakeFsEntry>>,
 386    next_inode: u64,
 387    next_mtime: SystemTime,
 388    event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
 389    events_paused: bool,
 390    buffered_events: Vec<fsevent::Event>,
 391}
 392
 393#[cfg(any(test, feature = "test-support"))]
 394#[derive(Debug)]
 395enum FakeFsEntry {
 396    File {
 397        inode: u64,
 398        mtime: SystemTime,
 399        content: String,
 400    },
 401    Dir {
 402        inode: u64,
 403        mtime: SystemTime,
 404        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 405        git_repo_state: Option<Arc<Mutex<repository::FakeGitRepositoryState>>>,
 406    },
 407    Symlink {
 408        target: PathBuf,
 409    },
 410}
 411
 412#[cfg(any(test, feature = "test-support"))]
 413impl FakeFsState {
 414    fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 415        Ok(self
 416            .try_read_path(target, true)
 417            .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
 418            .0)
 419    }
 420
 421    fn try_read_path<'a>(
 422        &'a self,
 423        target: &Path,
 424        follow_symlink: bool,
 425    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 426        let mut path = target.to_path_buf();
 427        let mut canonical_path = PathBuf::new();
 428        let mut entry_stack = Vec::new();
 429        'outer: loop {
 430            let mut path_components = path.components().peekable();
 431            while let Some(component) = path_components.next() {
 432                match component {
 433                    Component::Prefix(_) => panic!("prefix paths aren't supported"),
 434                    Component::RootDir => {
 435                        entry_stack.clear();
 436                        entry_stack.push(self.root.clone());
 437                        canonical_path.clear();
 438                        canonical_path.push("/");
 439                    }
 440                    Component::CurDir => {}
 441                    Component::ParentDir => {
 442                        entry_stack.pop()?;
 443                        canonical_path.pop();
 444                    }
 445                    Component::Normal(name) => {
 446                        let current_entry = entry_stack.last().cloned()?;
 447                        let current_entry = current_entry.lock();
 448                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 449                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 450                            if path_components.peek().is_some() || follow_symlink {
 451                                let entry = entry.lock();
 452                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 453                                    let mut target = target.clone();
 454                                    target.extend(path_components);
 455                                    path = target;
 456                                    continue 'outer;
 457                                }
 458                            }
 459                            entry_stack.push(entry.clone());
 460                            canonical_path.push(name);
 461                        } else {
 462                            return None;
 463                        }
 464                    }
 465                }
 466            }
 467            break;
 468        }
 469        Some((entry_stack.pop()?, canonical_path))
 470    }
 471
 472    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 473    where
 474        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 475    {
 476        let path = normalize_path(path);
 477        let filename = path
 478            .file_name()
 479            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 480        let parent_path = path.parent().unwrap();
 481
 482        let parent = self.read_path(parent_path)?;
 483        let mut parent = parent.lock();
 484        let new_entry = parent
 485            .dir_entries(parent_path)?
 486            .entry(filename.to_str().unwrap().into());
 487        callback(new_entry)
 488    }
 489
 490    fn emit_event<I, T>(&mut self, paths: I)
 491    where
 492        I: IntoIterator<Item = T>,
 493        T: Into<PathBuf>,
 494    {
 495        self.buffered_events
 496            .extend(paths.into_iter().map(|path| fsevent::Event {
 497                event_id: 0,
 498                flags: fsevent::StreamFlags::empty(),
 499                path: path.into(),
 500            }));
 501
 502        if !self.events_paused {
 503            self.flush_events(self.buffered_events.len());
 504        }
 505    }
 506
 507    fn flush_events(&mut self, mut count: usize) {
 508        count = count.min(self.buffered_events.len());
 509        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 510        self.event_txs.retain(|tx| {
 511            let _ = tx.try_send(events.clone());
 512            !tx.is_closed()
 513        });
 514    }
 515}
 516
 517#[cfg(any(test, feature = "test-support"))]
 518lazy_static! {
 519    pub static ref FS_DOT_GIT: &'static OsStr = OsStr::new(".git");
 520}
 521
 522#[cfg(any(test, feature = "test-support"))]
 523impl FakeFs {
 524    pub fn new(executor: Arc<gpui::executor::Background>) -> Arc<Self> {
 525        Arc::new(Self {
 526            executor: Arc::downgrade(&executor),
 527            state: Mutex::new(FakeFsState {
 528                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 529                    inode: 0,
 530                    mtime: SystemTime::UNIX_EPOCH,
 531                    entries: Default::default(),
 532                    git_repo_state: None,
 533                })),
 534                next_mtime: SystemTime::UNIX_EPOCH,
 535                next_inode: 1,
 536                event_txs: Default::default(),
 537                buffered_events: Vec::new(),
 538                events_paused: false,
 539            }),
 540        })
 541    }
 542
 543    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
 544        self.write_file_internal(path, content).unwrap()
 545    }
 546
 547    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 548        let mut state = self.state.lock();
 549        let path = path.as_ref();
 550        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 551        state
 552            .write_path(path.as_ref(), move |e| match e {
 553                btree_map::Entry::Vacant(e) => {
 554                    e.insert(file);
 555                    Ok(())
 556                }
 557                btree_map::Entry::Occupied(mut e) => {
 558                    *e.get_mut() = file;
 559                    Ok(())
 560                }
 561            })
 562            .unwrap();
 563        state.emit_event(&[path]);
 564    }
 565
 566    fn write_file_internal(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
 567        let mut state = self.state.lock();
 568        let path = path.as_ref();
 569        let inode = state.next_inode;
 570        let mtime = state.next_mtime;
 571        state.next_inode += 1;
 572        state.next_mtime += Duration::from_nanos(1);
 573        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 574            inode,
 575            mtime,
 576            content,
 577        }));
 578        state.write_path(path, move |entry| {
 579            match entry {
 580                btree_map::Entry::Vacant(e) => {
 581                    e.insert(file);
 582                }
 583                btree_map::Entry::Occupied(mut e) => {
 584                    *e.get_mut() = file;
 585                }
 586            }
 587            Ok(())
 588        })?;
 589        state.emit_event(&[path]);
 590        Ok(())
 591    }
 592
 593    pub fn pause_events(&self) {
 594        self.state.lock().events_paused = true;
 595    }
 596
 597    pub fn buffered_event_count(&self) -> usize {
 598        self.state.lock().buffered_events.len()
 599    }
 600
 601    pub fn flush_events(&self, count: usize) {
 602        self.state.lock().flush_events(count);
 603    }
 604
 605    #[must_use]
 606    pub fn insert_tree<'a>(
 607        &'a self,
 608        path: impl 'a + AsRef<Path> + Send,
 609        tree: serde_json::Value,
 610    ) -> futures::future::BoxFuture<'a, ()> {
 611        use futures::FutureExt as _;
 612        use serde_json::Value::*;
 613
 614        async move {
 615            let path = path.as_ref();
 616
 617            match tree {
 618                Object(map) => {
 619                    self.create_dir(path).await.unwrap();
 620                    for (name, contents) in map {
 621                        let mut path = PathBuf::from(path);
 622                        path.push(name);
 623                        self.insert_tree(&path, contents).await;
 624                    }
 625                }
 626                Null => {
 627                    self.create_dir(path).await.unwrap();
 628                }
 629                String(contents) => {
 630                    self.insert_file(&path, contents).await;
 631                }
 632                _ => {
 633                    panic!("JSON object must contain only objects, strings, or null");
 634                }
 635            }
 636        }
 637        .boxed()
 638    }
 639
 640    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
 641    where
 642        F: FnOnce(&mut FakeGitRepositoryState),
 643    {
 644        let mut state = self.state.lock();
 645        let entry = state.read_path(dot_git).unwrap();
 646        let mut entry = entry.lock();
 647
 648        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
 649            let repo_state = git_repo_state.get_or_insert_with(Default::default);
 650            let mut repo_state = repo_state.lock();
 651
 652            f(&mut repo_state);
 653
 654            if emit_git_event {
 655                state.emit_event([dot_git]);
 656            }
 657        } else {
 658            panic!("not a directory");
 659        }
 660    }
 661
 662    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
 663        self.with_git_state(dot_git, true, |state| {
 664            state.branch_name = branch.map(Into::into)
 665        })
 666    }
 667
 668    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
 669        self.with_git_state(dot_git, true, |state| {
 670            state.index_contents.clear();
 671            state.index_contents.extend(
 672                head_state
 673                    .iter()
 674                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
 675            );
 676        });
 677    }
 678
 679    pub fn set_status_for_repo_via_working_copy_change(
 680        &self,
 681        dot_git: &Path,
 682        statuses: &[(&Path, GitFileStatus)],
 683    ) {
 684        self.with_git_state(dot_git, false, |state| {
 685            state.worktree_statuses.clear();
 686            state.worktree_statuses.extend(
 687                statuses
 688                    .iter()
 689                    .map(|(path, content)| ((**path).into(), content.clone())),
 690            );
 691        });
 692        self.state.lock().emit_event(
 693            statuses
 694                .iter()
 695                .map(|(path, _)| dot_git.parent().unwrap().join(path)),
 696        );
 697    }
 698
 699    pub fn set_status_for_repo_via_git_operation(
 700        &self,
 701        dot_git: &Path,
 702        statuses: &[(&Path, GitFileStatus)],
 703    ) {
 704        self.with_git_state(dot_git, true, |state| {
 705            state.worktree_statuses.clear();
 706            state.worktree_statuses.extend(
 707                statuses
 708                    .iter()
 709                    .map(|(path, content)| ((**path).into(), content.clone())),
 710            );
 711        });
 712    }
 713
 714    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
 715        let mut result = Vec::new();
 716        let mut queue = collections::VecDeque::new();
 717        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 718        while let Some((path, entry)) = queue.pop_front() {
 719            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 720                for (name, entry) in entries {
 721                    queue.push_back((path.join(name), entry.clone()));
 722                }
 723            }
 724            if include_dot_git
 725                || !path
 726                    .components()
 727                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
 728            {
 729                result.push(path);
 730            }
 731        }
 732        result
 733    }
 734
 735    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
 736        let mut result = Vec::new();
 737        let mut queue = collections::VecDeque::new();
 738        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 739        while let Some((path, entry)) = queue.pop_front() {
 740            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 741                for (name, entry) in entries {
 742                    queue.push_back((path.join(name), entry.clone()));
 743                }
 744                if include_dot_git
 745                    || !path
 746                        .components()
 747                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
 748                {
 749                    result.push(path);
 750                }
 751            }
 752        }
 753        result
 754    }
 755
 756    pub fn files(&self) -> Vec<PathBuf> {
 757        let mut result = Vec::new();
 758        let mut queue = collections::VecDeque::new();
 759        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 760        while let Some((path, entry)) = queue.pop_front() {
 761            let e = entry.lock();
 762            match &*e {
 763                FakeFsEntry::File { .. } => result.push(path),
 764                FakeFsEntry::Dir { entries, .. } => {
 765                    for (name, entry) in entries {
 766                        queue.push_back((path.join(name), entry.clone()));
 767                    }
 768                }
 769                FakeFsEntry::Symlink { .. } => {}
 770            }
 771        }
 772        result
 773    }
 774
 775    async fn simulate_random_delay(&self) {
 776        self.executor
 777            .upgrade()
 778            .expect("executor has been dropped")
 779            .simulate_random_delay()
 780            .await;
 781    }
 782}
 783
 784#[cfg(any(test, feature = "test-support"))]
 785impl FakeFsEntry {
 786    fn is_file(&self) -> bool {
 787        matches!(self, Self::File { .. })
 788    }
 789
 790    fn is_symlink(&self) -> bool {
 791        matches!(self, Self::Symlink { .. })
 792    }
 793
 794    fn file_content(&self, path: &Path) -> Result<&String> {
 795        if let Self::File { content, .. } = self {
 796            Ok(content)
 797        } else {
 798            Err(anyhow!("not a file: {}", path.display()))
 799        }
 800    }
 801
 802    fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
 803        if let Self::File { content, mtime, .. } = self {
 804            *mtime = SystemTime::now();
 805            *content = new_content;
 806            Ok(())
 807        } else {
 808            Err(anyhow!("not a file: {}", path.display()))
 809        }
 810    }
 811
 812    fn dir_entries(
 813        &mut self,
 814        path: &Path,
 815    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 816        if let Self::Dir { entries, .. } = self {
 817            Ok(entries)
 818        } else {
 819            Err(anyhow!("not a directory: {}", path.display()))
 820        }
 821    }
 822}
 823
 824#[cfg(any(test, feature = "test-support"))]
 825#[async_trait::async_trait]
 826impl Fs for FakeFs {
 827    async fn create_dir(&self, path: &Path) -> Result<()> {
 828        self.simulate_random_delay().await;
 829
 830        let mut created_dirs = Vec::new();
 831        let mut cur_path = PathBuf::new();
 832        for component in path.components() {
 833            let mut state = self.state.lock();
 834            cur_path.push(component);
 835            if cur_path == Path::new("/") {
 836                continue;
 837            }
 838
 839            let inode = state.next_inode;
 840            let mtime = state.next_mtime;
 841            state.next_mtime += Duration::from_nanos(1);
 842            state.next_inode += 1;
 843            state.write_path(&cur_path, |entry| {
 844                entry.or_insert_with(|| {
 845                    created_dirs.push(cur_path.clone());
 846                    Arc::new(Mutex::new(FakeFsEntry::Dir {
 847                        inode,
 848                        mtime,
 849                        entries: Default::default(),
 850                        git_repo_state: None,
 851                    }))
 852                });
 853                Ok(())
 854            })?
 855        }
 856
 857        self.state.lock().emit_event(&created_dirs);
 858        Ok(())
 859    }
 860
 861    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 862        self.simulate_random_delay().await;
 863        let mut state = self.state.lock();
 864        let inode = state.next_inode;
 865        let mtime = state.next_mtime;
 866        state.next_mtime += Duration::from_nanos(1);
 867        state.next_inode += 1;
 868        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 869            inode,
 870            mtime,
 871            content: String::new(),
 872        }));
 873        state.write_path(path, |entry| {
 874            match entry {
 875                btree_map::Entry::Occupied(mut e) => {
 876                    if options.overwrite {
 877                        *e.get_mut() = file;
 878                    } else if !options.ignore_if_exists {
 879                        return Err(anyhow!("path already exists: {}", path.display()));
 880                    }
 881                }
 882                btree_map::Entry::Vacant(e) => {
 883                    e.insert(file);
 884                }
 885            }
 886            Ok(())
 887        })?;
 888        state.emit_event(&[path]);
 889        Ok(())
 890    }
 891
 892    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
 893        self.simulate_random_delay().await;
 894
 895        let old_path = normalize_path(old_path);
 896        let new_path = normalize_path(new_path);
 897
 898        let mut state = self.state.lock();
 899        let moved_entry = state.write_path(&old_path, |e| {
 900            if let btree_map::Entry::Occupied(e) = e {
 901                Ok(e.get().clone())
 902            } else {
 903                Err(anyhow!("path does not exist: {}", &old_path.display()))
 904            }
 905        })?;
 906
 907        state.write_path(&new_path, |e| {
 908            match e {
 909                btree_map::Entry::Occupied(mut e) => {
 910                    if options.overwrite {
 911                        *e.get_mut() = moved_entry;
 912                    } else if !options.ignore_if_exists {
 913                        return Err(anyhow!("path already exists: {}", new_path.display()));
 914                    }
 915                }
 916                btree_map::Entry::Vacant(e) => {
 917                    e.insert(moved_entry);
 918                }
 919            }
 920            Ok(())
 921        })?;
 922
 923        state
 924            .write_path(&old_path, |e| {
 925                if let btree_map::Entry::Occupied(e) = e {
 926                    Ok(e.remove())
 927                } else {
 928                    unreachable!()
 929                }
 930            })
 931            .unwrap();
 932
 933        state.emit_event(&[old_path, new_path]);
 934        Ok(())
 935    }
 936
 937    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 938        self.simulate_random_delay().await;
 939
 940        let source = normalize_path(source);
 941        let target = normalize_path(target);
 942        let mut state = self.state.lock();
 943        let mtime = state.next_mtime;
 944        let inode = util::post_inc(&mut state.next_inode);
 945        state.next_mtime += Duration::from_nanos(1);
 946        let source_entry = state.read_path(&source)?;
 947        let content = source_entry.lock().file_content(&source)?.clone();
 948        let entry = state.write_path(&target, |e| match e {
 949            btree_map::Entry::Occupied(e) => {
 950                if options.overwrite {
 951                    Ok(Some(e.get().clone()))
 952                } else if !options.ignore_if_exists {
 953                    return Err(anyhow!("{target:?} already exists"));
 954                } else {
 955                    Ok(None)
 956                }
 957            }
 958            btree_map::Entry::Vacant(e) => Ok(Some(
 959                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
 960                    inode,
 961                    mtime,
 962                    content: String::new(),
 963                })))
 964                .clone(),
 965            )),
 966        })?;
 967        if let Some(entry) = entry {
 968            entry.lock().set_file_content(&target, content)?;
 969        }
 970        state.emit_event(&[target]);
 971        Ok(())
 972    }
 973
 974    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 975        self.simulate_random_delay().await;
 976
 977        let path = normalize_path(path);
 978        let parent_path = path
 979            .parent()
 980            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 981        let base_name = path.file_name().unwrap();
 982
 983        let mut state = self.state.lock();
 984        let parent_entry = state.read_path(parent_path)?;
 985        let mut parent_entry = parent_entry.lock();
 986        let entry = parent_entry
 987            .dir_entries(parent_path)?
 988            .entry(base_name.to_str().unwrap().into());
 989
 990        match entry {
 991            btree_map::Entry::Vacant(_) => {
 992                if !options.ignore_if_not_exists {
 993                    return Err(anyhow!("{path:?} does not exist"));
 994                }
 995            }
 996            btree_map::Entry::Occupied(e) => {
 997                {
 998                    let mut entry = e.get().lock();
 999                    let children = entry.dir_entries(&path)?;
1000                    if !options.recursive && !children.is_empty() {
1001                        return Err(anyhow!("{path:?} is not empty"));
1002                    }
1003                }
1004                e.remove();
1005            }
1006        }
1007        state.emit_event(&[path]);
1008        Ok(())
1009    }
1010
1011    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1012        self.simulate_random_delay().await;
1013
1014        let path = normalize_path(path);
1015        let parent_path = path
1016            .parent()
1017            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1018        let base_name = path.file_name().unwrap();
1019        let mut state = self.state.lock();
1020        let parent_entry = state.read_path(parent_path)?;
1021        let mut parent_entry = parent_entry.lock();
1022        let entry = parent_entry
1023            .dir_entries(parent_path)?
1024            .entry(base_name.to_str().unwrap().into());
1025        match entry {
1026            btree_map::Entry::Vacant(_) => {
1027                if !options.ignore_if_not_exists {
1028                    return Err(anyhow!("{path:?} does not exist"));
1029                }
1030            }
1031            btree_map::Entry::Occupied(e) => {
1032                e.get().lock().file_content(&path)?;
1033                e.remove();
1034            }
1035        }
1036        state.emit_event(&[path]);
1037        Ok(())
1038    }
1039
1040    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1041        let text = self.load(path).await?;
1042        Ok(Box::new(io::Cursor::new(text)))
1043    }
1044
1045    async fn load(&self, path: &Path) -> Result<String> {
1046        let path = normalize_path(path);
1047        self.simulate_random_delay().await;
1048        let state = self.state.lock();
1049        let entry = state.read_path(&path)?;
1050        let entry = entry.lock();
1051        entry.file_content(&path).cloned()
1052    }
1053
1054    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1055        self.simulate_random_delay().await;
1056        let path = normalize_path(path.as_path());
1057        self.write_file_internal(path, data.to_string())?;
1058
1059        Ok(())
1060    }
1061
1062    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1063        self.simulate_random_delay().await;
1064        let path = normalize_path(path);
1065        let content = chunks(text, line_ending).collect();
1066        self.write_file_internal(path, content)?;
1067        Ok(())
1068    }
1069
1070    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1071        let path = normalize_path(path);
1072        self.simulate_random_delay().await;
1073        let state = self.state.lock();
1074        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1075            Ok(canonical_path)
1076        } else {
1077            Err(anyhow!("path does not exist: {}", path.display()))
1078        }
1079    }
1080
1081    async fn is_file(&self, path: &Path) -> bool {
1082        let path = normalize_path(path);
1083        self.simulate_random_delay().await;
1084        let state = self.state.lock();
1085        if let Some((entry, _)) = state.try_read_path(&path, true) {
1086            entry.lock().is_file()
1087        } else {
1088            false
1089        }
1090    }
1091
1092    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1093        self.simulate_random_delay().await;
1094        let path = normalize_path(path);
1095        let state = self.state.lock();
1096        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1097            let is_symlink = entry.lock().is_symlink();
1098            if is_symlink {
1099                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1100                    entry = e;
1101                } else {
1102                    return Ok(None);
1103                }
1104            }
1105
1106            let entry = entry.lock();
1107            Ok(Some(match &*entry {
1108                FakeFsEntry::File { inode, mtime, .. } => Metadata {
1109                    inode: *inode,
1110                    mtime: *mtime,
1111                    is_dir: false,
1112                    is_symlink,
1113                },
1114                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1115                    inode: *inode,
1116                    mtime: *mtime,
1117                    is_dir: true,
1118                    is_symlink,
1119                },
1120                FakeFsEntry::Symlink { .. } => unreachable!(),
1121            }))
1122        } else {
1123            Ok(None)
1124        }
1125    }
1126
1127    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1128        self.simulate_random_delay().await;
1129        let path = normalize_path(path);
1130        let state = self.state.lock();
1131        if let Some((entry, _)) = state.try_read_path(&path, false) {
1132            let entry = entry.lock();
1133            if let FakeFsEntry::Symlink { target } = &*entry {
1134                Ok(target.clone())
1135            } else {
1136                Err(anyhow!("not a symlink: {}", path.display()))
1137            }
1138        } else {
1139            Err(anyhow!("path does not exist: {}", path.display()))
1140        }
1141    }
1142
1143    async fn read_dir(
1144        &self,
1145        path: &Path,
1146    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1147        self.simulate_random_delay().await;
1148        let path = normalize_path(path);
1149        let state = self.state.lock();
1150        let entry = state.read_path(&path)?;
1151        let mut entry = entry.lock();
1152        let children = entry.dir_entries(&path)?;
1153        let paths = children
1154            .keys()
1155            .map(|file_name| Ok(path.join(file_name)))
1156            .collect::<Vec<_>>();
1157        Ok(Box::pin(futures::stream::iter(paths)))
1158    }
1159
1160    async fn watch(
1161        &self,
1162        path: &Path,
1163        _: Duration,
1164    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
1165        self.simulate_random_delay().await;
1166        let (tx, rx) = smol::channel::unbounded();
1167        self.state.lock().event_txs.push(tx);
1168        let path = path.to_path_buf();
1169        let executor = self.executor.clone();
1170        Box::pin(futures::StreamExt::filter(rx, move |events| {
1171            let result = events.iter().any(|event| event.path.starts_with(&path));
1172            let executor = executor.clone();
1173            async move {
1174                if let Some(executor) = executor.clone().upgrade() {
1175                    executor.simulate_random_delay().await;
1176                }
1177                result
1178            }
1179        }))
1180    }
1181
1182    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
1183        let state = self.state.lock();
1184        let entry = state.read_path(abs_dot_git).unwrap();
1185        let mut entry = entry.lock();
1186        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1187            let state = git_repo_state
1188                .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
1189                .clone();
1190            Some(repository::FakeGitRepository::open(state))
1191        } else {
1192            None
1193        }
1194    }
1195
1196    fn is_fake(&self) -> bool {
1197        true
1198    }
1199
1200    #[cfg(any(test, feature = "test-support"))]
1201    fn as_fake(&self) -> &FakeFs {
1202        self
1203    }
1204}
1205
1206fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1207    rope.chunks().flat_map(move |chunk| {
1208        let mut newline = false;
1209        chunk.split('\n').flat_map(move |line| {
1210            let ending = if newline {
1211                Some(line_ending.as_str())
1212            } else {
1213                None
1214            };
1215            newline = true;
1216            ending.into_iter().chain([line])
1217        })
1218    })
1219}
1220
1221pub fn normalize_path(path: &Path) -> PathBuf {
1222    let mut components = path.components().peekable();
1223    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1224        components.next();
1225        PathBuf::from(c.as_os_str())
1226    } else {
1227        PathBuf::new()
1228    };
1229
1230    for component in components {
1231        match component {
1232            Component::Prefix(..) => unreachable!(),
1233            Component::RootDir => {
1234                ret.push(component.as_os_str());
1235            }
1236            Component::CurDir => {}
1237            Component::ParentDir => {
1238                ret.pop();
1239            }
1240            Component::Normal(c) => {
1241                ret.push(c);
1242            }
1243        }
1244    }
1245    ret
1246}
1247
1248pub fn copy_recursive<'a>(
1249    fs: &'a dyn Fs,
1250    source: &'a Path,
1251    target: &'a Path,
1252    options: CopyOptions,
1253) -> BoxFuture<'a, Result<()>> {
1254    use futures::future::FutureExt;
1255
1256    async move {
1257        let metadata = fs
1258            .metadata(source)
1259            .await?
1260            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1261        if metadata.is_dir {
1262            if !options.overwrite && fs.metadata(target).await.is_ok() {
1263                if options.ignore_if_exists {
1264                    return Ok(());
1265                } else {
1266                    return Err(anyhow!("{target:?} already exists"));
1267                }
1268            }
1269
1270            let _ = fs
1271                .remove_dir(
1272                    target,
1273                    RemoveOptions {
1274                        recursive: true,
1275                        ignore_if_not_exists: true,
1276                    },
1277                )
1278                .await;
1279            fs.create_dir(target).await?;
1280            let mut children = fs.read_dir(source).await?;
1281            while let Some(child_path) = children.next().await {
1282                if let Ok(child_path) = child_path {
1283                    if let Some(file_name) = child_path.file_name() {
1284                        let child_target_path = target.join(file_name);
1285                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1286                    }
1287                }
1288            }
1289
1290            Ok(())
1291        } else {
1292            fs.copy_file(source, target, options).await
1293        }
1294    }
1295    .boxed()
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300    use super::*;
1301    use gpui::TestAppContext;
1302    use serde_json::json;
1303
1304    #[gpui::test]
1305    async fn test_fake_fs(cx: &mut TestAppContext) {
1306        let fs = FakeFs::new(cx.background());
1307
1308        fs.insert_tree(
1309            "/root",
1310            json!({
1311                "dir1": {
1312                    "a": "A",
1313                    "b": "B"
1314                },
1315                "dir2": {
1316                    "c": "C",
1317                    "dir3": {
1318                        "d": "D"
1319                    }
1320                }
1321            }),
1322        )
1323        .await;
1324
1325        assert_eq!(
1326            fs.files(),
1327            vec![
1328                PathBuf::from("/root/dir1/a"),
1329                PathBuf::from("/root/dir1/b"),
1330                PathBuf::from("/root/dir2/c"),
1331                PathBuf::from("/root/dir2/dir3/d"),
1332            ]
1333        );
1334
1335        fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
1336            .await;
1337
1338        assert_eq!(
1339            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1340                .await
1341                .unwrap(),
1342            PathBuf::from("/root/dir2/dir3"),
1343        );
1344        assert_eq!(
1345            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1346                .await
1347                .unwrap(),
1348            PathBuf::from("/root/dir2/dir3/d"),
1349        );
1350        assert_eq!(
1351            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1352            "D",
1353        );
1354    }
1355}