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