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 CARRIAGE_RETURNS_REGEX: Regex = Regex::new("\r\n|\r").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) = CARRIAGE_RETURNS_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) = CARRIAGE_RETURNS_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 files(&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            let e = entry.lock().await;
 640            match &*e {
 641                FakeFsEntry::File { .. } => result.push(path),
 642                FakeFsEntry::Dir { entries, .. } => {
 643                    for (name, entry) in entries {
 644                        queue.push_back((path.join(name), entry.clone()));
 645                    }
 646                }
 647                FakeFsEntry::Symlink { .. } => {}
 648            }
 649        }
 650        result
 651    }
 652
 653    async fn simulate_random_delay(&self) {
 654        self.executor
 655            .upgrade()
 656            .expect("executor has been dropped")
 657            .simulate_random_delay()
 658            .await;
 659    }
 660}
 661
 662#[cfg(any(test, feature = "test-support"))]
 663impl FakeFsEntry {
 664    fn is_file(&self) -> bool {
 665        matches!(self, Self::File { .. })
 666    }
 667
 668    fn file_content(&self, path: &Path) -> Result<&String> {
 669        if let Self::File { content, .. } = self {
 670            Ok(content)
 671        } else {
 672            Err(anyhow!("not a file: {}", path.display()))
 673        }
 674    }
 675
 676    fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
 677        if let Self::File { content, mtime, .. } = self {
 678            *mtime = SystemTime::now();
 679            *content = new_content;
 680            Ok(())
 681        } else {
 682            Err(anyhow!("not a file: {}", path.display()))
 683        }
 684    }
 685
 686    fn dir_entries(
 687        &mut self,
 688        path: &Path,
 689    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 690        if let Self::Dir { entries, .. } = self {
 691            Ok(entries)
 692        } else {
 693            Err(anyhow!("not a directory: {}", path.display()))
 694        }
 695    }
 696}
 697
 698#[cfg(any(test, feature = "test-support"))]
 699#[async_trait::async_trait]
 700impl Fs for FakeFs {
 701    async fn create_dir(&self, path: &Path) -> Result<()> {
 702        self.simulate_random_delay().await;
 703        let mut state = self.state.lock().await;
 704
 705        let mut created_dirs = Vec::new();
 706        let mut cur_path = PathBuf::new();
 707        for component in path.components() {
 708            cur_path.push(component);
 709            if cur_path == Path::new("/") {
 710                continue;
 711            }
 712
 713            let inode = state.next_inode;
 714            state.next_inode += 1;
 715            state
 716                .write_path(&cur_path, |entry| {
 717                    entry.or_insert_with(|| {
 718                        created_dirs.push(cur_path.clone());
 719                        Arc::new(Mutex::new(FakeFsEntry::Dir {
 720                            inode,
 721                            mtime: SystemTime::now(),
 722                            entries: Default::default(),
 723                            git_repo_state: None,
 724                        }))
 725                    });
 726                    Ok(())
 727                })
 728                .await?;
 729        }
 730
 731        state.emit_event(&created_dirs);
 732        Ok(())
 733    }
 734
 735    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 736        self.simulate_random_delay().await;
 737        let mut state = self.state.lock().await;
 738        let inode = state.next_inode;
 739        state.next_inode += 1;
 740        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 741            inode,
 742            mtime: SystemTime::now(),
 743            content: String::new(),
 744        }));
 745        state
 746            .write_path(path, |entry| {
 747                match entry {
 748                    btree_map::Entry::Occupied(mut e) => {
 749                        if options.overwrite {
 750                            *e.get_mut() = file;
 751                        } else if !options.ignore_if_exists {
 752                            return Err(anyhow!("path already exists: {}", path.display()));
 753                        }
 754                    }
 755                    btree_map::Entry::Vacant(e) => {
 756                        e.insert(file);
 757                    }
 758                }
 759                Ok(())
 760            })
 761            .await?;
 762        state.emit_event(&[path]);
 763        Ok(())
 764    }
 765
 766    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
 767        let old_path = normalize_path(old_path);
 768        let new_path = normalize_path(new_path);
 769        let mut state = self.state.lock().await;
 770        let moved_entry = state
 771            .write_path(&old_path, |e| {
 772                if let btree_map::Entry::Occupied(e) = e {
 773                    Ok(e.remove())
 774                } else {
 775                    Err(anyhow!("path does not exist: {}", &old_path.display()))
 776                }
 777            })
 778            .await?;
 779        state
 780            .write_path(&new_path, |e| {
 781                match e {
 782                    btree_map::Entry::Occupied(mut e) => {
 783                        if options.overwrite {
 784                            *e.get_mut() = moved_entry;
 785                        } else if !options.ignore_if_exists {
 786                            return Err(anyhow!("path already exists: {}", new_path.display()));
 787                        }
 788                    }
 789                    btree_map::Entry::Vacant(e) => {
 790                        e.insert(moved_entry);
 791                    }
 792                }
 793                Ok(())
 794            })
 795            .await?;
 796        state.emit_event(&[old_path, new_path]);
 797        Ok(())
 798    }
 799
 800    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 801        let source = normalize_path(source);
 802        let target = normalize_path(target);
 803        let mut state = self.state.lock().await;
 804        let source_entry = state.read_path(&source).await?;
 805        let content = source_entry.lock().await.file_content(&source)?.clone();
 806        let entry = state
 807            .write_path(&target, |e| match e {
 808                btree_map::Entry::Occupied(e) => {
 809                    if options.overwrite {
 810                        Ok(Some(e.get().clone()))
 811                    } else if !options.ignore_if_exists {
 812                        return Err(anyhow!("{target:?} already exists"));
 813                    } else {
 814                        Ok(None)
 815                    }
 816                }
 817                btree_map::Entry::Vacant(e) => Ok(Some(
 818                    e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
 819                        inode: 0,
 820                        mtime: SystemTime::now(),
 821                        content: String::new(),
 822                    })))
 823                    .clone(),
 824                )),
 825            })
 826            .await?;
 827        if let Some(entry) = entry {
 828            entry.lock().await.set_file_content(&target, content)?;
 829        }
 830        state.emit_event(&[target]);
 831        Ok(())
 832    }
 833
 834    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 835        let path = normalize_path(path);
 836        let parent_path = path
 837            .parent()
 838            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 839        let base_name = path.file_name().unwrap();
 840
 841        let state = self.state.lock().await;
 842        let parent_entry = state.read_path(parent_path).await?;
 843        let mut parent_entry = parent_entry.lock().await;
 844        let entry = parent_entry
 845            .dir_entries(parent_path)?
 846            .entry(base_name.to_str().unwrap().into());
 847
 848        match entry {
 849            btree_map::Entry::Vacant(_) => {
 850                if !options.ignore_if_not_exists {
 851                    return Err(anyhow!("{path:?} does not exist"));
 852                }
 853            }
 854            btree_map::Entry::Occupied(e) => {
 855                {
 856                    let mut entry = e.get().lock().await;
 857                    let children = entry.dir_entries(&path)?;
 858                    if !options.recursive && !children.is_empty() {
 859                        return Err(anyhow!("{path:?} is not empty"));
 860                    }
 861                }
 862                e.remove();
 863            }
 864        }
 865
 866        Ok(())
 867    }
 868
 869    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 870        let path = normalize_path(path);
 871        let parent_path = path
 872            .parent()
 873            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 874        let base_name = path.file_name().unwrap();
 875        let mut state = self.state.lock().await;
 876        let parent_entry = state.read_path(parent_path).await?;
 877        let mut parent_entry = parent_entry.lock().await;
 878        let entry = parent_entry
 879            .dir_entries(parent_path)?
 880            .entry(base_name.to_str().unwrap().into());
 881        match entry {
 882            btree_map::Entry::Vacant(_) => {
 883                if !options.ignore_if_not_exists {
 884                    return Err(anyhow!("{path:?} does not exist"));
 885                }
 886            }
 887            btree_map::Entry::Occupied(e) => {
 888                e.get().lock().await.file_content(&path)?;
 889                e.remove();
 890            }
 891        }
 892        state.emit_event(&[path]);
 893        Ok(())
 894    }
 895
 896    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 897        let text = self.load(path).await?;
 898        Ok(Box::new(io::Cursor::new(text)))
 899    }
 900
 901    async fn load(&self, path: &Path) -> Result<String> {
 902        let path = normalize_path(path);
 903        self.simulate_random_delay().await;
 904        let state = self.state.lock().await;
 905        let entry = state.read_path(&path).await?;
 906        let entry = entry.lock().await;
 907        entry.file_content(&path).cloned()
 908    }
 909
 910    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 911        self.simulate_random_delay().await;
 912        let path = normalize_path(path.as_path());
 913        self.insert_file(path, data.to_string()).await;
 914
 915        Ok(())
 916    }
 917
 918    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 919        self.simulate_random_delay().await;
 920        let path = normalize_path(path);
 921        let content = chunks(text, line_ending).collect();
 922        self.insert_file(path, content).await;
 923        Ok(())
 924    }
 925
 926    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 927        let path = normalize_path(path);
 928        self.simulate_random_delay().await;
 929        let state = self.state.lock().await;
 930        if let Some((_, real_path)) = state.try_read_path(&path).await {
 931            Ok(real_path)
 932        } else {
 933            Err(anyhow!("path does not exist: {}", path.display()))
 934        }
 935    }
 936
 937    async fn is_file(&self, path: &Path) -> bool {
 938        let path = normalize_path(path);
 939        self.simulate_random_delay().await;
 940        let state = self.state.lock().await;
 941        if let Some((entry, _)) = state.try_read_path(&path).await {
 942            entry.lock().await.is_file()
 943        } else {
 944            false
 945        }
 946    }
 947
 948    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 949        self.simulate_random_delay().await;
 950        let path = normalize_path(path);
 951        let state = self.state.lock().await;
 952        if let Some((entry, real_path)) = state.try_read_path(&path).await {
 953            let entry = entry.lock().await;
 954            let is_symlink = real_path != path;
 955
 956            Ok(Some(match &*entry {
 957                FakeFsEntry::File { inode, mtime, .. } => Metadata {
 958                    inode: *inode,
 959                    mtime: *mtime,
 960                    is_dir: false,
 961                    is_symlink,
 962                },
 963                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
 964                    inode: *inode,
 965                    mtime: *mtime,
 966                    is_dir: true,
 967                    is_symlink,
 968                },
 969                FakeFsEntry::Symlink { .. } => unreachable!(),
 970            }))
 971        } else {
 972            Ok(None)
 973        }
 974    }
 975
 976    async fn read_dir(
 977        &self,
 978        path: &Path,
 979    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 980        self.simulate_random_delay().await;
 981        let path = normalize_path(path);
 982        let state = self.state.lock().await;
 983        let entry = state.read_path(&path).await?;
 984        let mut entry = entry.lock().await;
 985        let children = entry.dir_entries(&path)?;
 986        let paths = children
 987            .keys()
 988            .map(|file_name| Ok(path.join(file_name)))
 989            .collect::<Vec<_>>();
 990        Ok(Box::pin(futures::stream::iter(paths)))
 991    }
 992
 993    async fn watch(
 994        &self,
 995        path: &Path,
 996        _: Duration,
 997    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
 998        let mut state = self.state.lock().await;
 999        self.simulate_random_delay().await;
1000        let (tx, rx) = smol::channel::unbounded();
1001        state.event_txs.push(tx);
1002        let path = path.to_path_buf();
1003        let executor = self.executor.clone();
1004        Box::pin(futures::StreamExt::filter(rx, move |events| {
1005            let result = events.iter().any(|event| event.path.starts_with(&path));
1006            let executor = executor.clone();
1007            async move {
1008                if let Some(executor) = executor.clone().upgrade() {
1009                    executor.simulate_random_delay().await;
1010                }
1011                result
1012            }
1013        }))
1014    }
1015
1016    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<SyncMutex<dyn GitRepository>>> {
1017        smol::block_on(async move {
1018            let state = self.state.lock().await;
1019            let entry = state.read_path(abs_dot_git).await.unwrap();
1020            let mut entry = entry.lock().await;
1021            if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1022                let state = git_repo_state
1023                    .get_or_insert_with(|| {
1024                        Arc::new(SyncMutex::new(FakeGitRepositoryState::default()))
1025                    })
1026                    .clone();
1027                Some(repository::FakeGitRepository::open(state))
1028            } else {
1029                None
1030            }
1031        })
1032    }
1033
1034    fn is_fake(&self) -> bool {
1035        true
1036    }
1037
1038    #[cfg(any(test, feature = "test-support"))]
1039    fn as_fake(&self) -> &FakeFs {
1040        self
1041    }
1042}
1043
1044fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1045    rope.chunks().flat_map(move |chunk| {
1046        let mut newline = false;
1047        chunk.split('\n').flat_map(move |line| {
1048            let ending = if newline {
1049                Some(line_ending.as_str())
1050            } else {
1051                None
1052            };
1053            newline = true;
1054            ending.into_iter().chain([line])
1055        })
1056    })
1057}
1058
1059pub fn normalize_path(path: &Path) -> PathBuf {
1060    let mut components = path.components().peekable();
1061    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1062        components.next();
1063        PathBuf::from(c.as_os_str())
1064    } else {
1065        PathBuf::new()
1066    };
1067
1068    for component in components {
1069        match component {
1070            Component::Prefix(..) => unreachable!(),
1071            Component::RootDir => {
1072                ret.push(component.as_os_str());
1073            }
1074            Component::CurDir => {}
1075            Component::ParentDir => {
1076                ret.pop();
1077            }
1078            Component::Normal(c) => {
1079                ret.push(c);
1080            }
1081        }
1082    }
1083    ret
1084}
1085
1086pub fn copy_recursive<'a>(
1087    fs: &'a dyn Fs,
1088    source: &'a Path,
1089    target: &'a Path,
1090    options: CopyOptions,
1091) -> BoxFuture<'a, Result<()>> {
1092    use futures::future::FutureExt;
1093
1094    async move {
1095        let metadata = fs
1096            .metadata(source)
1097            .await?
1098            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1099        if metadata.is_dir {
1100            if !options.overwrite && fs.metadata(target).await.is_ok() {
1101                if options.ignore_if_exists {
1102                    return Ok(());
1103                } else {
1104                    return Err(anyhow!("{target:?} already exists"));
1105                }
1106            }
1107
1108            let _ = fs
1109                .remove_dir(
1110                    target,
1111                    RemoveOptions {
1112                        recursive: true,
1113                        ignore_if_not_exists: true,
1114                    },
1115                )
1116                .await;
1117            fs.create_dir(target).await?;
1118            let mut children = fs.read_dir(source).await?;
1119            while let Some(child_path) = children.next().await {
1120                if let Ok(child_path) = child_path {
1121                    if let Some(file_name) = child_path.file_name() {
1122                        let child_target_path = target.join(file_name);
1123                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1124                    }
1125                }
1126            }
1127
1128            Ok(())
1129        } else {
1130            fs.copy_file(source, target, options).await
1131        }
1132    }
1133    .boxed()
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138    use super::*;
1139    use gpui::TestAppContext;
1140    use serde_json::json;
1141
1142    #[gpui::test]
1143    async fn test_fake_fs(cx: &mut TestAppContext) {
1144        let fs = FakeFs::new(cx.background());
1145
1146        fs.insert_tree(
1147            "/root",
1148            json!({
1149                "dir1": {
1150                    "a": "A",
1151                    "b": "B"
1152                },
1153                "dir2": {
1154                    "c": "C",
1155                    "dir3": {
1156                        "d": "D"
1157                    }
1158                }
1159            }),
1160        )
1161        .await;
1162
1163        assert_eq!(
1164            fs.files().await,
1165            vec![
1166                PathBuf::from("/root/dir1/a"),
1167                PathBuf::from("/root/dir1/b"),
1168                PathBuf::from("/root/dir2/c"),
1169                PathBuf::from("/root/dir2/dir3/d"),
1170            ]
1171        );
1172
1173        fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
1174            .await;
1175
1176        assert_eq!(
1177            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1178                .await
1179                .unwrap(),
1180            PathBuf::from("/root/dir2/dir3"),
1181        );
1182        assert_eq!(
1183            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1184                .await
1185                .unwrap(),
1186            PathBuf::from("/root/dir2/dir3/d"),
1187        );
1188        assert_eq!(
1189            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1190            "D",
1191        );
1192    }
1193}