fs.rs

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