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