fs.rs

   1pub mod repository;
   2
   3use anyhow::{anyhow, Result};
   4pub use fsevent::Event;
   5#[cfg(target_os = "macos")]
   6use fsevent::EventStream;
   7
   8#[cfg(not(target_os = "macos"))]
   9use fsevent::StreamFlags;
  10
  11#[cfg(not(target_os = "macos"))]
  12use notify::{Config, EventKind, Watcher};
  13
  14#[cfg(unix)]
  15use std::os::unix::fs::MetadataExt;
  16
  17use futures::{future::BoxFuture, Stream, StreamExt};
  18use git2::Repository as LibGitRepository;
  19use parking_lot::Mutex;
  20use repository::GitRepository;
  21use rope::Rope;
  22use smol::io::{AsyncReadExt, AsyncWriteExt};
  23use std::io::Write;
  24use std::sync::Arc;
  25use std::{
  26    io,
  27    path::{Component, Path, PathBuf},
  28    pin::Pin,
  29    time::{Duration, SystemTime},
  30};
  31use tempfile::{NamedTempFile, TempDir};
  32use text::LineEnding;
  33use util::ResultExt;
  34
  35#[cfg(any(test, feature = "test-support"))]
  36use collections::{btree_map, BTreeMap};
  37#[cfg(any(test, feature = "test-support"))]
  38use repository::{FakeGitRepositoryState, GitFileStatus};
  39#[cfg(any(test, feature = "test-support"))]
  40use std::ffi::OsStr;
  41
  42#[async_trait::async_trait]
  43pub trait Fs: Send + Sync {
  44    async fn create_dir(&self, path: &Path) -> Result<()>;
  45    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
  46    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
  47    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
  48    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  49    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
  50    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>>;
  51    async fn load(&self, path: &Path) -> Result<String>;
  52    async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
  53    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
  54    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
  55    async fn is_file(&self, path: &Path) -> bool;
  56    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
  57    async fn read_link(&self, path: &Path) -> Result<PathBuf>;
  58    async fn read_dir(
  59        &self,
  60        path: &Path,
  61    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
  62
  63    async fn watch(
  64        &self,
  65        path: &Path,
  66        latency: Duration,
  67    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>>;
  68
  69    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>>;
  70    fn is_fake(&self) -> bool;
  71    async fn is_case_sensitive(&self) -> Result<bool>;
  72    #[cfg(any(test, feature = "test-support"))]
  73    fn as_fake(&self) -> &FakeFs;
  74}
  75
  76#[derive(Copy, Clone, Default)]
  77pub struct CreateOptions {
  78    pub overwrite: bool,
  79    pub ignore_if_exists: bool,
  80}
  81
  82#[derive(Copy, Clone, Default)]
  83pub struct CopyOptions {
  84    pub overwrite: bool,
  85    pub ignore_if_exists: bool,
  86}
  87
  88#[derive(Copy, Clone, Default)]
  89pub struct RenameOptions {
  90    pub overwrite: bool,
  91    pub ignore_if_exists: bool,
  92}
  93
  94#[derive(Copy, Clone, Default)]
  95pub struct RemoveOptions {
  96    pub recursive: bool,
  97    pub ignore_if_not_exists: bool,
  98}
  99
 100#[derive(Copy, Clone, Debug)]
 101pub struct Metadata {
 102    pub inode: u64,
 103    pub mtime: SystemTime,
 104    pub is_symlink: bool,
 105    pub is_dir: bool,
 106}
 107
 108pub struct RealFs;
 109
 110#[async_trait::async_trait]
 111impl Fs for RealFs {
 112    async fn create_dir(&self, path: &Path) -> Result<()> {
 113        Ok(smol::fs::create_dir_all(path).await?)
 114    }
 115
 116    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 117        let mut open_options = smol::fs::OpenOptions::new();
 118        open_options.write(true).create(true);
 119        if options.overwrite {
 120            open_options.truncate(true);
 121        } else if !options.ignore_if_exists {
 122            open_options.create_new(true);
 123        }
 124        open_options.open(path).await?;
 125        Ok(())
 126    }
 127
 128    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 129        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 130            if options.ignore_if_exists {
 131                return Ok(());
 132            } else {
 133                return Err(anyhow!("{target:?} already exists"));
 134            }
 135        }
 136
 137        smol::fs::copy(source, target).await?;
 138        Ok(())
 139    }
 140
 141    async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
 142        if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
 143            if options.ignore_if_exists {
 144                return Ok(());
 145            } else {
 146                return Err(anyhow!("{target:?} already exists"));
 147            }
 148        }
 149
 150        smol::fs::rename(source, target).await?;
 151        Ok(())
 152    }
 153
 154    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 155        let result = if options.recursive {
 156            smol::fs::remove_dir_all(path).await
 157        } else {
 158            smol::fs::remove_dir(path).await
 159        };
 160        match result {
 161            Ok(()) => Ok(()),
 162            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 163                Ok(())
 164            }
 165            Err(err) => Err(err)?,
 166        }
 167    }
 168
 169    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
 170        match smol::fs::remove_file(path).await {
 171            Ok(()) => Ok(()),
 172            Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
 173                Ok(())
 174            }
 175            Err(err) => Err(err)?,
 176        }
 177    }
 178
 179    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
 180        Ok(Box::new(std::fs::File::open(path)?))
 181    }
 182
 183    async fn load(&self, path: &Path) -> Result<String> {
 184        let mut file = smol::fs::File::open(path).await?;
 185        let mut text = String::new();
 186        file.read_to_string(&mut text).await?;
 187        Ok(text)
 188    }
 189
 190    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
 191        smol::unblock(move || {
 192            let mut tmp_file = NamedTempFile::new()?;
 193            tmp_file.write_all(data.as_bytes())?;
 194            tmp_file.persist(path)?;
 195            Ok::<(), anyhow::Error>(())
 196        })
 197        .await?;
 198
 199        Ok(())
 200    }
 201
 202    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
 203        let buffer_size = text.summary().len.min(10 * 1024);
 204        if let Some(path) = path.parent() {
 205            self.create_dir(path).await?;
 206        }
 207        let file = smol::fs::File::create(path).await?;
 208        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 209        for chunk in chunks(text, line_ending) {
 210            writer.write_all(chunk.as_bytes()).await?;
 211        }
 212        writer.flush().await?;
 213        Ok(())
 214    }
 215
 216    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 217        Ok(smol::fs::canonicalize(path).await?)
 218    }
 219
 220    async fn is_file(&self, path: &Path) -> bool {
 221        smol::fs::metadata(path)
 222            .await
 223            .map_or(false, |metadata| metadata.is_file())
 224    }
 225
 226    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
 227        let symlink_metadata = match smol::fs::symlink_metadata(path).await {
 228            Ok(metadata) => metadata,
 229            Err(err) => {
 230                return match (err.kind(), err.raw_os_error()) {
 231                    (io::ErrorKind::NotFound, _) => Ok(None),
 232                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 233                    _ => Err(anyhow::Error::new(err)),
 234                }
 235            }
 236        };
 237
 238        let is_symlink = symlink_metadata.file_type().is_symlink();
 239        let metadata = if is_symlink {
 240            smol::fs::metadata(path).await?
 241        } else {
 242            symlink_metadata
 243        };
 244
 245        #[cfg(unix)]
 246        let inode = metadata.ino();
 247
 248        // todo!("windows")
 249        #[cfg(windows)]
 250        let inode = 0;
 251
 252        Ok(Some(Metadata {
 253            inode,
 254            mtime: metadata.modified().unwrap(),
 255            is_symlink,
 256            is_dir: metadata.file_type().is_dir(),
 257        }))
 258    }
 259
 260    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
 261        let path = smol::fs::read_link(path).await?;
 262        Ok(path)
 263    }
 264
 265    async fn read_dir(
 266        &self,
 267        path: &Path,
 268    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
 269        let result = smol::fs::read_dir(path).await?.map(|entry| match entry {
 270            Ok(entry) => Ok(entry.path()),
 271            Err(error) => Err(anyhow!("failed to read dir entry {:?}", error)),
 272        });
 273        Ok(Box::pin(result))
 274    }
 275
 276    #[cfg(target_os = "macos")]
 277    async fn watch(
 278        &self,
 279        path: &Path,
 280        latency: Duration,
 281    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
 282        let (tx, rx) = smol::channel::unbounded();
 283        let (stream, handle) = EventStream::new(&[path], latency);
 284        std::thread::spawn(move || {
 285            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
 286        });
 287        Box::pin(rx.chain(futures::stream::once(async move {
 288            drop(handle);
 289            vec![]
 290        })))
 291    }
 292
 293    #[cfg(not(target_os = "macos"))]
 294    async fn watch(
 295        &self,
 296        path: &Path,
 297        latency: Duration,
 298    ) -> Pin<Box<dyn Send + Stream<Item = Vec<Event>>>> {
 299        let (tx, rx) = smol::channel::unbounded();
 300
 301        if !path.exists() {
 302            log::error!("watch path does not exist: {}", path.display());
 303            return Box::pin(rx);
 304        }
 305
 306        let mut watcher =
 307            notify::recommended_watcher(move |res: Result<notify::Event, _>| match res {
 308                Ok(event) => {
 309                    let flags = match event.kind {
 310                        // ITEM_REMOVED is currently the only flag we care about
 311                        EventKind::Remove(_) => StreamFlags::ITEM_REMOVED,
 312                        _ => StreamFlags::NONE,
 313                    };
 314                    let events = event
 315                        .paths
 316                        .into_iter()
 317                        .map(|path| Event {
 318                            event_id: 0,
 319                            flags,
 320                            path,
 321                        })
 322                        .collect::<Vec<_>>();
 323                    let _ = tx.try_send(events);
 324                }
 325                Err(err) => {
 326                    log::error!("watch error: {}", err);
 327                }
 328            })
 329            .unwrap();
 330
 331        watcher
 332            .configure(Config::default().with_poll_interval(latency))
 333            .unwrap();
 334
 335        watcher
 336            .watch(path, notify::RecursiveMode::Recursive)
 337            .unwrap();
 338
 339        Box::pin(rx)
 340    }
 341
 342    fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
 343        LibGitRepository::open(&dotgit_path)
 344            .log_err()
 345            .and_then::<Arc<Mutex<dyn GitRepository>>, _>(|libgit_repository| {
 346                Some(Arc::new(Mutex::new(libgit_repository)))
 347            })
 348    }
 349
 350    fn is_fake(&self) -> bool {
 351        false
 352    }
 353
 354    /// Checks whether the file system is case sensitive by attempting to create two files
 355    /// that have the same name except for the casing.
 356    ///
 357    /// It creates both files in a temporary directory it removes at the end.
 358    async fn is_case_sensitive(&self) -> Result<bool> {
 359        let temp_dir = TempDir::new()?;
 360        let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
 361        let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
 362
 363        let create_opts = CreateOptions {
 364            overwrite: false,
 365            ignore_if_exists: false,
 366        };
 367
 368        // Create file1
 369        self.create_file(&test_file_1, create_opts).await?;
 370
 371        // Now check whether it's possible to create file2
 372        let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
 373            Ok(_) => Ok(true),
 374            Err(e) => {
 375                if let Some(io_error) = e.downcast_ref::<io::Error>() {
 376                    if io_error.kind() == io::ErrorKind::AlreadyExists {
 377                        Ok(false)
 378                    } else {
 379                        Err(e)
 380                    }
 381                } else {
 382                    Err(e)
 383                }
 384            }
 385        };
 386
 387        temp_dir.close()?;
 388        case_sensitive
 389    }
 390
 391    #[cfg(any(test, feature = "test-support"))]
 392    fn as_fake(&self) -> &FakeFs {
 393        panic!("called `RealFs::as_fake`")
 394    }
 395}
 396
 397pub fn fs_events_paths(events: Vec<Event>) -> Vec<PathBuf> {
 398    events.into_iter().map(|event| event.path).collect()
 399}
 400
 401#[cfg(any(test, feature = "test-support"))]
 402pub struct FakeFs {
 403    // Use an unfair lock to ensure tests are deterministic.
 404    state: Mutex<FakeFsState>,
 405    executor: gpui::BackgroundExecutor,
 406}
 407
 408#[cfg(any(test, feature = "test-support"))]
 409struct FakeFsState {
 410    root: Arc<Mutex<FakeFsEntry>>,
 411    next_inode: u64,
 412    next_mtime: SystemTime,
 413    event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
 414    events_paused: bool,
 415    buffered_events: Vec<fsevent::Event>,
 416    metadata_call_count: usize,
 417    read_dir_call_count: usize,
 418}
 419
 420#[cfg(any(test, feature = "test-support"))]
 421#[derive(Debug)]
 422enum FakeFsEntry {
 423    File {
 424        inode: u64,
 425        mtime: SystemTime,
 426        content: String,
 427    },
 428    Dir {
 429        inode: u64,
 430        mtime: SystemTime,
 431        entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
 432        git_repo_state: Option<Arc<Mutex<repository::FakeGitRepositoryState>>>,
 433    },
 434    Symlink {
 435        target: PathBuf,
 436    },
 437}
 438
 439#[cfg(any(test, feature = "test-support"))]
 440impl FakeFsState {
 441    fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
 442        Ok(self
 443            .try_read_path(target, true)
 444            .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
 445            .0)
 446    }
 447
 448    fn try_read_path<'a>(
 449        &'a self,
 450        target: &Path,
 451        follow_symlink: bool,
 452    ) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
 453        let mut path = target.to_path_buf();
 454        let mut canonical_path = PathBuf::new();
 455        let mut entry_stack = Vec::new();
 456        'outer: loop {
 457            let mut path_components = path.components().peekable();
 458            while let Some(component) = path_components.next() {
 459                match component {
 460                    Component::Prefix(_) => panic!("prefix paths aren't supported"),
 461                    Component::RootDir => {
 462                        entry_stack.clear();
 463                        entry_stack.push(self.root.clone());
 464                        canonical_path.clear();
 465                        canonical_path.push("/");
 466                    }
 467                    Component::CurDir => {}
 468                    Component::ParentDir => {
 469                        entry_stack.pop()?;
 470                        canonical_path.pop();
 471                    }
 472                    Component::Normal(name) => {
 473                        let current_entry = entry_stack.last().cloned()?;
 474                        let current_entry = current_entry.lock();
 475                        if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
 476                            let entry = entries.get(name.to_str().unwrap()).cloned()?;
 477                            if path_components.peek().is_some() || follow_symlink {
 478                                let entry = entry.lock();
 479                                if let FakeFsEntry::Symlink { target, .. } = &*entry {
 480                                    let mut target = target.clone();
 481                                    target.extend(path_components);
 482                                    path = target;
 483                                    continue 'outer;
 484                                }
 485                            }
 486                            entry_stack.push(entry.clone());
 487                            canonical_path.push(name);
 488                        } else {
 489                            return None;
 490                        }
 491                    }
 492                }
 493            }
 494            break;
 495        }
 496        Some((entry_stack.pop()?, canonical_path))
 497    }
 498
 499    fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
 500    where
 501        Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
 502    {
 503        let path = normalize_path(path);
 504        let filename = path
 505            .file_name()
 506            .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
 507        let parent_path = path.parent().unwrap();
 508
 509        let parent = self.read_path(parent_path)?;
 510        let mut parent = parent.lock();
 511        let new_entry = parent
 512            .dir_entries(parent_path)?
 513            .entry(filename.to_str().unwrap().into());
 514        callback(new_entry)
 515    }
 516
 517    fn emit_event<I, T>(&mut self, paths: I)
 518    where
 519        I: IntoIterator<Item = T>,
 520        T: Into<PathBuf>,
 521    {
 522        self.buffered_events
 523            .extend(paths.into_iter().map(|path| fsevent::Event {
 524                event_id: 0,
 525                flags: fsevent::StreamFlags::empty(),
 526                path: path.into(),
 527            }));
 528
 529        if !self.events_paused {
 530            self.flush_events(self.buffered_events.len());
 531        }
 532    }
 533
 534    fn flush_events(&mut self, mut count: usize) {
 535        count = count.min(self.buffered_events.len());
 536        let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
 537        self.event_txs.retain(|tx| {
 538            let _ = tx.try_send(events.clone());
 539            !tx.is_closed()
 540        });
 541    }
 542}
 543
 544#[cfg(any(test, feature = "test-support"))]
 545lazy_static::lazy_static! {
 546    pub static ref FS_DOT_GIT: &'static OsStr = OsStr::new(".git");
 547}
 548
 549#[cfg(any(test, feature = "test-support"))]
 550impl FakeFs {
 551    pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
 552        Arc::new(Self {
 553            executor,
 554            state: Mutex::new(FakeFsState {
 555                root: Arc::new(Mutex::new(FakeFsEntry::Dir {
 556                    inode: 0,
 557                    mtime: SystemTime::UNIX_EPOCH,
 558                    entries: Default::default(),
 559                    git_repo_state: None,
 560                })),
 561                next_mtime: SystemTime::UNIX_EPOCH,
 562                next_inode: 1,
 563                event_txs: Default::default(),
 564                buffered_events: Vec::new(),
 565                events_paused: false,
 566                read_dir_call_count: 0,
 567                metadata_call_count: 0,
 568            }),
 569        })
 570    }
 571
 572    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
 573        self.write_file_internal(path, content).unwrap()
 574    }
 575
 576    pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
 577        let mut state = self.state.lock();
 578        let path = path.as_ref();
 579        let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
 580        state
 581            .write_path(path.as_ref(), move |e| match e {
 582                btree_map::Entry::Vacant(e) => {
 583                    e.insert(file);
 584                    Ok(())
 585                }
 586                btree_map::Entry::Occupied(mut e) => {
 587                    *e.get_mut() = file;
 588                    Ok(())
 589                }
 590            })
 591            .unwrap();
 592        state.emit_event(&[path]);
 593    }
 594
 595    pub fn write_file_internal(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
 596        let mut state = self.state.lock();
 597        let path = path.as_ref();
 598        let inode = state.next_inode;
 599        let mtime = state.next_mtime;
 600        state.next_inode += 1;
 601        state.next_mtime += Duration::from_nanos(1);
 602        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 603            inode,
 604            mtime,
 605            content,
 606        }));
 607        state.write_path(path, move |entry| {
 608            match entry {
 609                btree_map::Entry::Vacant(e) => {
 610                    e.insert(file);
 611                }
 612                btree_map::Entry::Occupied(mut e) => {
 613                    *e.get_mut() = file;
 614                }
 615            }
 616            Ok(())
 617        })?;
 618        state.emit_event(&[path]);
 619        Ok(())
 620    }
 621
 622    pub fn pause_events(&self) {
 623        self.state.lock().events_paused = true;
 624    }
 625
 626    pub fn buffered_event_count(&self) -> usize {
 627        self.state.lock().buffered_events.len()
 628    }
 629
 630    pub fn flush_events(&self, count: usize) {
 631        self.state.lock().flush_events(count);
 632    }
 633
 634    #[must_use]
 635    pub fn insert_tree<'a>(
 636        &'a self,
 637        path: impl 'a + AsRef<Path> + Send,
 638        tree: serde_json::Value,
 639    ) -> futures::future::BoxFuture<'a, ()> {
 640        use futures::FutureExt as _;
 641        use serde_json::Value::*;
 642
 643        async move {
 644            let path = path.as_ref();
 645
 646            match tree {
 647                Object(map) => {
 648                    self.create_dir(path).await.unwrap();
 649                    for (name, contents) in map {
 650                        let mut path = PathBuf::from(path);
 651                        path.push(name);
 652                        self.insert_tree(&path, contents).await;
 653                    }
 654                }
 655                Null => {
 656                    self.create_dir(path).await.unwrap();
 657                }
 658                String(contents) => {
 659                    self.insert_file(&path, contents).await;
 660                }
 661                _ => {
 662                    panic!("JSON object must contain only objects, strings, or null");
 663                }
 664            }
 665        }
 666        .boxed()
 667    }
 668
 669    pub fn with_git_state<F>(&self, dot_git: &Path, emit_git_event: bool, f: F)
 670    where
 671        F: FnOnce(&mut FakeGitRepositoryState),
 672    {
 673        let mut state = self.state.lock();
 674        let entry = state.read_path(dot_git).unwrap();
 675        let mut entry = entry.lock();
 676
 677        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
 678            let repo_state = git_repo_state.get_or_insert_with(Default::default);
 679            let mut repo_state = repo_state.lock();
 680
 681            f(&mut repo_state);
 682
 683            if emit_git_event {
 684                state.emit_event([dot_git]);
 685            }
 686        } else {
 687            panic!("not a directory");
 688        }
 689    }
 690
 691    pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
 692        self.with_git_state(dot_git, true, |state| {
 693            state.branch_name = branch.map(Into::into)
 694        })
 695    }
 696
 697    pub fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
 698        self.with_git_state(dot_git, true, |state| {
 699            state.index_contents.clear();
 700            state.index_contents.extend(
 701                head_state
 702                    .iter()
 703                    .map(|(path, content)| (path.to_path_buf(), content.clone())),
 704            );
 705        });
 706    }
 707
 708    pub fn set_status_for_repo_via_working_copy_change(
 709        &self,
 710        dot_git: &Path,
 711        statuses: &[(&Path, GitFileStatus)],
 712    ) {
 713        self.with_git_state(dot_git, false, |state| {
 714            state.worktree_statuses.clear();
 715            state.worktree_statuses.extend(
 716                statuses
 717                    .iter()
 718                    .map(|(path, content)| ((**path).into(), content.clone())),
 719            );
 720        });
 721        self.state.lock().emit_event(
 722            statuses
 723                .iter()
 724                .map(|(path, _)| dot_git.parent().unwrap().join(path)),
 725        );
 726    }
 727
 728    pub fn set_status_for_repo_via_git_operation(
 729        &self,
 730        dot_git: &Path,
 731        statuses: &[(&Path, GitFileStatus)],
 732    ) {
 733        self.with_git_state(dot_git, true, |state| {
 734            state.worktree_statuses.clear();
 735            state.worktree_statuses.extend(
 736                statuses
 737                    .iter()
 738                    .map(|(path, content)| ((**path).into(), content.clone())),
 739            );
 740        });
 741    }
 742
 743    pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
 744        let mut result = Vec::new();
 745        let mut queue = collections::VecDeque::new();
 746        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 747        while let Some((path, entry)) = queue.pop_front() {
 748            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 749                for (name, entry) in entries {
 750                    queue.push_back((path.join(name), entry.clone()));
 751                }
 752            }
 753            if include_dot_git
 754                || !path
 755                    .components()
 756                    .any(|component| component.as_os_str() == *FS_DOT_GIT)
 757            {
 758                result.push(path);
 759            }
 760        }
 761        result
 762    }
 763
 764    pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
 765        let mut result = Vec::new();
 766        let mut queue = collections::VecDeque::new();
 767        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 768        while let Some((path, entry)) = queue.pop_front() {
 769            if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
 770                for (name, entry) in entries {
 771                    queue.push_back((path.join(name), entry.clone()));
 772                }
 773                if include_dot_git
 774                    || !path
 775                        .components()
 776                        .any(|component| component.as_os_str() == *FS_DOT_GIT)
 777                {
 778                    result.push(path);
 779                }
 780            }
 781        }
 782        result
 783    }
 784
 785    pub fn files(&self) -> Vec<PathBuf> {
 786        let mut result = Vec::new();
 787        let mut queue = collections::VecDeque::new();
 788        queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
 789        while let Some((path, entry)) = queue.pop_front() {
 790            let e = entry.lock();
 791            match &*e {
 792                FakeFsEntry::File { .. } => result.push(path),
 793                FakeFsEntry::Dir { entries, .. } => {
 794                    for (name, entry) in entries {
 795                        queue.push_back((path.join(name), entry.clone()));
 796                    }
 797                }
 798                FakeFsEntry::Symlink { .. } => {}
 799            }
 800        }
 801        result
 802    }
 803
 804    /// How many `read_dir` calls have been issued.
 805    pub fn read_dir_call_count(&self) -> usize {
 806        self.state.lock().read_dir_call_count
 807    }
 808
 809    /// How many `metadata` calls have been issued.
 810    pub fn metadata_call_count(&self) -> usize {
 811        self.state.lock().metadata_call_count
 812    }
 813
 814    fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
 815        self.executor.simulate_random_delay()
 816    }
 817}
 818
 819#[cfg(any(test, feature = "test-support"))]
 820impl FakeFsEntry {
 821    fn is_file(&self) -> bool {
 822        matches!(self, Self::File { .. })
 823    }
 824
 825    fn is_symlink(&self) -> bool {
 826        matches!(self, Self::Symlink { .. })
 827    }
 828
 829    fn file_content(&self, path: &Path) -> Result<&String> {
 830        if let Self::File { content, .. } = self {
 831            Ok(content)
 832        } else {
 833            Err(anyhow!("not a file: {}", path.display()))
 834        }
 835    }
 836
 837    fn set_file_content(&mut self, path: &Path, new_content: String) -> Result<()> {
 838        if let Self::File { content, mtime, .. } = self {
 839            *mtime = SystemTime::now();
 840            *content = new_content;
 841            Ok(())
 842        } else {
 843            Err(anyhow!("not a file: {}", path.display()))
 844        }
 845    }
 846
 847    fn dir_entries(
 848        &mut self,
 849        path: &Path,
 850    ) -> Result<&mut BTreeMap<String, Arc<Mutex<FakeFsEntry>>>> {
 851        if let Self::Dir { entries, .. } = self {
 852            Ok(entries)
 853        } else {
 854            Err(anyhow!("not a directory: {}", path.display()))
 855        }
 856    }
 857}
 858
 859#[cfg(any(test, feature = "test-support"))]
 860#[async_trait::async_trait]
 861impl Fs for FakeFs {
 862    async fn create_dir(&self, path: &Path) -> Result<()> {
 863        self.simulate_random_delay().await;
 864
 865        let mut created_dirs = Vec::new();
 866        let mut cur_path = PathBuf::new();
 867        for component in path.components() {
 868            let mut state = self.state.lock();
 869            cur_path.push(component);
 870            if cur_path == Path::new("/") {
 871                continue;
 872            }
 873
 874            let inode = state.next_inode;
 875            let mtime = state.next_mtime;
 876            state.next_mtime += Duration::from_nanos(1);
 877            state.next_inode += 1;
 878            state.write_path(&cur_path, |entry| {
 879                entry.or_insert_with(|| {
 880                    created_dirs.push(cur_path.clone());
 881                    Arc::new(Mutex::new(FakeFsEntry::Dir {
 882                        inode,
 883                        mtime,
 884                        entries: Default::default(),
 885                        git_repo_state: None,
 886                    }))
 887                });
 888                Ok(())
 889            })?
 890        }
 891
 892        self.state.lock().emit_event(&created_dirs);
 893        Ok(())
 894    }
 895
 896    async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
 897        self.simulate_random_delay().await;
 898        let mut state = self.state.lock();
 899        let inode = state.next_inode;
 900        let mtime = state.next_mtime;
 901        state.next_mtime += Duration::from_nanos(1);
 902        state.next_inode += 1;
 903        let file = Arc::new(Mutex::new(FakeFsEntry::File {
 904            inode,
 905            mtime,
 906            content: String::new(),
 907        }));
 908        state.write_path(path, |entry| {
 909            match entry {
 910                btree_map::Entry::Occupied(mut e) => {
 911                    if options.overwrite {
 912                        *e.get_mut() = file;
 913                    } else if !options.ignore_if_exists {
 914                        return Err(anyhow!("path already exists: {}", path.display()));
 915                    }
 916                }
 917                btree_map::Entry::Vacant(e) => {
 918                    e.insert(file);
 919                }
 920            }
 921            Ok(())
 922        })?;
 923        state.emit_event(&[path]);
 924        Ok(())
 925    }
 926
 927    async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
 928        self.simulate_random_delay().await;
 929
 930        let old_path = normalize_path(old_path);
 931        let new_path = normalize_path(new_path);
 932
 933        let mut state = self.state.lock();
 934        let moved_entry = state.write_path(&old_path, |e| {
 935            if let btree_map::Entry::Occupied(e) = e {
 936                Ok(e.get().clone())
 937            } else {
 938                Err(anyhow!("path does not exist: {}", &old_path.display()))
 939            }
 940        })?;
 941
 942        state.write_path(&new_path, |e| {
 943            match e {
 944                btree_map::Entry::Occupied(mut e) => {
 945                    if options.overwrite {
 946                        *e.get_mut() = moved_entry;
 947                    } else if !options.ignore_if_exists {
 948                        return Err(anyhow!("path already exists: {}", new_path.display()));
 949                    }
 950                }
 951                btree_map::Entry::Vacant(e) => {
 952                    e.insert(moved_entry);
 953                }
 954            }
 955            Ok(())
 956        })?;
 957
 958        state
 959            .write_path(&old_path, |e| {
 960                if let btree_map::Entry::Occupied(e) = e {
 961                    Ok(e.remove())
 962                } else {
 963                    unreachable!()
 964                }
 965            })
 966            .unwrap();
 967
 968        state.emit_event(&[old_path, new_path]);
 969        Ok(())
 970    }
 971
 972    async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
 973        self.simulate_random_delay().await;
 974
 975        let source = normalize_path(source);
 976        let target = normalize_path(target);
 977        let mut state = self.state.lock();
 978        let mtime = state.next_mtime;
 979        let inode = util::post_inc(&mut state.next_inode);
 980        state.next_mtime += Duration::from_nanos(1);
 981        let source_entry = state.read_path(&source)?;
 982        let content = source_entry.lock().file_content(&source)?.clone();
 983        let entry = state.write_path(&target, |e| match e {
 984            btree_map::Entry::Occupied(e) => {
 985                if options.overwrite {
 986                    Ok(Some(e.get().clone()))
 987                } else if !options.ignore_if_exists {
 988                    return Err(anyhow!("{target:?} already exists"));
 989                } else {
 990                    Ok(None)
 991                }
 992            }
 993            btree_map::Entry::Vacant(e) => Ok(Some(
 994                e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
 995                    inode,
 996                    mtime,
 997                    content: String::new(),
 998                })))
 999                .clone(),
