fs.rs

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