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    next_mtime: SystemTime,
 393    event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
 394}
 395
 396#[cfg(any(test, feature = "test-support"))]
 397#[derive(Debug)]
 398enum FakeFsEntry {
 399    File {
 400        inode: u64,
 401        mtime: SystemTime,
 402        content: String,
 403    },
 404    Dir {
 405        inode: u64,
 406        mtime: SystemTime,
 407        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 408        git_repo_state: Option<Arc<SyncMutex<repository::FakeGitRepositoryState>>>,
 409    },
 410    Symlink {
 411        target: PathBuf,
 412    },
 413}
 414
 415#[cfg(any(test, feature = "test-support"))]
 416impl FakeFsState {
 417    async fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 418        Ok(self
 419            .try_read_path(target)
 420            .await
 421            .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
 422            .0)
 423    }
 424
 425    async fn try_read_path<'a>(
 426        &'a self,
 427        target: &Path,
 428    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 429        let mut path = target.to_path_buf();
 430        let mut real_path = PathBuf::new();
 431        let mut entry_stack = Vec::new();
 432        'outer: loop {
 433            let mut path_components = path.components().collect::<collections::VecDeque<_>>();
 434            while let Some(component) = path_components.pop_front() {
 435                match component {
 436                    Component::Prefix(_) => panic!("prefix paths aren't supported"),
 437                    Component::RootDir => {
 438                        entry_stack.clear();
 439                        entry_stack.push(self.root.clone());
 440                        real_path.clear();
 441                        real_path.push("/");
 442                    }
 443                    Component::CurDir => {}
 444                    Component::ParentDir => {
 445                        entry_stack.pop()?;
 446                        real_path.pop();
 447                    }
 448                    Component::Normal(name) => {
 449                        let current_entry = entry_stack.last().cloned()?;
 450                        let current_entry = current_entry.lock().await;
 451                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 452                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 453                            let _entry = entry.lock().await;
 454                            if let FakeFsEntry::Symlink { target, .. } = &*_entry {
 455                                let mut target = target.clone();
 456                                target.extend(path_components);
 457                                path = target;
 458                                continue 'outer;
 459                            } else {
 460                                entry_stack.push(entry.clone());
 461                                real_path.push(name);
 462                            }
 463                        } else {
 464                            return None;
 465                        }
 466                    }
 467                }
 468            }
 469            break;
 470        }
 471        entry_stack.pop().map(|entry| (entry, real_path))
 472    }
 473
 474    async fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 475    where
 476        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 477    {
 478        let path = normalize_path(path);
 479        let filename = path
 480            .file_name()
 481            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 482        let parent_path = path.parent().unwrap();
 483
 484        let parent = self.read_path(parent_path).await?;
 485        let mut parent = parent.lock().await;
 486        let new_entry = parent
 487            .dir_entries(parent_path)?
 488            .entry(filename.to_str().unwrap().into());
 489        callback(new_entry)
 490    }
 491
 492    fn emit_event<I, T>(&mut self, paths: I)
 493    where
 494        I: IntoIterator<Item = T>,
 495        T: Into<PathBuf>,
 496    {
 497        let events = paths
 498            .into_iter()
 499            .map(|path| fsevent::Event {
 500                event_id: 0,
 501                flags: fsevent::StreamFlags::empty(),
 502                path: path.into(),
 503            })
 504            .collect::<Vec<_>>();
 505
 506        self.event_txs.retain(|tx| {
 507            let _ = tx.try_send(events.clone());
 508            !tx.is_closed()
 509        });
 510    }
 511}
 512
 513#[cfg(any(test, feature = "test-support"))]
 514impl FakeFs {
 515    pub fn new(executor: Arc<gpui::executor::Background>) -> Arc<Self> {
 516        Arc::new(Self {
 517            executor: Arc::downgrade(&executor),
 518            state: Mutex::new(FakeFsState {
 519                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 520                    inode: 0,
 521                    mtime: SystemTime::UNIX_EPOCH,
 522                    entries: Default::default(),
 523                    git_repo_state: None,
 524                })),
 525                next_mtime: SystemTime::UNIX_EPOCH,
 526                next_inode: 1,
 527                event_txs: Default::default(),
 528            }),
 529        })
 530    }
 531
 532    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
 533        let mut state = self.state.lock().await;
 534        let path = path.as_ref();
 535        let inode = state.next_inode;
 536        let mtime = state.next_mtime;
 537        state.next_inode += 1;
 538        state.next_mtime += Duration::from_nanos(1);
 539        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 540            inode,
 541            mtime,
 542            content,
 543        }));
 544        state
 545            .write_path(path, move |entry| {
 546                match entry {
 547                    btree_map::Entry::Vacant(e) => {
 548                        e.insert(file);
 549                    }
 550                    btree_map::Entry::Occupied(mut e) => {
 551                        *e.get_mut() = file;
 552                    }
 553                }
 554                Ok(())
 555            })
 556            .await
 557            .unwrap();
 558        state.emit_event(&[path]);
 559    }
 560
 561    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 562        let mut state = self.state.lock().await;
 563        let path = path.as_ref();
 564        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 565        state
 566            .write_path(path.as_ref(), move |e| match e {
 567                btree_map::Entry::Vacant(e) => {
 568                    e.insert(file);
 569                    Ok(())
 570                }
 571                btree_map::Entry::Occupied(mut e) => {
 572                    *e.get_mut() = file;
 573                    Ok(())
 574                }
 575            })
 576            .await
 577            .unwrap();
 578        state.emit_event(&[path]);
 579    }
 580
 581    #[must_use]
 582    pub fn insert_tree<'a>(
 583        &'a self,
 584        path: impl 'a + AsRef<Path> + Send,
 585        tree: serde_json::Value,
 586    ) -> futures::future::BoxFuture<'a, ()> {
 587        use futures::FutureExt as _;
 588        use serde_json::Value::*;
 589
 590        async move {
 591            let path = path.as_ref();
 592
 593            match tree {
 594                Object(map) => {
 595                    self.create_dir(path).await.unwrap();
 596                    for (name, contents) in map {
 597                        let mut path = PathBuf::from(path);
 598                        path.push(name);
 599                        self.insert_tree(&path, contents).await;
 600                    }
 601                }
 602                Null => {
 603                    self.create_dir(path).await.unwrap();
 604                }
 605                String(contents) => {
 606                    self.insert_file(&path, contents).await;
 607                }
 608                _ => {
 609                    panic!("JSON object must contain only objects, strings, or null");
 610                }
 611            }
 612        }
 613        .boxed()
 614    }
 615
 616    pub async fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
 617        let mut state = self.state.lock().await;
 618        let entry = state.read_path(dot_git).await.unwrap();
 619        let mut entry = entry.lock().await;
 620
 621        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
 622            let repo_state = git_repo_state.get_or_insert_with(Default::default);
 623            let mut repo_state = repo_state.lock();
 624
 625            repo_state.index_contents.clear();
 626            repo_state.index_contents.extend(
 627                head_state
 628                    .iter()
 629                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
 630            );
 631
 632            state.emit_event([dot_git]);
 633        } else {
 634            panic!("not a directory");
 635        }
 636    }
 637
 638    pub async fn paths(&self) -> Vec<PathBuf> {
 639        let mut result = Vec::new();
 640        let mut queue = collections::VecDeque::new();
 641        queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone()));
 642        while let Some((path, entry)) = queue.pop_front() {
 643            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock().await {
 644                for (name, entry) in entries {
 645                    queue.push_back((path.join(name), entry.clone()));
 646                }
 647            }
 648            result.push(path);
 649        }
 650        result
 651    }
 652
 653    pub async fn directories(&self) -> Vec<PathBuf> {
 654        let mut result = Vec::new();
 655        let mut queue = collections::VecDeque::new();
 656        queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone()));
 657        while let Some((path, entry)) = queue.pop_front() {
 658            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock().await {
 659                for (name, entry) in entries {
 660                    queue.push_back((path.join(name), entry.clone()));
 661                }
 662                result.push(path);
 663            }
 664        }
 665        result
 666    }
 667
 668    pub async fn files(&self) -> Vec<PathBuf> {
 669        let mut result = Vec::new();
 670        let mut queue = collections::VecDeque::new();
 671        queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone()));
 672        while let Some((path, entry)) = queue.pop_front() {
 673            let e = entry.lock().await;
 674            match &*e {
 675                FakeFsEntry::File { .. } => result.push(path),
 676                FakeFsEntry::Dir { entries, .. } => {
 677                    for (name, entry) in entries {
 678                        queue.push_back((path.join(name), entry.clone()));
 679                    }
 680                }
 681                FakeFsEntry::Symlink { .. } => {}
 682            }
 683        }
 684        result
 685    }
 686
 687    async fn simulate_random_delay(&self) {
 688        self.executor
 689            .upgrade()
 690            .expect("executor has been dropped")
 691            .simulate_random_delay()
 692            .await;
 693    }
 694}
 695
 696#[cfg(any(test, feature = "test-support"))]
 697impl FakeFsEntry {
 698    fn is_file(&self) -> bool {
 699        matches!(self, Self::File { .. })
 700    }
 701
 702    fn file_content(&self, path: &Path) -> Result<&String> {
 703        if let Self::File { content, .. } = self {
 704            Ok(content)
 705        } else {
 706            Err(anyhow!("not a file: {}", path.display()))
 707        }
 708    }
 709
 710    fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
 711        if let Self::File { content, mtime, .. } = self {
 712            *mtime = SystemTime::now();
 713            *content = new_content;
 714            Ok(())
 715        } else {
 716            Err(anyhow!("not a file: {}", path.display()))
 717        }
 718    }
 719
 720    fn dir_entries(
 721        &mut self,
 722        path: &Path,
 723    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 724        if let Self::Dir { entries, .. } = self {
 725            Ok(entries)
 726        } else {
 727            Err(anyhow!("not a directory: {}", path.display()))
 728        }
 729    }
 730}
 731
 732#[cfg(any(test, feature = "test-support"))]
 733#[async_trait::async_trait]
 734impl Fs for FakeFs {
 735    async fn create_dir(&self, path: &Path) -> Result<()> {
 736        self.simulate_random_delay().await;
 737        let mut state = self.state.lock().await;
 738
 739        let mut created_dirs = Vec::new();
 740        let mut cur_path = PathBuf::new();
 741        for component in path.components() {
 742            cur_path.push(component);
 743            if cur_path == Path::new("/") {
 744                continue;
 745            }
 746
 747            let inode = state.next_inode;
 748            let mtime = state.next_mtime;
 749            state.next_mtime += Duration::from_nanos(1);
 750            state.next_inode += 1;
 751            state
 752                .write_path(&cur_path, |entry| {
 753                    entry.or_insert_with(|| {
 754                        created_dirs.push(cur_path.clone());
 755                        Arc::new(Mutex::new(FakeFsEntry::Dir {
 756                            inode,
 757                            mtime,
 758                            entries: Default::default(),
 759                            git_repo_state: None,
 760                        }))
 761                    });
 762                    Ok(())
 763                })
 764                .await?;
 765        }
 766
 767        state.emit_event(&created_dirs);
 768        Ok(())
 769    }
 770
 771    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 772        self.simulate_random_delay().await;
 773        let mut state = self.state.lock().await;
 774        let inode = state.next_inode;
 775        let mtime = state.next_mtime;
 776        state.next_mtime += Duration::from_nanos(1);
 777        state.next_inode += 1;
 778        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 779            inode,
 780            mtime,
 781            content: String::new(),
 782        }));
 783        state
 784            .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            .await?;
 800        state.emit_event(&[path]);
 801        Ok(())
 802    }
 803
 804    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
 805        let old_path = normalize_path(old_path);
 806        let new_path = normalize_path(new_path);
 807        let mut state = self.state.lock().await;
 808        let moved_entry = state
 809            .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            .await?;
 817        state
 818            .write_path(&new_path, |e| {
 819                match e {
 820                    btree_map::Entry::Occupied(mut e) => {
 821                        if options.overwrite {
 822                            *e.get_mut() = moved_entry;
 823                        } else if !options.ignore_if_exists {
 824                            return Err(anyhow!("path already exists: {}", new_path.display()));
 825                        }
 826                    }
 827                    btree_map::Entry::Vacant(e) => {
 828                        e.insert(moved_entry);
 829                    }
 830                }
 831                Ok(())
 832            })
 833            .await?;
 834        state.emit_event(&[old_path, new_path]);
 835        Ok(())
 836    }
 837
 838    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 839        let source = normalize_path(source);
 840        let target = normalize_path(target);
 841        let mut state = self.state.lock().await;
 842        let mtime = state.next_mtime;
 843        let inode = util::post_inc(&mut state.next_inode);
 844        state.next_mtime += Duration::from_nanos(1);
 845        let source_entry = state.read_path(&source).await?;
 846        let content = source_entry.lock().await.file_content(&source)?.clone();
 847        let entry = state
 848            .write_path(&target, |e| match e {
 849                btree_map::Entry::Occupied(e) => {
 850                    if options.overwrite {
 851                        Ok(Some(e.get().clone()))
 852                    } else if !options.ignore_if_exists {
 853                        return Err(anyhow!("{target:?} already exists"));
 854                    } else {
 855                        Ok(None)
 856                    }
 857                }
 858                btree_map::Entry::Vacant(e) => Ok(Some(
 859                    e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
 860                        inode,
 861                        mtime,
 862                        content: String::new(),
 863                    })))
 864                    .clone(),
 865                )),
 866            })
 867            .await?;
 868        if let Some(entry) = entry {
 869            entry.lock().await.set_file_content(&target, content)?;
 870        }
 871        state.emit_event(&[target]);
 872        Ok(())
 873    }
 874
 875    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 876        let path = normalize_path(path);
 877        let parent_path = path
 878            .parent()
 879            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 880        let base_name = path.file_name().unwrap();
 881
 882        let state = self.state.lock().await;
 883        let parent_entry = state.read_path(parent_path).await?;
 884        let mut parent_entry = parent_entry.lock().await;
 885        let entry = parent_entry
 886            .dir_entries(parent_path)?
 887            .entry(base_name.to_str().unwrap().into());
 888
 889        match entry {
 890            btree_map::Entry::Vacant(_) => {
 891                if !options.ignore_if_not_exists {
 892                    return Err(anyhow!("{path:?} does not exist"));
 893                }
 894            }
 895            btree_map::Entry::Occupied(e) => {
 896                {
 897                    let mut entry = e.get().lock().await;
 898                    let children = entry.dir_entries(&path)?;
 899                    if !options.recursive && !children.is_empty() {
 900                        return Err(anyhow!("{path:?} is not empty"));
 901                    }
 902                }
 903                e.remove();
 904            }
 905        }
 906
 907        Ok(())
 908    }
 909
 910    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 911        let path = normalize_path(path);
 912        let parent_path = path
 913            .parent()
 914            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 915        let base_name = path.file_name().unwrap();
 916        let mut state = self.state.lock().await;
 917        let parent_entry = state.read_path(parent_path).await?;
 918        let mut parent_entry = parent_entry.lock().await;
 919        let entry = parent_entry
 920            .dir_entries(parent_path)?
 921            .entry(base_name.to_str().unwrap().into());
 922        match entry {
 923            btree_map::Entry::Vacant(_) => {
 924                if !options.ignore_if_not_exists {
 925                    return Err(anyhow!("{path:?} does not exist"));
 926                }
 927            }
 928            btree_map::Entry::Occupied(e) => {
 929                e.get().lock().await.file_content(&path)?;
 930                e.remove();
 931            }
 932        }
 933        state.emit_event(&[path]);
 934        Ok(())
 935    }
 936
 937    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 938        let text = self.load(path).await?;
 939        Ok(Box::new(io::Cursor::new(text)))
 940    }
 941
 942    async fn load(&self, path: &Path) -> Result<String> {
 943        let path = normalize_path(path);
 944        self.simulate_random_delay().await;
 945        let state = self.state.lock().await;
 946        let entry = state.read_path(&path).await?;
 947        let entry = entry.lock().await;
 948        entry.file_content(&path).cloned()
 949    }
 950
 951    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 952        self.simulate_random_delay().await;
 953        let path = normalize_path(path.as_path());
 954        self.insert_file(path, data.to_string()).await;
 955
 956        Ok(())
 957    }
 958
 959    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 960        self.simulate_random_delay().await;
 961        let path = normalize_path(path);
 962        let content = chunks(text, line_ending).collect();
 963        self.insert_file(path, content).await;
 964        Ok(())
 965    }
 966
 967    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 968        let path = normalize_path(path);
 969        self.simulate_random_delay().await;
 970        let state = self.state.lock().await;
 971        if let Some((_, real_path)) = state.try_read_path(&path).await {
 972            Ok(real_path)
 973        } else {
 974            Err(anyhow!("path does not exist: {}", path.display()))
 975        }
 976    }
 977
 978    async fn is_file(&self, path: &Path) -> bool {
 979        let path = normalize_path(path);
 980        self.simulate_random_delay().await;
 981        let state = self.state.lock().await;
 982        if let Some((entry, _)) = state.try_read_path(&path).await {
 983            entry.lock().await.is_file()
 984        } else {
 985            false
 986        }
 987    }
 988
 989    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 990        self.simulate_random_delay().await;
 991        let path = normalize_path(path);
 992        let state = self.state.lock().await;
 993        if let Some((entry, real_path)) = state.try_read_path(&path).await {
 994            let entry = entry.lock().await;
 995            let is_symlink = real_path != path;
 996
 997            Ok(Some(match &*entry {
 998                FakeFsEntry::File { inode, mtime, .. } => Metadata {
 999                    inode: *inode,
1000                    mtime: *mtime,
1001                    is_dir: false,
1002                    is_symlink,
1003                },
1004                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1005                    inode: *inode,
1006                    mtime: *mtime,
1007                    is_dir: true,
1008                    is_symlink,
1009                },
1010                FakeFsEntry::Symlink { .. } => unreachable!(),
1011            }))
1012        } else {
1013            Ok(None)
1014        }
1015    }
1016
1017    async fn read_dir(
1018        &self,
1019        path: &Path,
1020    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1021        self.simulate_random_delay().await;
1022        let path = normalize_path(path);
1023        let state = self.state.lock().await;
1024        let entry = state.read_path(&path).await?;
1025        let mut entry = entry.lock().await;
1026        let children = entry.dir_entries(&path)?;
1027        let paths = children
1028            .keys()
1029            .map(|file_name| Ok(path.join(file_name)))
1030            .collect::<Vec<_>>();
1031        Ok(Box::pin(futures::stream::iter(paths)))
1032    }
1033
1034    async fn watch(
1035        &self,
1036        path: &Path,
1037        _: Duration,
1038    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
1039        let mut state = self.state.lock().await;
1040        self.simulate_random_delay().await;
1041        let (tx, rx) = smol::channel::unbounded();
1042        state.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<SyncMutex<dyn GitRepository>>> {
1058        smol::block_on(async move {
1059            let state = self.state.lock().await;
1060            let entry = state.read_path(abs_dot_git).await.unwrap();
1061            let mut entry = entry.lock().await;
1062            if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1063                let state = git_repo_state
1064                    .get_or_insert_with(|| {
1065                        Arc::new(SyncMutex::new(FakeGitRepositoryState::default()))
1066                    })
1067                    .clone();
1068                Some(repository::FakeGitRepository::open(state))
1069            } else {
1070                None
1071            }
1072        })
1073    }
1074
1075    fn is_fake(&self) -> bool {
1076        true
1077    }
1078
1079    #[cfg(any(test, feature = "test-support"))]
1080    fn as_fake(&self) -> &FakeFs {
1081        self
1082    }
1083}
1084
1085fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1086    rope.chunks().flat_map(move |chunk| {
1087        let mut newline = false;
1088        chunk.split('\n').flat_map(move |line| {
1089            let ending = if newline {
1090                Some(line_ending.as_str())
1091            } else {
1092                None
1093            };
1094            newline = true;
1095            ending.into_iter().chain([line])
1096        })
1097    })
1098}
1099
1100pub fn normalize_path(path: &Path) -> PathBuf {
1101    let mut components = path.components().peekable();
1102    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1103        components.next();
1104        PathBuf::from(c.as_os_str())
1105    } else {
1106        PathBuf::new()
1107    };
1108
1109    for component in components {
1110        match component {
1111            Component::Prefix(..) => unreachable!(),
1112            Component::RootDir => {
1113                ret.push(component.as_os_str());
1114            }
1115            Component::CurDir => {}
1116            Component::ParentDir => {
1117                ret.pop();
1118            }
1119            Component::Normal(c) => {
1120                ret.push(c);
1121            }
1122        }
1123    }
1124    ret
1125}
1126
1127pub fn copy_recursive<'a>(
1128    fs: &'a dyn Fs,
1129    source: &'a Path,
1130    target: &'a Path,
1131    options: CopyOptions,
1132) -> BoxFuture<'a, Result<()>> {
1133    use futures::future::FutureExt;
1134
1135    async move {
1136        let metadata = fs
1137            .metadata(source)
1138            .await?
1139            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1140        if metadata.is_dir {
1141            if !options.overwrite && fs.metadata(target).await.is_ok() {
1142                if options.ignore_if_exists {
1143                    return Ok(());
1144                } else {
1145                    return Err(anyhow!("{target:?} already exists"));
1146                }
1147            }
1148
1149            let _ = fs
1150                .remove_dir(
1151                    target,
1152                    RemoveOptions {
1153                        recursive: true,
1154                        ignore_if_not_exists: true,
1155                    },
1156                )
1157                .await;
1158            fs.create_dir(target).await?;
1159            let mut children = fs.read_dir(source).await?;
1160            while let Some(child_path) = children.next().await {
1161                if let Ok(child_path) = child_path {
1162                    if let Some(file_name) = child_path.file_name() {
1163                        let child_target_path = target.join(file_name);
1164                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1165                    }
1166                }
1167            }
1168
1169            Ok(())
1170        } else {
1171            fs.copy_file(source, target, options).await
1172        }
1173    }
1174    .boxed()
1175}
1176
1177#[cfg(test)]
1178mod tests {
1179    use super::*;
1180    use gpui::TestAppContext;
1181    use serde_json::json;
1182
1183    #[gpui::test]
1184    async fn test_fake_fs(cx: &mut TestAppContext) {
1185        let fs = FakeFs::new(cx.background());
1186
1187        fs.insert_tree(
1188            "/root",
1189            json!({
1190                "dir1": {
1191                    "a": "A",
1192                    "b": "B"
1193                },
1194                "dir2": {
1195                    "c": "C",
1196                    "dir3": {
1197                        "d": "D"
1198                    }
1199                }
1200            }),
1201        )
1202        .await;
1203
1204        assert_eq!(
1205            fs.files().await,
1206            vec![
1207                PathBuf::from("/root/dir1/a"),
1208                PathBuf::from("/root/dir1/b"),
1209                PathBuf::from("/root/dir2/c"),
1210                PathBuf::from("/root/dir2/dir3/d"),
1211            ]
1212        );
1213
1214        fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
1215            .await;
1216
1217        assert_eq!(
1218            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1219                .await
1220                .unwrap(),
1221            PathBuf::from("/root/dir2/dir3"),
1222        );
1223        assert_eq!(
1224            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1225                .await
1226                .unwrap(),
1227            PathBuf::from("/root/dir2/dir3/d"),
1228        );
1229        assert_eq!(
1230            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1231            "D",
1232        );
1233    }
1234}