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