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