fs.rs

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