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().len.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::thread::spawn(move || {
 230            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
 231        });
 232        Box::pin(rx.chain(futures::stream::once(async move {
 233            drop(handle);
 234            vec![]
 235        })))
 236    }
 237
 238    fn is_fake(&self) -> bool {
 239        false
 240    }
 241    #[cfg(any(test, feature = "test-support"))]
 242    fn as_fake(&self) -> &FakeFs {
 243        panic!("called `RealFs::as_fake`")
 244    }
 245}
 246
 247#[cfg(any(test, feature = "test-support"))]
 248pub struct FakeFs {
 249    // Use an unfair lock to ensure tests are deterministic.
 250    state: Mutex<FakeFsState>,
 251    executor: Weak<gpui::executor::Background>,
 252}
 253
 254#[cfg(any(test, feature = "test-support"))]
 255struct FakeFsState {
 256    root: Arc<Mutex<FakeFsEntry>>,
 257    next_inode: u64,
 258    event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
 259}
 260
 261#[cfg(any(test, feature = "test-support"))]
 262#[derive(Debug)]
 263enum FakeFsEntry {
 264    File {
 265        inode: u64,
 266        mtime: SystemTime,
 267        content: String,
 268    },
 269    Dir {
 270        inode: u64,
 271        mtime: SystemTime,
 272        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 273    },
 274    Symlink {
 275        target: PathBuf,
 276    },
 277}
 278
 279#[cfg(any(test, feature = "test-support"))]
 280impl FakeFsState {
 281    async fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 282        Ok(self
 283            .try_read_path(target)
 284            .await
 285            .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
 286            .0)
 287    }
 288
 289    async fn try_read_path<'a>(
 290        &'a self,
 291        target: &Path,
 292    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 293        let mut path = target.to_path_buf();
 294        let mut real_path = PathBuf::new();
 295        let mut entry_stack = Vec::new();
 296        'outer: loop {
 297            let mut path_components = path.components().collect::<collections::VecDeque<_>>();
 298            while let Some(component) = path_components.pop_front() {
 299                match component {
 300                    Component::Prefix(_) => panic!("prefix paths aren't supported"),
 301                    Component::RootDir => {
 302                        entry_stack.clear();
 303                        entry_stack.push(self.root.clone());
 304                        real_path.clear();
 305                        real_path.push("/");
 306                    }
 307                    Component::CurDir => {}
 308                    Component::ParentDir => {
 309                        entry_stack.pop()?;
 310                        real_path.pop();
 311                    }
 312                    Component::Normal(name) => {
 313                        let current_entry = entry_stack.last().cloned()?;
 314                        let current_entry = current_entry.lock().await;
 315                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 316                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 317                            let _entry = entry.lock().await;
 318                            if let FakeFsEntry::Symlink { target, .. } = &*_entry {
 319                                let mut target = target.clone();
 320                                target.extend(path_components);
 321                                path = target;
 322                                continue 'outer;
 323                            } else {
 324                                entry_stack.push(entry.clone());
 325                                real_path.push(name);
 326                            }
 327                        } else {
 328                            return None;
 329                        }
 330                    }
 331                }
 332            }
 333            break;
 334        }
 335        entry_stack.pop().map(|entry| (entry, real_path))
 336    }
 337
 338    async fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 339    where
 340        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 341    {
 342        let path = normalize_path(path);
 343        let filename = path
 344            .file_name()
 345            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 346        let parent_path = path.parent().unwrap();
 347
 348        let parent = self.read_path(parent_path).await?;
 349        let mut parent = parent.lock().await;
 350        let new_entry = parent
 351            .dir_entries(parent_path)?
 352            .entry(filename.to_str().unwrap().into());
 353        callback(new_entry)
 354    }
 355
 356    fn emit_event<I, T>(&mut self, paths: I)
 357    where
 358        I: IntoIterator<Item = T>,
 359        T: Into<PathBuf>,
 360    {
 361        let events = paths
 362            .into_iter()
 363            .map(|path| fsevent::Event {
 364                event_id: 0,
 365                flags: fsevent::StreamFlags::empty(),
 366                path: path.into(),
 367            })
 368            .collect::<Vec<_>>();
 369
 370        self.event_txs.retain(|tx| {
 371            let _ = tx.try_send(events.clone());
 372            !tx.is_closed()
 373        });
 374    }
 375}
 376
 377#[cfg(any(test, feature = "test-support"))]
 378impl FakeFs {
 379    pub fn new(executor: Arc<gpui::executor::Background>) -> Arc<Self> {
 380        Arc::new(Self {
 381            executor: Arc::downgrade(&executor),
 382            state: Mutex::new(FakeFsState {
 383                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 384                    inode: 0,
 385                    mtime: SystemTime::now(),
 386                    entries: Default::default(),
 387                })),
 388                next_inode: 1,
 389                event_txs: Default::default(),
 390            }),
 391        })
 392    }
 393
 394    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
 395        let mut state = self.state.lock().await;
 396        let path = path.as_ref();
 397        let inode = state.next_inode;
 398        state.next_inode += 1;
 399        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 400            inode,
 401            mtime: SystemTime::now(),
 402            content,
 403        }));
 404        state
 405            .write_path(path, move |entry| {
 406                match entry {
 407                    btree_map::Entry::Vacant(e) => {
 408                        e.insert(file);
 409                    }
 410                    btree_map::Entry::Occupied(mut e) => {
 411                        *e.get_mut() = file;
 412                    }
 413                }
 414                Ok(())
 415            })
 416            .await
 417            .unwrap();
 418        state.emit_event(&[path]);
 419    }
 420
 421    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 422        let mut state = self.state.lock().await;
 423        let path = path.as_ref();
 424        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 425        state
 426            .write_path(path.as_ref(), move |e| match e {
 427                btree_map::Entry::Vacant(e) => {
 428                    e.insert(file);
 429                    Ok(())
 430                }
 431                btree_map::Entry::Occupied(mut e) => {
 432                    *e.get_mut() = file;
 433                    Ok(())
 434                }
 435            })
 436            .await
 437            .unwrap();
 438        state.emit_event(&[path]);
 439    }
 440
 441    #[must_use]
 442    pub fn insert_tree<'a>(
 443        &'a self,
 444        path: impl 'a + AsRef<Path> + Send,
 445        tree: serde_json::Value,
 446    ) -> futures::future::BoxFuture<'a, ()> {
 447        use futures::FutureExt as _;
 448        use serde_json::Value::*;
 449
 450        async move {
 451            let path = path.as_ref();
 452
 453            match tree {
 454                Object(map) => {
 455                    self.create_dir(path).await.unwrap();
 456                    for (name, contents) in map {
 457                        let mut path = PathBuf::from(path);
 458                        path.push(name);
 459                        self.insert_tree(&path, contents).await;
 460                    }
 461                }
 462                Null => {
 463                    self.create_dir(path).await.unwrap();
 464                }
 465                String(contents) => {
 466                    self.insert_file(&path, contents).await;
 467                }
 468                _ => {
 469                    panic!("JSON object must contain only objects, strings, or null");
 470                }
 471            }
 472        }
 473        .boxed()
 474    }
 475
 476    pub async fn files(&self) -> Vec<PathBuf> {
 477        let mut result = Vec::new();
 478        let mut queue = collections::VecDeque::new();
 479        queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone()));
 480        while let Some((path, entry)) = queue.pop_front() {
 481            let e = entry.lock().await;
 482            match &*e {
 483                FakeFsEntry::File { .. } => result.push(path),
 484                FakeFsEntry::Dir { entries, .. } => {
 485                    for (name, entry) in entries {
 486                        queue.push_back((path.join(name), entry.clone()));
 487                    }
 488                }
 489                FakeFsEntry::Symlink { .. } => {}
 490            }
 491        }
 492        result
 493    }
 494
 495    async fn simulate_random_delay(&self) {
 496        self.executor
 497            .upgrade()
 498            .expect("executor has been dropped")
 499            .simulate_random_delay()
 500            .await;
 501    }
 502}
 503
 504#[cfg(any(test, feature = "test-support"))]
 505impl FakeFsEntry {
 506    fn is_file(&self) -> bool {
 507        matches!(self, Self::File { .. })
 508    }
 509
 510    fn file_content(&self, path: &Path) -> Result<&String> {
 511        if let Self::File { content, .. } = self {
 512            Ok(content)
 513        } else {
 514            Err(anyhow!("not a file: {}", path.display()))
 515        }
 516    }
 517
 518    fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
 519        if let Self::File { content, mtime, .. } = self {
 520            *mtime = SystemTime::now();
 521            *content = new_content;
 522            Ok(())
 523        } else {
 524            Err(anyhow!("not a file: {}", path.display()))
 525        }
 526    }
 527
 528    fn dir_entries(
 529        &mut self,
 530        path: &Path,
 531    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 532        if let Self::Dir { entries, .. } = self {
 533            Ok(entries)
 534        } else {
 535            Err(anyhow!("not a directory: {}", path.display()))
 536        }
 537    }
 538}
 539
 540#[cfg(any(test, feature = "test-support"))]
 541#[async_trait::async_trait]
 542impl Fs for FakeFs {
 543    async fn create_dir(&self, path: &Path) -> Result<()> {
 544        self.simulate_random_delay().await;
 545        let mut state = self.state.lock().await;
 546
 547        let mut created_dirs = Vec::new();
 548        let mut cur_path = PathBuf::new();
 549        for component in path.components() {
 550            cur_path.push(component);
 551            if cur_path == Path::new("/") {
 552                continue;
 553            }
 554
 555            let inode = state.next_inode;
 556            state.next_inode += 1;
 557            state
 558                .write_path(&cur_path, |entry| {
 559                    entry.or_insert_with(|| {
 560                        created_dirs.push(cur_path.clone());
 561                        Arc::new(Mutex::new(FakeFsEntry::Dir {
 562                            inode,
 563                            mtime: SystemTime::now(),
 564                            entries: Default::default(),
 565                        }))
 566                    });
 567                    Ok(())
 568                })
 569                .await?;
 570        }
 571
 572        state.emit_event(&created_dirs);
 573        Ok(())
 574    }
 575
 576    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 577        self.simulate_random_delay().await;
 578        let mut state = self.state.lock().await;
 579        let inode = state.next_inode;
 580        state.next_inode += 1;
 581        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 582            inode,
 583            mtime: SystemTime::now(),
 584            content: String::new(),
 585        }));
 586        state
 587            .write_path(path, |entry| {
 588                match entry {
 589                    btree_map::Entry::Occupied(mut e) => {
 590                        if options.overwrite {
 591                            *e.get_mut() = file;
 592                        } else if !options.ignore_if_exists {
 593                            return Err(anyhow!("path already exists: {}", path.display()));
 594                        }
 595                    }
 596                    btree_map::Entry::Vacant(e) => {
 597                        e.insert(file);
 598                    }
 599                }
 600                Ok(())
 601            })
 602            .await?;
 603        state.emit_event(&[path]);
 604        Ok(())
 605    }
 606
 607    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
 608        let old_path = normalize_path(old_path);
 609        let new_path = normalize_path(new_path);
 610        let mut state = self.state.lock().await;
 611        let moved_entry = state
 612            .write_path(&old_path, |e| {
 613                if let btree_map::Entry::Occupied(e) = e {
 614                    Ok(e.remove())
 615                } else {
 616                    Err(anyhow!("path does not exist: {}", &old_path.display()))
 617                }
 618            })
 619            .await?;
 620        state
 621            .write_path(&new_path, |e| {
 622                match e {
 623                    btree_map::Entry::Occupied(mut e) => {
 624                        if options.overwrite {
 625                            *e.get_mut() = moved_entry;
 626                        } else if !options.ignore_if_exists {
 627                            return Err(anyhow!("path already exists: {}", new_path.display()));
 628                        }
 629                    }
 630                    btree_map::Entry::Vacant(e) => {
 631                        e.insert(moved_entry);
 632                    }
 633                }
 634                Ok(())
 635            })
 636            .await?;
 637        state.emit_event(&[old_path, new_path]);
 638        Ok(())
 639    }
 640
 641    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 642        let source = normalize_path(source);
 643        let target = normalize_path(target);
 644        let mut state = self.state.lock().await;
 645        let source_entry = state.read_path(&source).await?;
 646        let content = source_entry.lock().await.file_content(&source)?.clone();
 647        let entry = state
 648            .write_path(&target, |e| match e {
 649                btree_map::Entry::Occupied(e) => {
 650                    if options.overwrite {
 651                        Ok(Some(e.get().clone()))
 652                    } else if !options.ignore_if_exists {
 653                        return Err(anyhow!("{target:?} already exists"));
 654                    } else {
 655                        Ok(None)
 656                    }
 657                }
 658                btree_map::Entry::Vacant(e) => Ok(Some(
 659                    e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
 660                        inode: 0,
 661                        mtime: SystemTime::now(),
 662                        content: String::new(),
 663                    })))
 664                    .clone(),
 665                )),
 666            })
 667            .await?;
 668        if let Some(entry) = entry {
 669            entry.lock().await.set_file_content(&target, content)?;
 670        }
 671        state.emit_event(&[target]);
 672        Ok(())
 673    }
 674
 675    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 676        let path = normalize_path(path);
 677        let parent_path = path
 678            .parent()
 679            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 680        let base_name = path.file_name().unwrap();
 681
 682        let state = self.state.lock().await;
 683        let parent_entry = state.read_path(parent_path).await?;
 684        let mut parent_entry = parent_entry.lock().await;
 685        let entry = parent_entry
 686            .dir_entries(parent_path)?
 687            .entry(base_name.to_str().unwrap().into());
 688
 689        match entry {
 690            btree_map::Entry::Vacant(_) => {
 691                if !options.ignore_if_not_exists {
 692                    return Err(anyhow!("{path:?} does not exist"));
 693                }
 694            }
 695            btree_map::Entry::Occupied(e) => {
 696                {
 697                    let mut entry = e.get().lock().await;
 698                    let children = entry.dir_entries(&path)?;
 699                    if !options.recursive && !children.is_empty() {
 700                        return Err(anyhow!("{path:?} is not empty"));
 701                    }
 702                }
 703                e.remove();
 704            }
 705        }
 706
 707        Ok(())
 708    }
 709
 710    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 711        let path = normalize_path(path);
 712        let parent_path = path
 713            .parent()
 714            .ok_or_else(|| anyhow!("cannot remove the root"))?;
 715        let base_name = path.file_name().unwrap();
 716        let mut state = self.state.lock().await;
 717        let parent_entry = state.read_path(parent_path).await?;
 718        let mut parent_entry = parent_entry.lock().await;
 719        let entry = parent_entry
 720            .dir_entries(parent_path)?
 721            .entry(base_name.to_str().unwrap().into());
 722        match entry {
 723            btree_map::Entry::Vacant(_) => {
 724                if !options.ignore_if_not_exists {
 725                    return Err(anyhow!("{path:?} does not exist"));
 726                }
 727            }
 728            btree_map::Entry::Occupied(e) => {
 729                e.get().lock().await.file_content(&path)?;
 730                e.remove();
 731            }
 732        }
 733        state.emit_event(&[path]);
 734        Ok(())
 735    }
 736
 737    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 738        let text = self.load(path).await?;
 739        Ok(Box::new(io::Cursor::new(text)))
 740    }
 741
 742    async fn load(&self, path: &Path) -> Result<String> {
 743        let path = normalize_path(path);
 744        self.simulate_random_delay().await;
 745        let state = self.state.lock().await;
 746        let entry = state.read_path(&path).await?;
 747        let entry = entry.lock().await;
 748        entry.file_content(&path).cloned()
 749    }
 750
 751    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 752        self.simulate_random_delay().await;
 753        let path = normalize_path(path);
 754        let content = chunks(text, line_ending).collect();
 755        self.insert_file(path, content).await;
 756        Ok(())
 757    }
 758
 759    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 760        let path = normalize_path(path);
 761        self.simulate_random_delay().await;
 762        let state = self.state.lock().await;
 763        if let Some((_, real_path)) = state.try_read_path(&path).await {
 764            Ok(real_path)
 765        } else {
 766            Err(anyhow!("path does not exist: {}", path.display()))
 767        }
 768    }
 769
 770    async fn is_file(&self, path: &Path) -> bool {
 771        let path = normalize_path(path);
 772        self.simulate_random_delay().await;
 773        let state = self.state.lock().await;
 774        if let Some((entry, _)) = state.try_read_path(&path).await {
 775            entry.lock().await.is_file()
 776        } else {
 777            false
 778        }
 779    }
 780
 781    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 782        self.simulate_random_delay().await;
 783        let path = normalize_path(path);
 784        let state = self.state.lock().await;
 785        if let Some((entry, real_path)) = state.try_read_path(&path).await {
 786            let entry = entry.lock().await;
 787            let is_symlink = real_path != path;
 788
 789            Ok(Some(match &*entry {
 790                FakeFsEntry::File { inode, mtime, .. } => Metadata {
 791                    inode: *inode,
 792                    mtime: *mtime,
 793                    is_dir: false,
 794                    is_symlink,
 795                },
 796                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
 797                    inode: *inode,
 798                    mtime: *mtime,
 799                    is_dir: true,
 800                    is_symlink,
 801                },
 802                FakeFsEntry::Symlink { .. } => unreachable!(),
 803            }))
 804        } else {
 805            Ok(None)
 806        }
 807    }
 808
 809    async fn read_dir(
 810        &self,
 811        path: &Path,
 812    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 813        self.simulate_random_delay().await;
 814        let path = normalize_path(path);
 815        let state = self.state.lock().await;
 816        let entry = state.read_path(&path).await?;
 817        let mut entry = entry.lock().await;
 818        let children = entry.dir_entries(&path)?;
 819        let paths = children
 820            .keys()
 821            .map(|file_name| Ok(path.join(file_name)))
 822            .collect::<Vec<_>>();
 823        Ok(Box::pin(futures::stream::iter(paths)))
 824    }
 825
 826    async fn watch(
 827        &self,
 828        path: &Path,
 829        _: Duration,
 830    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
 831        let mut state = self.state.lock().await;
 832        self.simulate_random_delay().await;
 833        let (tx, rx) = smol::channel::unbounded();
 834        state.event_txs.push(tx);
 835        let path = path.to_path_buf();
 836        let executor = self.executor.clone();
 837        Box::pin(futures::StreamExt::filter(rx, move |events| {
 838            let result = events.iter().any(|event| event.path.starts_with(&path));
 839            let executor = executor.clone();
 840            async move {
 841                if let Some(executor) = executor.clone().upgrade() {
 842                    executor.simulate_random_delay().await;
 843                }
 844                result
 845            }
 846        }))
 847    }
 848
 849    fn is_fake(&self) -> bool {
 850        true
 851    }
 852
 853    #[cfg(any(test, feature = "test-support"))]
 854    fn as_fake(&self) -> &FakeFs {
 855        self
 856    }
 857}
 858
 859fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
 860    rope.chunks().flat_map(move |chunk| {
 861        let mut newline = false;
 862        chunk.split('\n').flat_map(move |line| {
 863            let ending = if newline {
 864                Some(line_ending.as_str())
 865            } else {
 866                None
 867            };
 868            newline = true;
 869            ending.into_iter().chain([line])
 870        })
 871    })
 872}
 873
 874pub fn normalize_path(path: &Path) -> PathBuf {
 875    let mut components = path.components().peekable();
 876    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
 877        components.next();
 878        PathBuf::from(c.as_os_str())
 879    } else {
 880        PathBuf::new()
 881    };
 882
 883    for component in components {
 884        match component {
 885            Component::Prefix(..) => unreachable!(),
 886            Component::RootDir => {
 887                ret.push(component.as_os_str());
 888            }
 889            Component::CurDir => {}
 890            Component::ParentDir => {
 891                ret.pop();
 892            }
 893            Component::Normal(c) => {
 894                ret.push(c);
 895            }
 896        }
 897    }
 898    ret
 899}
 900
 901pub fn copy_recursive<'a>(
 902    fs: &'a dyn Fs,
 903    source: &'a Path,
 904    target: &'a Path,
 905    options: CopyOptions,
 906) -> BoxFuture<'a, Result<()>> {
 907    use futures::future::FutureExt;
 908
 909    async move {
 910        let metadata = fs
 911            .metadata(source)
 912            .await?
 913            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
 914        if metadata.is_dir {
 915            if !options.overwrite && fs.metadata(target).await.is_ok() {
 916                if options.ignore_if_exists {
 917                    return Ok(());
 918                } else {
 919                    return Err(anyhow!("{target:?} already exists"));
 920                }
 921            }
 922
 923            let _ = fs
 924                .remove_dir(
 925                    target,
 926                    RemoveOptions {
 927                        recursive: true,
 928                        ignore_if_not_exists: true,
 929                    },
 930                )
 931                .await;
 932            fs.create_dir(target).await?;
 933            let mut children = fs.read_dir(source).await?;
 934            while let Some(child_path) = children.next().await {
 935                if let Ok(child_path) = child_path {
 936                    if let Some(file_name) = child_path.file_name() {
 937                        let child_target_path = target.join(file_name);
 938                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
 939                    }
 940                }
 941            }
 942
 943            Ok(())
 944        } else {
 945            fs.copy_file(source, target, options).await
 946        }
 947    }
 948    .boxed()
 949}
 950
 951#[cfg(test)]
 952mod tests {
 953    use super::*;
 954    use gpui::TestAppContext;
 955    use serde_json::json;
 956
 957    #[gpui::test]
 958    async fn test_fake_fs(cx: &mut TestAppContext) {
 959        let fs = FakeFs::new(cx.background());
 960
 961        fs.insert_tree(
 962            "/root",
 963            json!({
 964                "dir1": {
 965                    "a": "A",
 966                    "b": "B"
 967                },
 968                "dir2": {
 969                    "c": "C",
 970                    "dir3": {
 971                        "d": "D"
 972                    }
 973                }
 974            }),
 975        )
 976        .await;
 977
 978        assert_eq!(
 979            fs.files().await,
 980            vec![
 981                PathBuf::from("/root/dir1/a"),
 982                PathBuf::from("/root/dir1/b"),
 983                PathBuf::from("/root/dir2/c"),
 984                PathBuf::from("/root/dir2/dir3/d"),
 985            ]
 986        );
 987
 988        fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
 989            .await;
 990
 991        assert_eq!(
 992            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
 993                .await
 994                .unwrap(),
 995            PathBuf::from("/root/dir2/dir3"),
 996        );
 997        assert_eq!(
 998            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
 999                .await
1000                .unwrap(),
1001            PathBuf::from("/root/dir2/dir3/d"),
1002        );
1003        assert_eq!(
1004            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1005            "D",
1006        );
1007    }
1008}