1000            )),
1001        })?;
1002        if let Some(entry) = entry {
1003            entry.lock().set_file_content(&target, content)?;
1004        }
1005        state.emit_event(&[target]);
1006        Ok(())
1007    }
1008
1009    async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1010        self.simulate_random_delay().await;
1011
1012        let path = normalize_path(path);
1013        let parent_path = path
1014            .parent()
1015            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1016        let base_name = path.file_name().unwrap();
1017
1018        let mut state = self.state.lock();
1019        let parent_entry = state.read_path(parent_path)?;
1020        let mut parent_entry = parent_entry.lock();
1021        let entry = parent_entry
1022            .dir_entries(parent_path)?
1023            .entry(base_name.to_str().unwrap().into());
1024
1025        match entry {
1026            btree_map::Entry::Vacant(_) => {
1027                if !options.ignore_if_not_exists {
1028                    return Err(anyhow!("{path:?} does not exist"));
1029                }
1030            }
1031            btree_map::Entry::Occupied(e) => {
1032                {
1033                    let mut entry = e.get().lock();
1034                    let children = entry.dir_entries(&path)?;
1035                    if !options.recursive && !children.is_empty() {
1036                        return Err(anyhow!("{path:?} is not empty"));
1037                    }
1038                }
1039                e.remove();
1040            }
1041        }
1042        state.emit_event(&[path]);
1043        Ok(())
1044    }
1045
1046    async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
1047        self.simulate_random_delay().await;
1048
1049        let path = normalize_path(path);
1050        let parent_path = path
1051            .parent()
1052            .ok_or_else(|| anyhow!("cannot remove the root"))?;
1053        let base_name = path.file_name().unwrap();
1054        let mut state = self.state.lock();
1055        let parent_entry = state.read_path(parent_path)?;
1056        let mut parent_entry = parent_entry.lock();
1057        let entry = parent_entry
1058            .dir_entries(parent_path)?
1059            .entry(base_name.to_str().unwrap().into());
1060        match entry {
1061            btree_map::Entry::Vacant(_) => {
1062                if !options.ignore_if_not_exists {
1063                    return Err(anyhow!("{path:?} does not exist"));
1064                }
1065            }
1066            btree_map::Entry::Occupied(e) => {
1067                e.get().lock().file_content(&path)?;
1068                e.remove();
1069            }
1070        }
1071        state.emit_event(&[path]);
1072        Ok(())
1073    }
1074
1075    async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read>> {
1076        let text = self.load(path).await?;
1077        Ok(Box::new(io::Cursor::new(text)))
1078    }
1079
1080    async fn load(&self, path: &Path) -> Result<String> {
1081        let path = normalize_path(path);
1082        self.simulate_random_delay().await;
1083        let state = self.state.lock();
1084        let entry = state.read_path(&path)?;
1085        let entry = entry.lock();
1086        entry.file_content(&path).cloned()
1087    }
1088
1089    async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
1090        self.simulate_random_delay().await;
1091        let path = normalize_path(path.as_path());
1092        self.write_file_internal(path, data.to_string())?;
1093
1094        Ok(())
1095    }
1096
1097    async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
1098        self.simulate_random_delay().await;
1099        let path = normalize_path(path);
1100        let content = chunks(text, line_ending).collect();
1101        if let Some(path) = path.parent() {
1102            self.create_dir(path).await?;
1103        }
1104        self.write_file_internal(path, content)?;
1105        Ok(())
1106    }
1107
1108    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
1109        let path = normalize_path(path);
1110        self.simulate_random_delay().await;
1111        let state = self.state.lock();
1112        if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
1113            Ok(canonical_path)
1114        } else {
1115            Err(anyhow!("path does not exist: {}", path.display()))
1116        }
1117    }
1118
1119    async fn is_file(&self, path: &Path) -> bool {
1120        let path = normalize_path(path);
1121        self.simulate_random_delay().await;
1122        let state = self.state.lock();
1123        if let Some((entry, _)) = state.try_read_path(&path, true) {
1124            entry.lock().is_file()
1125        } else {
1126            false
1127        }
1128    }
1129
1130    async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
1131        self.simulate_random_delay().await;
1132        let path = normalize_path(path);
1133        let mut state = self.state.lock();
1134        state.metadata_call_count += 1;
1135        if let Some((mut entry, _)) = state.try_read_path(&path, false) {
1136            let is_symlink = entry.lock().is_symlink();
1137            if is_symlink {
1138                if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
1139                    entry = e;
1140                } else {
1141                    return Ok(None);
1142                }
1143            }
1144
1145            let entry = entry.lock();
1146            Ok(Some(match &*entry {
1147                FakeFsEntry::File { inode, mtime, .. } => Metadata {
1148                    inode: *inode,
1149                    mtime: *mtime,
1150                    is_dir: false,
1151                    is_symlink,
1152                },
1153                FakeFsEntry::Dir { inode, mtime, .. } => Metadata {
1154                    inode: *inode,
1155                    mtime: *mtime,
1156                    is_dir: true,
1157                    is_symlink,
1158                },
1159                FakeFsEntry::Symlink { .. } => unreachable!(),
1160            }))
1161        } else {
1162            Ok(None)
1163        }
1164    }
1165
1166    async fn read_link(&self, path: &Path) -> Result<PathBuf> {
1167        self.simulate_random_delay().await;
1168        let path = normalize_path(path);
1169        let state = self.state.lock();
1170        if let Some((entry, _)) = state.try_read_path(&path, false) {
1171            let entry = entry.lock();
1172            if let FakeFsEntry::Symlink { target } = &*entry {
1173                Ok(target.clone())
1174            } else {
1175                Err(anyhow!("not a symlink: {}", path.display()))
1176            }
1177        } else {
1178            Err(anyhow!("path does not exist: {}", path.display()))
1179        }
1180    }
1181
1182    async fn read_dir(
1183        &self,
1184        path: &Path,
1185    ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
1186        self.simulate_random_delay().await;
1187        let path = normalize_path(path);
1188        let mut state = self.state.lock();
1189        state.read_dir_call_count += 1;
1190        let entry = state.read_path(&path)?;
1191        let mut entry = entry.lock();
1192        let children = entry.dir_entries(&path)?;
1193        let paths = children
1194            .keys()
1195            .map(|file_name| Ok(path.join(file_name)))
1196            .collect::<Vec<_>>();
1197        Ok(Box::pin(futures::stream::iter(paths)))
1198    }
1199
1200    async fn watch(
1201        &self,
1202        path: &Path,
1203        _: Duration,
1204    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
1205        self.simulate_random_delay().await;
1206        let (tx, rx) = smol::channel::unbounded();
1207        self.state.lock().event_txs.push(tx);
1208        let path = path.to_path_buf();
1209        let executor = self.executor.clone();
1210        Box::pin(futures::StreamExt::filter(rx, move |events| {
1211            let result = events.iter().any(|event| event.path.starts_with(&path));
1212            let executor = executor.clone();
1213            async move {
1214                executor.simulate_random_delay().await;
1215                result
1216            }
1217        }))
1218    }
1219
1220    fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
1221        let state = self.state.lock();
1222        let entry = state.read_path(abs_dot_git).unwrap();
1223        let mut entry = entry.lock();
1224        if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
1225            let state = git_repo_state
1226                .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
1227                .clone();
1228            Some(repository::FakeGitRepository::open(state))
1229        } else {
1230            None
1231        }
1232    }
1233
1234    fn is_fake(&self) -> bool {
1235        true
1236    }
1237
1238    async fn is_case_sensitive(&self) -> Result<bool> {
1239        Ok(true)
1240    }
1241
1242    #[cfg(any(test, feature = "test-support"))]
1243    fn as_fake(&self) -> &FakeFs {
1244        self
1245    }
1246}
1247
1248fn chunks(rope: &Rope, line_ending: LineEnding) -> impl Iterator<Item = &str> {
1249    rope.chunks().flat_map(move |chunk| {
1250        let mut newline = false;
1251        chunk.split('\n').flat_map(move |line| {
1252            let ending = if newline {
1253                Some(line_ending.as_str())
1254            } else {
1255                None
1256            };
1257            newline = true;
1258            ending.into_iter().chain([line])
1259        })
1260    })
1261}
1262
1263pub fn normalize_path(path: &Path) -> PathBuf {
1264    let mut components = path.components().peekable();
1265    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
1266        components.next();
1267        PathBuf::from(c.as_os_str())
1268    } else {
1269        PathBuf::new()
1270    };
1271
1272    for component in components {
1273        match component {
1274            Component::Prefix(..) => unreachable!(),
1275            Component::RootDir => {
1276                ret.push(component.as_os_str());
1277            }
1278            Component::CurDir => {}
1279            Component::ParentDir => {
1280                ret.pop();
1281            }
1282            Component::Normal(c) => {
1283                ret.push(c);
1284            }
1285        }
1286    }
1287    ret
1288}
1289
1290pub fn copy_recursive<'a>(
1291    fs: &'a dyn Fs,
1292    source: &'a Path,
1293    target: &'a Path,
1294    options: CopyOptions,
1295) -> BoxFuture<'a, Result<()>> {
1296    use futures::future::FutureExt;
1297
1298    async move {
1299        let metadata = fs
1300            .metadata(source)
1301            .await?
1302            .ok_or_else(|| anyhow!("path does not exist: {}", source.display()))?;
1303        if metadata.is_dir {
1304            if !options.overwrite && fs.metadata(target).await.is_ok_and(|m| m.is_some()) {
1305                if options.ignore_if_exists {
1306                    return Ok(());
1307                } else {
1308                    return Err(anyhow!("{target:?} already exists"));
1309                }
1310            }
1311
1312            let _ = fs
1313                .remove_dir(
1314                    target,
1315                    RemoveOptions {
1316                        recursive: true,
1317                        ignore_if_not_exists: true,
1318                    },
1319                )
1320                .await;
1321            fs.create_dir(target).await?;
1322            let mut children = fs.read_dir(source).await?;
1323            while let Some(child_path) = children.next().await {
1324                if let Ok(child_path) = child_path {
1325                    if let Some(file_name) = child_path.file_name() {
1326                        let child_target_path = target.join(file_name);
1327                        copy_recursive(fs, &child_path, &child_target_path, options).await?;
1328                    }
1329                }
1330            }
1331
1332            Ok(())
1333        } else {
1334            fs.copy_file(source, target, options).await
1335        }
1336    }
1337    .boxed()
1338}
1339
1340#[cfg(test)]
1341mod tests {
1342    use super::*;
1343    use gpui::BackgroundExecutor;
1344    use serde_json::json;
1345
1346    #[gpui::test]
1347    async fn test_fake_fs(executor: BackgroundExecutor) {
1348        let fs = FakeFs::new(executor.clone());
1349        fs.insert_tree(
1350            "/root",
1351            json!({
1352                "dir1": {
1353                    "a": "A",
1354                    "b": "B"
1355                },
1356                "dir2": {
1357                    "c": "C",
1358                    "dir3": {
1359                        "d": "D"
1360                    }
1361                }
1362            }),
1363        )
1364        .await;
1365
1366        assert_eq!(
1367            fs.files(),
1368            vec![
1369                PathBuf::from("/root/dir1/a"),
1370                PathBuf::from("/root/dir1/b"),
1371                PathBuf::from("/root/dir2/c"),
1372                PathBuf::from("/root/dir2/dir3/d"),
1373            ]
1374        );
1375
1376        fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
1377            .await;
1378
1379        assert_eq!(
1380            fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
1381                .await
1382                .unwrap(),
1383            PathBuf::from("/root/dir2/dir3"),
1384        );
1385        assert_eq!(
1386            fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
1387                .await
1388                .unwrap(),
1389            PathBuf::from("/root/dir2/dir3/d"),
1390        );
1391        assert_eq!(
1392            fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
1393            "D",
1394        );
1395    }
1396}