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