worktree.rs

   1mod char_bag;
   2mod fuzzy;
   3mod ignore;
   4
   5use self::{char_bag::CharBag, ignore::IgnoreStack};
   6use crate::{
   7    editor::{self, Buffer, History, Operation, Rope},
   8    language::LanguageRegistry,
   9    rpc::{self, proto},
  10    sum_tree::{self, Cursor, Edit, SumTree},
  11    time::{self, ReplicaId},
  12    util::Bias,
  13};
  14use ::ignore::gitignore::Gitignore;
  15use anyhow::{anyhow, Context, Result};
  16use atomic::Ordering::SeqCst;
  17use fsevent::EventStream;
  18use futures::{Stream, StreamExt};
  19pub use fuzzy::{match_paths, PathMatch};
  20use gpui::{
  21    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  22    Task, WeakModelHandle,
  23};
  24use lazy_static::lazy_static;
  25use parking_lot::Mutex;
  26use postage::{
  27    prelude::{Sink as _, Stream as _},
  28    watch,
  29};
  30use smol::{
  31    channel::{self, Sender},
  32    io::{AsyncReadExt, AsyncWriteExt},
  33};
  34use std::{
  35    cmp::{self, Ordering},
  36    collections::HashMap,
  37    convert::{TryFrom, TryInto},
  38    ffi::{OsStr, OsString},
  39    fmt,
  40    future::Future,
  41    io,
  42    ops::Deref,
  43    os::unix::fs::MetadataExt,
  44    path::{Path, PathBuf},
  45    pin::Pin,
  46    sync::{
  47        atomic::{self, AtomicUsize},
  48        Arc,
  49    },
  50    time::{Duration, SystemTime},
  51};
  52use zed_rpc::{ForegroundRouter, PeerId, TypedEnvelope};
  53
  54lazy_static! {
  55    static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
  56}
  57
  58pub fn init(cx: &mut MutableAppContext, rpc: &rpc::Client, router: &mut ForegroundRouter) {
  59    rpc.on_message(router, remote::add_peer, cx);
  60    rpc.on_message(router, remote::remove_peer, cx);
  61    rpc.on_message(router, remote::update_worktree, cx);
  62    rpc.on_message(router, remote::open_buffer, cx);
  63    rpc.on_message(router, remote::close_buffer, cx);
  64    rpc.on_message(router, remote::update_buffer, cx);
  65    rpc.on_message(router, remote::buffer_saved, cx);
  66    rpc.on_message(router, remote::save_buffer, cx);
  67}
  68
  69#[async_trait::async_trait]
  70pub trait Fs: Send + Sync {
  71    async fn entry(
  72        &self,
  73        root_char_bag: CharBag,
  74        next_entry_id: &AtomicUsize,
  75        path: Arc<Path>,
  76        abs_path: &Path,
  77    ) -> Result<Option<Entry>>;
  78    async fn child_entries<'a>(
  79        &self,
  80        root_char_bag: CharBag,
  81        next_entry_id: &'a AtomicUsize,
  82        path: &'a Path,
  83        abs_path: &'a Path,
  84    ) -> Result<Pin<Box<dyn 'a + Stream<Item = Result<Entry>> + Send>>>;
  85    async fn load(&self, path: &Path) -> Result<String>;
  86    async fn save(&self, path: &Path, text: &Rope) -> Result<()>;
  87    async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
  88    async fn is_file(&self, path: &Path) -> bool;
  89    async fn watch(
  90        &self,
  91        path: &Path,
  92        latency: Duration,
  93    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>;
  94    fn is_fake(&self) -> bool;
  95}
  96
  97pub struct RealFs;
  98
  99#[async_trait::async_trait]
 100impl Fs for RealFs {
 101    async fn entry(
 102        &self,
 103        root_char_bag: CharBag,
 104        next_entry_id: &AtomicUsize,
 105        path: Arc<Path>,
 106        abs_path: &Path,
 107    ) -> Result<Option<Entry>> {
 108        let metadata = match smol::fs::metadata(&abs_path).await {
 109            Err(err) => {
 110                return match (err.kind(), err.raw_os_error()) {
 111                    (io::ErrorKind::NotFound, _) => Ok(None),
 112                    (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
 113                    _ => Err(anyhow::Error::new(err)),
 114                }
 115            }
 116            Ok(metadata) => metadata,
 117        };
 118        let inode = metadata.ino();
 119        let mtime = metadata.modified()?;
 120        let is_symlink = smol::fs::symlink_metadata(&abs_path)
 121            .await
 122            .context("failed to read symlink metadata")?
 123            .file_type()
 124            .is_symlink();
 125
 126        let entry = Entry {
 127            id: next_entry_id.fetch_add(1, SeqCst),
 128            kind: if metadata.file_type().is_dir() {
 129                EntryKind::PendingDir
 130            } else {
 131                EntryKind::File(char_bag_for_path(root_char_bag, &path))
 132            },
 133            path: Arc::from(path),
 134            inode,
 135            mtime,
 136            is_symlink,
 137            is_ignored: false,
 138        };
 139
 140        Ok(Some(entry))
 141    }
 142
 143    async fn child_entries<'a>(
 144        &self,
 145        root_char_bag: CharBag,
 146        next_entry_id: &'a AtomicUsize,
 147        path: &'a Path,
 148        abs_path: &'a Path,
 149    ) -> Result<Pin<Box<dyn 'a + Stream<Item = Result<Entry>> + Send>>> {
 150        let entries = smol::fs::read_dir(abs_path).await?;
 151        Ok(entries
 152            .then(move |entry| async move {
 153                let child_entry = entry?;
 154                let child_name = child_entry.file_name();
 155                let child_path: Arc<Path> = path.join(&child_name).into();
 156                let child_abs_path = abs_path.join(&child_name);
 157                let child_is_symlink = child_entry.metadata().await?.file_type().is_symlink();
 158                let child_metadata = smol::fs::metadata(child_abs_path).await?;
 159                let child_inode = child_metadata.ino();
 160                let child_mtime = child_metadata.modified()?;
 161                Ok(Entry {
 162                    id: next_entry_id.fetch_add(1, SeqCst),
 163                    kind: if child_metadata.file_type().is_dir() {
 164                        EntryKind::PendingDir
 165                    } else {
 166                        EntryKind::File(char_bag_for_path(root_char_bag, &child_path))
 167                    },
 168                    path: child_path,
 169                    inode: child_inode,
 170                    mtime: child_mtime,
 171                    is_symlink: child_is_symlink,
 172                    is_ignored: false,
 173                })
 174            })
 175            .boxed())
 176    }
 177
 178    async fn load(&self, path: &Path) -> Result<String> {
 179        let mut file = smol::fs::File::open(path).await?;
 180        let mut text = String::new();
 181        file.read_to_string(&mut text).await?;
 182        Ok(text)
 183    }
 184
 185    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
 186        let buffer_size = text.summary().bytes.min(10 * 1024);
 187        let file = smol::fs::File::create(path).await?;
 188        let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
 189        for chunk in text.chunks() {
 190            writer.write_all(chunk.as_bytes()).await?;
 191        }
 192        writer.flush().await?;
 193        Ok(())
 194    }
 195
 196    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 197        Ok(smol::fs::canonicalize(path).await?)
 198    }
 199
 200    async fn is_file(&self, path: &Path) -> bool {
 201        smol::fs::metadata(path)
 202            .await
 203            .map_or(false, |metadata| metadata.is_file())
 204    }
 205
 206    async fn watch(
 207        &self,
 208        path: &Path,
 209        latency: Duration,
 210    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
 211        let (mut tx, rx) = postage::mpsc::channel(64);
 212        let (stream, handle) = EventStream::new(&[path], latency);
 213        std::mem::forget(handle);
 214        std::thread::spawn(move || {
 215            stream.run(move |events| smol::block_on(tx.send(events)).is_ok());
 216        });
 217        Box::pin(rx)
 218    }
 219
 220    fn is_fake(&self) -> bool {
 221        false
 222    }
 223}
 224
 225#[derive(Clone, Debug)]
 226struct FakeFsEntry {
 227    inode: u64,
 228    mtime: SystemTime,
 229    is_dir: bool,
 230    is_symlink: bool,
 231    content: Option<String>,
 232}
 233
 234#[cfg(any(test, feature = "test-support"))]
 235struct FakeFsState {
 236    entries: std::collections::BTreeMap<PathBuf, FakeFsEntry>,
 237    next_inode: u64,
 238    events_tx: postage::broadcast::Sender<Vec<fsevent::Event>>,
 239}
 240
 241#[cfg(any(test, feature = "test-support"))]
 242impl FakeFsState {
 243    fn validate_path(&self, path: &Path) -> Result<()> {
 244        if path.is_absolute()
 245            && path
 246                .parent()
 247                .and_then(|path| self.entries.get(path))
 248                .map_or(false, |e| e.is_dir)
 249        {
 250            Ok(())
 251        } else {
 252            Err(anyhow!("invalid path {:?}", path))
 253        }
 254    }
 255
 256    async fn emit_event(&mut self, paths: &[&Path]) {
 257        let events = paths
 258            .iter()
 259            .map(|path| fsevent::Event {
 260                event_id: 0,
 261                flags: fsevent::StreamFlags::empty(),
 262                path: path.to_path_buf(),
 263            })
 264            .collect();
 265
 266        let _ = self.events_tx.send(events).await;
 267    }
 268}
 269
 270#[cfg(any(test, feature = "test-support"))]
 271pub struct FakeFs {
 272    // Use an unfair lock to ensure tests are deterministic.
 273    state: futures::lock::Mutex<FakeFsState>,
 274}
 275
 276#[cfg(any(test, feature = "test-support"))]
 277impl FakeFs {
 278    pub fn new() -> Self {
 279        let (events_tx, _) = postage::broadcast::channel(2048);
 280        let mut entries = std::collections::BTreeMap::new();
 281        entries.insert(
 282            Path::new("/").to_path_buf(),
 283            FakeFsEntry {
 284                inode: 0,
 285                mtime: SystemTime::now(),
 286                is_dir: true,
 287                is_symlink: false,
 288                content: None,
 289            },
 290        );
 291        Self {
 292            state: futures::lock::Mutex::new(FakeFsState {
 293                entries,
 294                next_inode: 1,
 295                events_tx,
 296            }),
 297        }
 298    }
 299
 300    pub async fn insert_dir(&self, path: impl AsRef<Path>) -> Result<()> {
 301        let mut state = self.state.lock().await;
 302        let path = path.as_ref();
 303        state.validate_path(path)?;
 304
 305        let inode = state.next_inode;
 306        state.next_inode += 1;
 307        state.entries.insert(
 308            path.to_path_buf(),
 309            FakeFsEntry {
 310                inode,
 311                mtime: SystemTime::now(),
 312                is_dir: true,
 313                is_symlink: false,
 314                content: None,
 315            },
 316        );
 317        state.emit_event(&[path]).await;
 318        Ok(())
 319    }
 320
 321    pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) -> Result<()> {
 322        let mut state = self.state.lock().await;
 323        let path = path.as_ref();
 324        state.validate_path(path)?;
 325
 326        let inode = state.next_inode;
 327        state.next_inode += 1;
 328        state.entries.insert(
 329            path.to_path_buf(),
 330            FakeFsEntry {
 331                inode,
 332                mtime: SystemTime::now(),
 333                is_dir: false,
 334                is_symlink: false,
 335                content: Some(content),
 336            },
 337        );
 338        state.emit_event(&[path]).await;
 339        Ok(())
 340    }
 341
 342    pub async fn remove(&self, path: &Path) -> Result<()> {
 343        let mut state = self.state.lock().await;
 344        state.validate_path(path)?;
 345        state.entries.retain(|path, _| !path.starts_with(path));
 346        state.emit_event(&[path]).await;
 347        Ok(())
 348    }
 349
 350    pub async fn rename(&self, source: &Path, target: &Path) -> Result<()> {
 351        let mut state = self.state.lock().await;
 352        state.validate_path(source)?;
 353        state.validate_path(target)?;
 354        if state.entries.contains_key(target) {
 355            Err(anyhow!("target path already exists"))
 356        } else {
 357            let mut removed = Vec::new();
 358            state.entries.retain(|path, entry| {
 359                if let Ok(relative_path) = path.strip_prefix(source) {
 360                    removed.push((relative_path.to_path_buf(), entry.clone()));
 361                    false
 362                } else {
 363                    true
 364                }
 365            });
 366
 367            for (relative_path, entry) in removed {
 368                let new_path = target.join(relative_path);
 369                state.entries.insert(new_path, entry);
 370            }
 371
 372            state.emit_event(&[source, target]).await;
 373            Ok(())
 374        }
 375    }
 376}
 377
 378#[cfg(any(test, feature = "test-support"))]
 379#[async_trait::async_trait]
 380impl Fs for FakeFs {
 381    async fn entry(
 382        &self,
 383        root_char_bag: CharBag,
 384        next_entry_id: &AtomicUsize,
 385        path: Arc<Path>,
 386        abs_path: &Path,
 387    ) -> Result<Option<Entry>> {
 388        let state = self.state.lock().await;
 389        if let Some(entry) = state.entries.get(abs_path) {
 390            Ok(Some(Entry {
 391                id: next_entry_id.fetch_add(1, SeqCst),
 392                kind: if entry.is_dir {
 393                    EntryKind::PendingDir
 394                } else {
 395                    EntryKind::File(char_bag_for_path(root_char_bag, &path))
 396                },
 397                path: Arc::from(path),
 398                inode: entry.inode,
 399                mtime: entry.mtime,
 400                is_symlink: entry.is_symlink,
 401                is_ignored: false,
 402            }))
 403        } else {
 404            Ok(None)
 405        }
 406    }
 407
 408    async fn child_entries<'a>(
 409        &self,
 410        root_char_bag: CharBag,
 411        next_entry_id: &'a AtomicUsize,
 412        path: &'a Path,
 413        abs_path: &'a Path,
 414    ) -> Result<Pin<Box<dyn 'a + Stream<Item = Result<Entry>> + Send>>> {
 415        use futures::{future, stream};
 416
 417        let state = self.state.lock().await;
 418        Ok(stream::iter(state.entries.clone())
 419            .filter(move |(child_path, _)| future::ready(child_path.parent() == Some(abs_path)))
 420            .then(move |(child_abs_path, child_entry)| async move {
 421                smol::future::yield_now().await;
 422                let child_path = Arc::from(path.join(child_abs_path.file_name().unwrap()));
 423                Ok(Entry {
 424                    id: next_entry_id.fetch_add(1, SeqCst),
 425                    kind: if child_entry.is_dir {
 426                        EntryKind::PendingDir
 427                    } else {
 428                        EntryKind::File(char_bag_for_path(root_char_bag, &child_path))
 429                    },
 430                    path: child_path,
 431                    inode: child_entry.inode,
 432                    mtime: child_entry.mtime,
 433                    is_symlink: child_entry.is_symlink,
 434                    is_ignored: false,
 435                })
 436            })
 437            .boxed())
 438    }
 439
 440    async fn load(&self, path: &Path) -> Result<String> {
 441        let state = self.state.lock().await;
 442        let text = state
 443            .entries
 444            .get(path)
 445            .and_then(|e| e.content.as_ref())
 446            .ok_or_else(|| anyhow!("file {:?} does not exist", path))?;
 447        Ok(text.clone())
 448    }
 449
 450    async fn save(&self, path: &Path, text: &Rope) -> Result<()> {
 451        let mut state = self.state.lock().await;
 452        state.validate_path(path)?;
 453        if let Some(entry) = state.entries.get_mut(path) {
 454            if entry.is_dir {
 455                Err(anyhow!("cannot overwrite a directory with a file"))
 456            } else {
 457                entry.content = Some(text.chunks().collect());
 458                entry.mtime = SystemTime::now();
 459                state.emit_event(&[path]).await;
 460                Ok(())
 461            }
 462        } else {
 463            let inode = state.next_inode;
 464            state.next_inode += 1;
 465            let entry = FakeFsEntry {
 466                inode,
 467                mtime: SystemTime::now(),
 468                is_dir: false,
 469                is_symlink: false,
 470                content: Some(text.chunks().collect()),
 471            };
 472            state.entries.insert(path.to_path_buf(), entry);
 473            state.emit_event(&[path]).await;
 474            Ok(())
 475        }
 476    }
 477
 478    async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
 479        Ok(path.to_path_buf())
 480    }
 481
 482    async fn is_file(&self, path: &Path) -> bool {
 483        let state = self.state.lock().await;
 484        state.entries.get(path).map_or(false, |entry| !entry.is_dir)
 485    }
 486
 487    async fn watch(
 488        &self,
 489        path: &Path,
 490        _: Duration,
 491    ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
 492        let state = self.state.lock().await;
 493        let rx = state.events_tx.subscribe();
 494        let path = path.to_path_buf();
 495        Box::pin(futures::StreamExt::filter(rx, move |events| {
 496            let result = events.iter().any(|event| event.path.starts_with(&path));
 497            async move { result }
 498        }))
 499    }
 500
 501    fn is_fake(&self) -> bool {
 502        true
 503    }
 504}
 505
 506#[derive(Clone, Debug)]
 507enum ScanState {
 508    Idle,
 509    Scanning,
 510    Err(Arc<anyhow::Error>),
 511}
 512
 513pub enum Worktree {
 514    Local(LocalWorktree),
 515    Remote(RemoteWorktree),
 516}
 517
 518impl Entity for Worktree {
 519    type Event = ();
 520
 521    fn release(&mut self, cx: &mut MutableAppContext) {
 522        let rpc = match self {
 523            Self::Local(tree) => tree.rpc.clone(),
 524            Self::Remote(tree) => Some((tree.rpc.clone(), tree.remote_id)),
 525        };
 526
 527        if let Some((rpc, worktree_id)) = rpc {
 528            cx.spawn(|_| async move {
 529                rpc.state
 530                    .write()
 531                    .await
 532                    .shared_worktrees
 533                    .remove(&worktree_id);
 534                if let Err(err) = rpc.send(proto::CloseWorktree { worktree_id }).await {
 535                    log::error!("error closing worktree {}: {}", worktree_id, err);
 536                }
 537            })
 538            .detach();
 539        }
 540    }
 541}
 542
 543impl Worktree {
 544    pub async fn open_local(
 545        path: impl Into<Arc<Path>>,
 546        languages: Arc<LanguageRegistry>,
 547        fs: Arc<dyn Fs>,
 548        cx: &mut AsyncAppContext,
 549    ) -> Result<ModelHandle<Self>> {
 550        let (tree, scan_states_tx) = LocalWorktree::new(path, languages, fs.clone(), cx).await?;
 551        tree.update(cx, |tree, cx| {
 552            let tree = tree.as_local_mut().unwrap();
 553            let abs_path = tree.snapshot.abs_path.clone();
 554            let background_snapshot = tree.background_snapshot.clone();
 555            let thread_pool = cx.thread_pool().clone();
 556            tree._background_scanner_task = Some(cx.background().spawn(async move {
 557                let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 558                let scanner =
 559                    BackgroundScanner::new(background_snapshot, scan_states_tx, fs, thread_pool);
 560                scanner.run(events).await;
 561            }));
 562        });
 563        Ok(tree)
 564    }
 565
 566    pub async fn open_remote(
 567        rpc: rpc::Client,
 568        id: u64,
 569        access_token: String,
 570        languages: Arc<LanguageRegistry>,
 571        cx: &mut AsyncAppContext,
 572    ) -> Result<ModelHandle<Self>> {
 573        let response = rpc
 574            .request(proto::OpenWorktree {
 575                worktree_id: id,
 576                access_token,
 577            })
 578            .await?;
 579
 580        Worktree::remote(response, rpc, languages, cx).await
 581    }
 582
 583    async fn remote(
 584        open_response: proto::OpenWorktreeResponse,
 585        rpc: rpc::Client,
 586        languages: Arc<LanguageRegistry>,
 587        cx: &mut AsyncAppContext,
 588    ) -> Result<ModelHandle<Self>> {
 589        let worktree = open_response
 590            .worktree
 591            .ok_or_else(|| anyhow!("empty worktree"))?;
 592
 593        let remote_id = open_response.worktree_id;
 594        let replica_id = open_response.replica_id as ReplicaId;
 595        let peers = open_response.peers;
 596        let root_char_bag: CharBag = worktree
 597            .root_name
 598            .chars()
 599            .map(|c| c.to_ascii_lowercase())
 600            .collect();
 601        let root_name = worktree.root_name.clone();
 602        let (entries_by_path, entries_by_id) = cx
 603            .background()
 604            .spawn(async move {
 605                let mut entries_by_path_edits = Vec::new();
 606                let mut entries_by_id_edits = Vec::new();
 607                for entry in worktree.entries {
 608                    match Entry::try_from((&root_char_bag, entry)) {
 609                        Ok(entry) => {
 610                            entries_by_id_edits.push(Edit::Insert(PathEntry {
 611                                id: entry.id,
 612                                path: entry.path.clone(),
 613                                scan_id: 0,
 614                            }));
 615                            entries_by_path_edits.push(Edit::Insert(entry));
 616                        }
 617                        Err(err) => log::warn!("error for remote worktree entry {:?}", err),
 618                    }
 619                }
 620
 621                let mut entries_by_path = SumTree::new();
 622                let mut entries_by_id = SumTree::new();
 623                entries_by_path.edit(entries_by_path_edits, &());
 624                entries_by_id.edit(entries_by_id_edits, &());
 625                (entries_by_path, entries_by_id)
 626            })
 627            .await;
 628
 629        let worktree = cx.update(|cx| {
 630            cx.add_model(|cx: &mut ModelContext<Worktree>| {
 631                let snapshot = Snapshot {
 632                    id: cx.model_id(),
 633                    scan_id: 0,
 634                    abs_path: Path::new("").into(),
 635                    root_name,
 636                    root_char_bag,
 637                    ignores: Default::default(),
 638                    entries_by_path,
 639                    entries_by_id,
 640                    removed_entry_ids: Default::default(),
 641                    next_entry_id: Default::default(),
 642                };
 643
 644                let (updates_tx, mut updates_rx) = postage::mpsc::channel(64);
 645                let (mut snapshot_tx, snapshot_rx) = watch::channel_with(snapshot.clone());
 646
 647                cx.background()
 648                    .spawn(async move {
 649                        while let Some(update) = updates_rx.recv().await {
 650                            let mut snapshot = snapshot_tx.borrow().clone();
 651                            if let Err(error) = snapshot.apply_update(update) {
 652                                log::error!("error applying worktree update: {}", error);
 653                            }
 654                            *snapshot_tx.borrow_mut() = snapshot;
 655                        }
 656                    })
 657                    .detach();
 658
 659                {
 660                    let mut snapshot_rx = snapshot_rx.clone();
 661                    cx.spawn_weak(|this, mut cx| async move {
 662                        while let Some(_) = snapshot_rx.recv().await {
 663                            if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
 664                                this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 665                            } else {
 666                                break;
 667                            }
 668                        }
 669                    })
 670                    .detach();
 671                }
 672
 673                Worktree::Remote(RemoteWorktree {
 674                    remote_id,
 675                    replica_id,
 676                    snapshot,
 677                    snapshot_rx,
 678                    updates_tx,
 679                    rpc: rpc.clone(),
 680                    open_buffers: Default::default(),
 681                    peers: peers
 682                        .into_iter()
 683                        .map(|p| (PeerId(p.peer_id), p.replica_id as ReplicaId))
 684                        .collect(),
 685                    languages,
 686                })
 687            })
 688        });
 689        rpc.state
 690            .write()
 691            .await
 692            .shared_worktrees
 693            .insert(open_response.worktree_id, worktree.downgrade());
 694
 695        Ok(worktree)
 696    }
 697
 698    pub fn as_local(&self) -> Option<&LocalWorktree> {
 699        if let Worktree::Local(worktree) = self {
 700            Some(worktree)
 701        } else {
 702            None
 703        }
 704    }
 705
 706    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 707        if let Worktree::Local(worktree) = self {
 708            Some(worktree)
 709        } else {
 710            None
 711        }
 712    }
 713
 714    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 715        if let Worktree::Remote(worktree) = self {
 716            Some(worktree)
 717        } else {
 718            None
 719        }
 720    }
 721
 722    pub fn snapshot(&self) -> Snapshot {
 723        match self {
 724            Worktree::Local(worktree) => worktree.snapshot(),
 725            Worktree::Remote(worktree) => worktree.snapshot(),
 726        }
 727    }
 728
 729    pub fn replica_id(&self) -> ReplicaId {
 730        match self {
 731            Worktree::Local(_) => 0,
 732            Worktree::Remote(worktree) => worktree.replica_id,
 733        }
 734    }
 735
 736    pub fn add_peer(
 737        &mut self,
 738        envelope: TypedEnvelope<proto::AddPeer>,
 739        cx: &mut ModelContext<Worktree>,
 740    ) -> Result<()> {
 741        match self {
 742            Worktree::Local(worktree) => worktree.add_peer(envelope, cx),
 743            Worktree::Remote(worktree) => worktree.add_peer(envelope, cx),
 744        }
 745    }
 746
 747    pub fn remove_peer(
 748        &mut self,
 749        envelope: TypedEnvelope<proto::RemovePeer>,
 750        cx: &mut ModelContext<Worktree>,
 751    ) -> Result<()> {
 752        match self {
 753            Worktree::Local(worktree) => worktree.remove_peer(envelope, cx),
 754            Worktree::Remote(worktree) => worktree.remove_peer(envelope, cx),
 755        }
 756    }
 757
 758    pub fn peers(&self) -> &HashMap<PeerId, ReplicaId> {
 759        match self {
 760            Worktree::Local(worktree) => &worktree.peers,
 761            Worktree::Remote(worktree) => &worktree.peers,
 762        }
 763    }
 764
 765    pub fn open_buffer(
 766        &mut self,
 767        path: impl AsRef<Path>,
 768        cx: &mut ModelContext<Self>,
 769    ) -> Task<Result<ModelHandle<Buffer>>> {
 770        match self {
 771            Worktree::Local(worktree) => worktree.open_buffer(path.as_ref(), cx),
 772            Worktree::Remote(worktree) => worktree.open_buffer(path.as_ref(), cx),
 773        }
 774    }
 775
 776    #[cfg(feature = "test-support")]
 777    pub fn has_open_buffer(&self, path: impl AsRef<Path>, cx: &AppContext) -> bool {
 778        let mut open_buffers: Box<dyn Iterator<Item = _>> = match self {
 779            Worktree::Local(worktree) => Box::new(worktree.open_buffers.values()),
 780            Worktree::Remote(worktree) => {
 781                Box::new(worktree.open_buffers.values().filter_map(|buf| {
 782                    if let RemoteBuffer::Loaded(buf) = buf {
 783                        Some(buf)
 784                    } else {
 785                        None
 786                    }
 787                }))
 788            }
 789        };
 790
 791        let path = path.as_ref();
 792        open_buffers
 793            .find(|buffer| {
 794                if let Some(file) = buffer.upgrade(cx).and_then(|buffer| buffer.read(cx).file()) {
 795                    file.path.as_ref() == path
 796                } else {
 797                    false
 798                }
 799            })
 800            .is_some()
 801    }
 802
 803    pub fn update_buffer(
 804        &mut self,
 805        envelope: proto::UpdateBuffer,
 806        cx: &mut ModelContext<Self>,
 807    ) -> Result<()> {
 808        let buffer_id = envelope.buffer_id as usize;
 809        let ops = envelope
 810            .operations
 811            .into_iter()
 812            .map(|op| op.try_into())
 813            .collect::<anyhow::Result<Vec<_>>>()?;
 814
 815        match self {
 816            Worktree::Local(worktree) => {
 817                let buffer = worktree
 818                    .open_buffers
 819                    .get(&buffer_id)
 820                    .and_then(|buf| buf.upgrade(&cx))
 821                    .ok_or_else(|| {
 822                        anyhow!("invalid buffer {} in update buffer message", buffer_id)
 823                    })?;
 824                buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 825            }
 826            Worktree::Remote(worktree) => match worktree.open_buffers.get_mut(&buffer_id) {
 827                Some(RemoteBuffer::Operations(pending_ops)) => pending_ops.extend(ops),
 828                Some(RemoteBuffer::Loaded(buffer)) => {
 829                    if let Some(buffer) = buffer.upgrade(&cx) {
 830                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 831                    } else {
 832                        worktree
 833                            .open_buffers
 834                            .insert(buffer_id, RemoteBuffer::Operations(ops));
 835                    }
 836                }
 837                None => {
 838                    worktree
 839                        .open_buffers
 840                        .insert(buffer_id, RemoteBuffer::Operations(ops));
 841                }
 842            },
 843        }
 844
 845        Ok(())
 846    }
 847
 848    pub fn buffer_saved(
 849        &mut self,
 850        message: proto::BufferSaved,
 851        cx: &mut ModelContext<Self>,
 852    ) -> Result<()> {
 853        if let Worktree::Remote(worktree) = self {
 854            if let Some(buffer) = worktree
 855                .open_buffers
 856                .get(&(message.buffer_id as usize))
 857                .and_then(|buf| buf.upgrade(&cx))
 858            {
 859                buffer.update(cx, |buffer, cx| {
 860                    let version = message.version.try_into()?;
 861                    let mtime = message
 862                        .mtime
 863                        .ok_or_else(|| anyhow!("missing mtime"))?
 864                        .into();
 865                    buffer.did_save(version, mtime, cx);
 866                    Result::<_, anyhow::Error>::Ok(())
 867                })?;
 868            }
 869            Ok(())
 870        } else {
 871            Err(anyhow!(
 872                "invalid buffer {} in buffer saved message",
 873                message.buffer_id
 874            ))
 875        }
 876    }
 877
 878    fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
 879        match self {
 880            Self::Local(worktree) => {
 881                let is_fake_fs = worktree.fs.is_fake();
 882                worktree.snapshot = worktree.background_snapshot.lock().clone();
 883                if worktree.is_scanning() {
 884                    if !worktree.poll_scheduled {
 885                        cx.spawn(|this, mut cx| async move {
 886                            if is_fake_fs {
 887                                smol::future::yield_now().await;
 888                            } else {
 889                                smol::Timer::after(Duration::from_millis(100)).await;
 890                            }
 891                            this.update(&mut cx, |this, cx| {
 892                                this.as_local_mut().unwrap().poll_scheduled = false;
 893                                this.poll_snapshot(cx);
 894                            })
 895                        })
 896                        .detach();
 897                        worktree.poll_scheduled = true;
 898                    }
 899                } else {
 900                    self.update_open_buffers(cx);
 901                }
 902            }
 903            Self::Remote(worktree) => {
 904                worktree.snapshot = worktree.snapshot_rx.borrow().clone();
 905                self.update_open_buffers(cx);
 906            }
 907        };
 908
 909        cx.notify();
 910    }
 911
 912    fn update_open_buffers(&mut self, cx: &mut ModelContext<Self>) {
 913        let open_buffers: Box<dyn Iterator<Item = _>> = match &self {
 914            Self::Local(worktree) => Box::new(worktree.open_buffers.iter()),
 915            Self::Remote(worktree) => {
 916                Box::new(worktree.open_buffers.iter().filter_map(|(id, buf)| {
 917                    if let RemoteBuffer::Loaded(buf) = buf {
 918                        Some((id, buf))
 919                    } else {
 920                        None
 921                    }
 922                }))
 923            }
 924        };
 925
 926        let mut buffers_to_delete = Vec::new();
 927        for (buffer_id, buffer) in open_buffers {
 928            if let Some(buffer) = buffer.upgrade(&cx) {
 929                buffer.update(cx, |buffer, cx| {
 930                    let buffer_is_clean = !buffer.is_dirty();
 931
 932                    if let Some(file) = buffer.file_mut() {
 933                        let mut file_changed = false;
 934
 935                        if let Some(entry) = file
 936                            .entry_id
 937                            .and_then(|entry_id| self.entry_for_id(entry_id))
 938                        {
 939                            if entry.path != file.path {
 940                                file.path = entry.path.clone();
 941                                file_changed = true;
 942                            }
 943
 944                            if entry.mtime != file.mtime {
 945                                file.mtime = entry.mtime;
 946                                file_changed = true;
 947                                if let Some(worktree) = self.as_local() {
 948                                    if buffer_is_clean {
 949                                        let abs_path = worktree.absolutize(&file.path);
 950                                        refresh_buffer(abs_path, &worktree.fs, cx);
 951                                    }
 952                                }
 953                            }
 954                        } else if let Some(entry) = self.entry_for_path(&file.path) {
 955                            file.entry_id = Some(entry.id);
 956                            file.mtime = entry.mtime;
 957                            if let Some(worktree) = self.as_local() {
 958                                if buffer_is_clean {
 959                                    let abs_path = worktree.absolutize(&file.path);
 960                                    refresh_buffer(abs_path, &worktree.fs, cx);
 961                                }
 962                            }
 963                            file_changed = true;
 964                        } else if !file.is_deleted() {
 965                            if buffer_is_clean {
 966                                cx.emit(editor::buffer::Event::Dirtied);
 967                            }
 968                            file.entry_id = None;
 969                            file_changed = true;
 970                        }
 971
 972                        if file_changed {
 973                            cx.emit(editor::buffer::Event::FileHandleChanged);
 974                        }
 975                    }
 976                });
 977            } else {
 978                buffers_to_delete.push(*buffer_id);
 979            }
 980        }
 981
 982        for buffer_id in buffers_to_delete {
 983            match self {
 984                Self::Local(worktree) => {
 985                    worktree.open_buffers.remove(&buffer_id);
 986                }
 987                Self::Remote(worktree) => {
 988                    worktree.open_buffers.remove(&buffer_id);
 989                }
 990            }
 991        }
 992    }
 993}
 994
 995impl Deref for Worktree {
 996    type Target = Snapshot;
 997
 998    fn deref(&self) -> &Self::Target {
 999        match self {
1000            Worktree::Local(worktree) => &worktree.snapshot,
1001            Worktree::Remote(worktree) => &worktree.snapshot,
1002        }
1003    }
1004}
1005
1006pub struct LocalWorktree {
1007    snapshot: Snapshot,
1008    background_snapshot: Arc<Mutex<Snapshot>>,
1009    snapshots_to_send_tx: Option<Sender<Snapshot>>,
1010    last_scan_state_rx: watch::Receiver<ScanState>,
1011    _background_scanner_task: Option<Task<()>>,
1012    poll_scheduled: bool,
1013    rpc: Option<(rpc::Client, u64)>,
1014    open_buffers: HashMap<usize, WeakModelHandle<Buffer>>,
1015    shared_buffers: HashMap<PeerId, HashMap<u64, ModelHandle<Buffer>>>,
1016    peers: HashMap<PeerId, ReplicaId>,
1017    languages: Arc<LanguageRegistry>,
1018    fs: Arc<dyn Fs>,
1019}
1020
1021impl LocalWorktree {
1022    async fn new(
1023        path: impl Into<Arc<Path>>,
1024        languages: Arc<LanguageRegistry>,
1025        fs: Arc<dyn Fs>,
1026        cx: &mut AsyncAppContext,
1027    ) -> Result<(ModelHandle<Worktree>, Sender<ScanState>)> {
1028        let abs_path = path.into();
1029        let path: Arc<Path> = Arc::from(Path::new(""));
1030        let next_entry_id = AtomicUsize::new(0);
1031
1032        // After determining whether the root entry is a file or a directory, populate the
1033        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
1034        let mut root_name = abs_path
1035            .file_name()
1036            .map_or(String::new(), |f| f.to_string_lossy().to_string());
1037        let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
1038        let entry = fs
1039            .entry(root_char_bag, &next_entry_id, path.clone(), &abs_path)
1040            .await?
1041            .ok_or_else(|| anyhow!("root entry does not exist"))?;
1042        let is_dir = entry.is_dir();
1043        if is_dir {
1044            root_name.push('/');
1045        }
1046
1047        let (scan_states_tx, scan_states_rx) = smol::channel::unbounded();
1048        let (mut last_scan_state_tx, last_scan_state_rx) = watch::channel_with(ScanState::Scanning);
1049        let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
1050            let mut snapshot = Snapshot {
1051                id: cx.model_id(),
1052                scan_id: 0,
1053                abs_path,
1054                root_name,
1055                root_char_bag,
1056                ignores: Default::default(),
1057                entries_by_path: Default::default(),
1058                entries_by_id: Default::default(),
1059                removed_entry_ids: Default::default(),
1060                next_entry_id: Arc::new(next_entry_id),
1061            };
1062            snapshot.insert_entry(entry);
1063
1064            let tree = Self {
1065                snapshot: snapshot.clone(),
1066                background_snapshot: Arc::new(Mutex::new(snapshot)),
1067                snapshots_to_send_tx: None,
1068                last_scan_state_rx,
1069                _background_scanner_task: None,
1070                poll_scheduled: false,
1071                open_buffers: Default::default(),
1072                shared_buffers: Default::default(),
1073                peers: Default::default(),
1074                rpc: None,
1075                languages,
1076                fs,
1077            };
1078
1079            cx.spawn_weak(|this, mut cx| async move {
1080                while let Ok(scan_state) = scan_states_rx.recv().await {
1081                    if let Some(handle) = cx.read(|cx| this.upgrade(&cx)) {
1082                        let to_send = handle.update(&mut cx, |this, cx| {
1083                            last_scan_state_tx.blocking_send(scan_state).ok();
1084                            this.poll_snapshot(cx);
1085                            let tree = this.as_local_mut().unwrap();
1086                            if !tree.is_scanning() {
1087                                if let Some(snapshots_to_send_tx) =
1088                                    tree.snapshots_to_send_tx.clone()
1089                                {
1090                                    Some((tree.snapshot(), snapshots_to_send_tx))
1091                                } else {
1092                                    None
1093                                }
1094                            } else {
1095                                None
1096                            }
1097                        });
1098
1099                        if let Some((snapshot, snapshots_to_send_tx)) = to_send {
1100                            if let Err(err) = snapshots_to_send_tx.send(snapshot).await {
1101                                log::error!("error submitting snapshot to send {}", err);
1102                            }
1103                        }
1104                    } else {
1105                        break;
1106                    }
1107                }
1108            })
1109            .detach();
1110
1111            Worktree::Local(tree)
1112        });
1113
1114        Ok((tree, scan_states_tx))
1115    }
1116
1117    pub fn open_buffer(
1118        &mut self,
1119        path: &Path,
1120        cx: &mut ModelContext<Worktree>,
1121    ) -> Task<Result<ModelHandle<Buffer>>> {
1122        let handle = cx.handle();
1123
1124        // If there is already a buffer for the given path, then return it.
1125        let mut existing_buffer = None;
1126        self.open_buffers.retain(|_buffer_id, buffer| {
1127            if let Some(buffer) = buffer.upgrade(cx.as_ref()) {
1128                if let Some(file) = buffer.read(cx.as_ref()).file() {
1129                    if file.worktree_id() == handle.id() && file.path.as_ref() == path {
1130                        existing_buffer = Some(buffer);
1131                    }
1132                }
1133                true
1134            } else {
1135                false
1136            }
1137        });
1138
1139        let languages = self.languages.clone();
1140        let path = Arc::from(path);
1141        cx.spawn(|this, mut cx| async move {
1142            if let Some(existing_buffer) = existing_buffer {
1143                Ok(existing_buffer)
1144            } else {
1145                let (file, contents) = this
1146                    .update(&mut cx, |this, cx| this.as_local().unwrap().load(&path, cx))
1147                    .await?;
1148                let language = languages.select_language(&path).cloned();
1149                let buffer = cx.add_model(|cx| {
1150                    Buffer::from_history(0, History::new(contents.into()), Some(file), language, cx)
1151                });
1152                this.update(&mut cx, |this, _| {
1153                    let this = this
1154                        .as_local_mut()
1155                        .ok_or_else(|| anyhow!("must be a local worktree"))?;
1156                    this.open_buffers.insert(buffer.id(), buffer.downgrade());
1157                    Ok(buffer)
1158                })
1159            }
1160        })
1161    }
1162
1163    pub fn open_remote_buffer(
1164        &mut self,
1165        envelope: TypedEnvelope<proto::OpenBuffer>,
1166        cx: &mut ModelContext<Worktree>,
1167    ) -> Task<Result<proto::OpenBufferResponse>> {
1168        let peer_id = envelope.original_sender_id();
1169        let path = Path::new(&envelope.payload.path);
1170
1171        let buffer = self.open_buffer(path, cx);
1172
1173        cx.spawn(|this, mut cx| async move {
1174            let buffer = buffer.await?;
1175            this.update(&mut cx, |this, cx| {
1176                this.as_local_mut()
1177                    .unwrap()
1178                    .shared_buffers
1179                    .entry(peer_id?)
1180                    .or_default()
1181                    .insert(buffer.id() as u64, buffer.clone());
1182
1183                Ok(proto::OpenBufferResponse {
1184                    buffer: Some(buffer.update(cx.as_mut(), |buffer, cx| buffer.to_proto(cx))),
1185                })
1186            })
1187        })
1188    }
1189
1190    pub fn close_remote_buffer(
1191        &mut self,
1192        envelope: TypedEnvelope<proto::CloseBuffer>,
1193        _: &mut ModelContext<Worktree>,
1194    ) -> Result<()> {
1195        if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
1196            shared_buffers.remove(&envelope.payload.buffer_id);
1197        }
1198
1199        Ok(())
1200    }
1201
1202    pub fn add_peer(
1203        &mut self,
1204        envelope: TypedEnvelope<proto::AddPeer>,
1205        cx: &mut ModelContext<Worktree>,
1206    ) -> Result<()> {
1207        let peer = envelope.payload.peer.ok_or_else(|| anyhow!("empty peer"))?;
1208        self.peers
1209            .insert(PeerId(peer.peer_id), peer.replica_id as ReplicaId);
1210        cx.notify();
1211        Ok(())
1212    }
1213
1214    pub fn remove_peer(
1215        &mut self,
1216        envelope: TypedEnvelope<proto::RemovePeer>,
1217        cx: &mut ModelContext<Worktree>,
1218    ) -> Result<()> {
1219        let peer_id = PeerId(envelope.payload.peer_id);
1220        let replica_id = self
1221            .peers
1222            .remove(&peer_id)
1223            .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?;
1224        self.shared_buffers.remove(&peer_id);
1225        for (_, buffer) in &self.open_buffers {
1226            if let Some(buffer) = buffer.upgrade(&cx) {
1227                buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1228            }
1229        }
1230        cx.notify();
1231        Ok(())
1232    }
1233
1234    pub fn scan_complete(&self) -> impl Future<Output = ()> {
1235        let mut scan_state_rx = self.last_scan_state_rx.clone();
1236        async move {
1237            let mut scan_state = Some(scan_state_rx.borrow().clone());
1238            while let Some(ScanState::Scanning) = scan_state {
1239                scan_state = scan_state_rx.recv().await;
1240            }
1241        }
1242    }
1243
1244    fn is_scanning(&self) -> bool {
1245        if let ScanState::Scanning = *self.last_scan_state_rx.borrow() {
1246            true
1247        } else {
1248            false
1249        }
1250    }
1251
1252    pub fn snapshot(&self) -> Snapshot {
1253        self.snapshot.clone()
1254    }
1255
1256    pub fn abs_path(&self) -> &Path {
1257        self.snapshot.abs_path.as_ref()
1258    }
1259
1260    pub fn contains_abs_path(&self, path: &Path) -> bool {
1261        path.starts_with(&self.snapshot.abs_path)
1262    }
1263
1264    fn absolutize(&self, path: &Path) -> PathBuf {
1265        if path.file_name().is_some() {
1266            self.snapshot.abs_path.join(path)
1267        } else {
1268            self.snapshot.abs_path.to_path_buf()
1269        }
1270    }
1271
1272    fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
1273        let handle = cx.handle();
1274        let path = Arc::from(path);
1275        let abs_path = self.absolutize(&path);
1276        let background_snapshot = self.background_snapshot.clone();
1277        let fs = self.fs.clone();
1278        cx.spawn(|this, mut cx| async move {
1279            let text = fs.load(&abs_path).await?;
1280            // Eagerly populate the snapshot with an updated entry for the loaded file
1281            let entry = refresh_entry(fs.as_ref(), &background_snapshot, path, &abs_path).await?;
1282            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
1283            Ok((File::new(entry.id, handle, entry.path, entry.mtime), text))
1284        })
1285    }
1286
1287    pub fn save_buffer_as(
1288        &self,
1289        buffer: ModelHandle<Buffer>,
1290        path: impl Into<Arc<Path>>,
1291        text: Rope,
1292        cx: &mut ModelContext<Worktree>,
1293    ) -> Task<Result<File>> {
1294        let save = self.save(path, text, cx);
1295        cx.spawn(|this, mut cx| async move {
1296            let entry = save.await?;
1297            this.update(&mut cx, |this, cx| {
1298                this.as_local_mut()
1299                    .unwrap()
1300                    .open_buffers
1301                    .insert(buffer.id(), buffer.downgrade());
1302                Ok(File::new(entry.id, cx.handle(), entry.path, entry.mtime))
1303            })
1304        })
1305    }
1306
1307    fn save(
1308        &self,
1309        path: impl Into<Arc<Path>>,
1310        text: Rope,
1311        cx: &mut ModelContext<Worktree>,
1312    ) -> Task<Result<Entry>> {
1313        let path = path.into();
1314        let abs_path = self.absolutize(&path);
1315        let background_snapshot = self.background_snapshot.clone();
1316        let fs = self.fs.clone();
1317        let save = cx.background().spawn(async move {
1318            fs.save(&abs_path, &text).await?;
1319            refresh_entry(fs.as_ref(), &background_snapshot, path.clone(), &abs_path).await
1320        });
1321
1322        cx.spawn(|this, mut cx| async move {
1323            let entry = save.await?;
1324            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
1325            Ok(entry)
1326        })
1327    }
1328
1329    pub fn share(
1330        &mut self,
1331        rpc: rpc::Client,
1332        cx: &mut ModelContext<Worktree>,
1333    ) -> Task<anyhow::Result<(u64, String)>> {
1334        let snapshot = self.snapshot();
1335        let share_request = self.share_request(cx);
1336        let handle = cx.handle();
1337        cx.spawn(|this, mut cx| async move {
1338            let share_request = share_request.await;
1339            let share_response = rpc.request(share_request).await?;
1340
1341            rpc.state
1342                .write()
1343                .await
1344                .shared_worktrees
1345                .insert(share_response.worktree_id, handle.downgrade());
1346
1347            log::info!("sharing worktree {:?}", share_response);
1348            let (snapshots_to_send_tx, snapshots_to_send_rx) =
1349                smol::channel::unbounded::<Snapshot>();
1350
1351            cx.background()
1352                .spawn({
1353                    let rpc = rpc.clone();
1354                    let worktree_id = share_response.worktree_id;
1355                    async move {
1356                        let mut prev_snapshot = snapshot;
1357                        while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
1358                            let message = snapshot.build_update(&prev_snapshot, worktree_id);
1359                            match rpc.send(message).await {
1360                                Ok(()) => prev_snapshot = snapshot,
1361                                Err(err) => log::error!("error sending snapshot diff {}", err),
1362                            }
1363                        }
1364                    }
1365                })
1366                .detach();
1367
1368            this.update(&mut cx, |worktree, _| {
1369                let worktree = worktree.as_local_mut().unwrap();
1370                worktree.rpc = Some((rpc, share_response.worktree_id));
1371                worktree.snapshots_to_send_tx = Some(snapshots_to_send_tx);
1372            });
1373
1374            Ok((share_response.worktree_id, share_response.access_token))
1375        })
1376    }
1377
1378    fn share_request(&self, cx: &mut ModelContext<Worktree>) -> Task<proto::ShareWorktree> {
1379        let snapshot = self.snapshot();
1380        let root_name = self.root_name.clone();
1381        cx.background().spawn(async move {
1382            let entries = snapshot
1383                .entries_by_path
1384                .cursor::<(), ()>()
1385                .map(Into::into)
1386                .collect();
1387            proto::ShareWorktree {
1388                worktree: Some(proto::Worktree { root_name, entries }),
1389            }
1390        })
1391    }
1392}
1393
1394pub fn refresh_buffer(abs_path: PathBuf, fs: &Arc<dyn Fs>, cx: &mut ModelContext<Buffer>) {
1395    let fs = fs.clone();
1396    cx.spawn(|buffer, mut cx| async move {
1397        let new_text = fs.load(&abs_path).await;
1398        match new_text {
1399            Err(error) => log::error!("error refreshing buffer after file changed: {}", error),
1400            Ok(new_text) => {
1401                buffer
1402                    .update(&mut cx, |buffer, cx| {
1403                        buffer.set_text_from_disk(new_text.into(), cx)
1404                    })
1405                    .await;
1406            }
1407        }
1408    })
1409    .detach()
1410}
1411
1412impl Deref for LocalWorktree {
1413    type Target = Snapshot;
1414
1415    fn deref(&self) -> &Self::Target {
1416        &self.snapshot
1417    }
1418}
1419
1420impl fmt::Debug for LocalWorktree {
1421    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1422        self.snapshot.fmt(f)
1423    }
1424}
1425
1426pub struct RemoteWorktree {
1427    remote_id: u64,
1428    snapshot: Snapshot,
1429    snapshot_rx: watch::Receiver<Snapshot>,
1430    rpc: rpc::Client,
1431    updates_tx: postage::mpsc::Sender<proto::UpdateWorktree>,
1432    replica_id: ReplicaId,
1433    open_buffers: HashMap<usize, RemoteBuffer>,
1434    peers: HashMap<PeerId, ReplicaId>,
1435    languages: Arc<LanguageRegistry>,
1436}
1437
1438impl RemoteWorktree {
1439    pub fn open_buffer(
1440        &mut self,
1441        path: &Path,
1442        cx: &mut ModelContext<Worktree>,
1443    ) -> Task<Result<ModelHandle<Buffer>>> {
1444        let handle = cx.handle();
1445        let mut existing_buffer = None;
1446        self.open_buffers.retain(|_buffer_id, buffer| {
1447            if let Some(buffer) = buffer.upgrade(cx.as_ref()) {
1448                if let Some(file) = buffer.read(cx.as_ref()).file() {
1449                    if file.worktree_id() == handle.id() && file.path.as_ref() == path {
1450                        existing_buffer = Some(buffer);
1451                    }
1452                }
1453                true
1454            } else {
1455                false
1456            }
1457        });
1458
1459        let rpc = self.rpc.clone();
1460        let languages = self.languages.clone();
1461        let replica_id = self.replica_id;
1462        let remote_worktree_id = self.remote_id;
1463        let path = path.to_string_lossy().to_string();
1464        cx.spawn(|this, mut cx| async move {
1465            if let Some(existing_buffer) = existing_buffer {
1466                Ok(existing_buffer)
1467            } else {
1468                let entry = this
1469                    .read_with(&cx, |tree, _| tree.entry_for_path(&path).cloned())
1470                    .ok_or_else(|| anyhow!("file does not exist"))?;
1471                let file = File::new(entry.id, handle, entry.path, entry.mtime);
1472                let language = languages.select_language(&path).cloned();
1473                let response = rpc
1474                    .request(proto::OpenBuffer {
1475                        worktree_id: remote_worktree_id as u64,
1476                        path,
1477                    })
1478                    .await?;
1479                let remote_buffer = response.buffer.ok_or_else(|| anyhow!("empty buffer"))?;
1480                let buffer_id = remote_buffer.id as usize;
1481                let buffer = cx.add_model(|cx| {
1482                    Buffer::from_proto(replica_id, remote_buffer, Some(file), language, cx).unwrap()
1483                });
1484                this.update(&mut cx, |this, cx| {
1485                    let this = this.as_remote_mut().unwrap();
1486                    if let Some(RemoteBuffer::Operations(pending_ops)) = this
1487                        .open_buffers
1488                        .insert(buffer_id, RemoteBuffer::Loaded(buffer.downgrade()))
1489                    {
1490                        buffer.update(cx, |buf, cx| buf.apply_ops(pending_ops, cx))?;
1491                    }
1492                    Result::<_, anyhow::Error>::Ok(())
1493                })?;
1494                Ok(buffer)
1495            }
1496        })
1497    }
1498
1499    fn snapshot(&self) -> Snapshot {
1500        self.snapshot.clone()
1501    }
1502
1503    pub fn add_peer(
1504        &mut self,
1505        envelope: TypedEnvelope<proto::AddPeer>,
1506        cx: &mut ModelContext<Worktree>,
1507    ) -> Result<()> {
1508        let peer = envelope.payload.peer.ok_or_else(|| anyhow!("empty peer"))?;
1509        self.peers
1510            .insert(PeerId(peer.peer_id), peer.replica_id as ReplicaId);
1511        cx.notify();
1512        Ok(())
1513    }
1514
1515    pub fn remove_peer(
1516        &mut self,
1517        envelope: TypedEnvelope<proto::RemovePeer>,
1518        cx: &mut ModelContext<Worktree>,
1519    ) -> Result<()> {
1520        let peer_id = PeerId(envelope.payload.peer_id);
1521        let replica_id = self
1522            .peers
1523            .remove(&peer_id)
1524            .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?;
1525        for (_, buffer) in &self.open_buffers {
1526            if let Some(buffer) = buffer.upgrade(&cx) {
1527                buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1528            }
1529        }
1530        cx.notify();
1531        Ok(())
1532    }
1533}
1534
1535enum RemoteBuffer {
1536    Operations(Vec<Operation>),
1537    Loaded(WeakModelHandle<Buffer>),
1538}
1539
1540impl RemoteBuffer {
1541    fn upgrade(&self, cx: impl AsRef<AppContext>) -> Option<ModelHandle<Buffer>> {
1542        match self {
1543            Self::Operations(_) => None,
1544            Self::Loaded(buffer) => buffer.upgrade(cx),
1545        }
1546    }
1547}
1548
1549#[derive(Clone)]
1550pub struct Snapshot {
1551    id: usize,
1552    scan_id: usize,
1553    abs_path: Arc<Path>,
1554    root_name: String,
1555    root_char_bag: CharBag,
1556    ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
1557    entries_by_path: SumTree<Entry>,
1558    entries_by_id: SumTree<PathEntry>,
1559    removed_entry_ids: HashMap<u64, usize>,
1560    next_entry_id: Arc<AtomicUsize>,
1561}
1562
1563impl Snapshot {
1564    pub fn build_update(&self, other: &Self, worktree_id: u64) -> proto::UpdateWorktree {
1565        let mut updated_entries = Vec::new();
1566        let mut removed_entries = Vec::new();
1567        let mut self_entries = self.entries_by_id.cursor::<(), ()>().peekable();
1568        let mut other_entries = other.entries_by_id.cursor::<(), ()>().peekable();
1569        loop {
1570            match (self_entries.peek(), other_entries.peek()) {
1571                (Some(self_entry), Some(other_entry)) => match self_entry.id.cmp(&other_entry.id) {
1572                    Ordering::Less => {
1573                        let entry = self.entry_for_id(self_entry.id).unwrap().into();
1574                        updated_entries.push(entry);
1575                        self_entries.next();
1576                    }
1577                    Ordering::Equal => {
1578                        if self_entry.scan_id != other_entry.scan_id {
1579                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1580                            updated_entries.push(entry);
1581                        }
1582
1583                        self_entries.next();
1584                        other_entries.next();
1585                    }
1586                    Ordering::Greater => {
1587                        removed_entries.push(other_entry.id as u64);
1588                        other_entries.next();
1589                    }
1590                },
1591                (Some(self_entry), None) => {
1592                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1593                    updated_entries.push(entry);
1594                    self_entries.next();
1595                }
1596                (None, Some(other_entry)) => {
1597                    removed_entries.push(other_entry.id as u64);
1598                    other_entries.next();
1599                }
1600                (None, None) => break,
1601            }
1602        }
1603
1604        proto::UpdateWorktree {
1605            updated_entries,
1606            removed_entries,
1607            worktree_id,
1608        }
1609    }
1610
1611    fn apply_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1612        self.scan_id += 1;
1613        let scan_id = self.scan_id;
1614
1615        let mut entries_by_path_edits = Vec::new();
1616        let mut entries_by_id_edits = Vec::new();
1617        for entry_id in update.removed_entries {
1618            let entry_id = entry_id as usize;
1619            let entry = self
1620                .entry_for_id(entry_id)
1621                .ok_or_else(|| anyhow!("unknown entry"))?;
1622            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1623            entries_by_id_edits.push(Edit::Remove(entry.id));
1624        }
1625
1626        for entry in update.updated_entries {
1627            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1628            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1629                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1630            }
1631            entries_by_id_edits.push(Edit::Insert(PathEntry {
1632                id: entry.id,
1633                path: entry.path.clone(),
1634                scan_id,
1635            }));
1636            entries_by_path_edits.push(Edit::Insert(entry));
1637        }
1638
1639        self.entries_by_path.edit(entries_by_path_edits, &());
1640        self.entries_by_id.edit(entries_by_id_edits, &());
1641
1642        Ok(())
1643    }
1644
1645    pub fn file_count(&self) -> usize {
1646        self.entries_by_path.summary().file_count
1647    }
1648
1649    pub fn visible_file_count(&self) -> usize {
1650        self.entries_by_path.summary().visible_file_count
1651    }
1652
1653    pub fn files(&self, start: usize) -> FileIter {
1654        FileIter::all(self, start)
1655    }
1656
1657    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1658        let empty_path = Path::new("");
1659        self.entries_by_path
1660            .cursor::<(), ()>()
1661            .filter(move |entry| entry.path.as_ref() != empty_path)
1662            .map(|entry| entry.path())
1663    }
1664
1665    pub fn visible_files(&self, start: usize) -> FileIter {
1666        FileIter::visible(self, start)
1667    }
1668
1669    fn child_entries<'a>(&'a self, path: &'a Path) -> ChildEntriesIter<'a> {
1670        ChildEntriesIter::new(path, self)
1671    }
1672
1673    pub fn root_entry(&self) -> &Entry {
1674        self.entry_for_path("").unwrap()
1675    }
1676
1677    /// Returns the filename of the snapshot's root, plus a trailing slash if the snapshot's root is
1678    /// a directory.
1679    pub fn root_name(&self) -> &str {
1680        &self.root_name
1681    }
1682
1683    fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1684        let mut cursor = self.entries_by_path.cursor::<_, ()>();
1685        if cursor.seek(&PathSearch::Exact(path.as_ref()), Bias::Left, &()) {
1686            cursor.item()
1687        } else {
1688            None
1689        }
1690    }
1691
1692    fn entry_for_id(&self, id: usize) -> Option<&Entry> {
1693        let entry = self.entries_by_id.get(&id, &())?;
1694        self.entry_for_path(&entry.path)
1695    }
1696
1697    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1698        self.entry_for_path(path.as_ref()).map(|e| e.inode())
1699    }
1700
1701    fn insert_entry(&mut self, mut entry: Entry) -> Entry {
1702        if !entry.is_dir() && entry.path().file_name() == Some(&GITIGNORE) {
1703            let (ignore, err) = Gitignore::new(self.abs_path.join(entry.path()));
1704            if let Some(err) = err {
1705                log::error!("error in ignore file {:?} - {:?}", entry.path(), err);
1706            }
1707
1708            let ignore_dir_path = entry.path().parent().unwrap();
1709            self.ignores
1710                .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1711        }
1712
1713        self.reuse_entry_id(&mut entry);
1714        self.entries_by_path.insert_or_replace(entry.clone(), &());
1715        self.entries_by_id.insert_or_replace(
1716            PathEntry {
1717                id: entry.id,
1718                path: entry.path.clone(),
1719                scan_id: self.scan_id,
1720            },
1721            &(),
1722        );
1723        entry
1724    }
1725
1726    fn populate_dir(
1727        &mut self,
1728        parent_path: Arc<Path>,
1729        entries: impl IntoIterator<Item = Entry>,
1730        ignore: Option<Arc<Gitignore>>,
1731    ) {
1732        let mut parent_entry = self
1733            .entries_by_path
1734            .get(&PathKey(parent_path.clone()), &())
1735            .unwrap()
1736            .clone();
1737        if let Some(ignore) = ignore {
1738            self.ignores.insert(parent_path, (ignore, self.scan_id));
1739        }
1740        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1741            parent_entry.kind = EntryKind::Dir;
1742        } else {
1743            unreachable!();
1744        }
1745
1746        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1747        let mut entries_by_id_edits = Vec::new();
1748
1749        for mut entry in entries {
1750            self.reuse_entry_id(&mut entry);
1751            entries_by_id_edits.push(Edit::Insert(PathEntry {
1752                id: entry.id,
1753                path: entry.path.clone(),
1754                scan_id: self.scan_id,
1755            }));
1756            entries_by_path_edits.push(Edit::Insert(entry));
1757        }
1758
1759        self.entries_by_path.edit(entries_by_path_edits, &());
1760        self.entries_by_id.edit(entries_by_id_edits, &());
1761    }
1762
1763    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1764        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1765            entry.id = removed_entry_id;
1766        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1767            entry.id = existing_entry.id;
1768        }
1769    }
1770
1771    fn remove_path(&mut self, path: &Path) {
1772        let mut new_entries;
1773        let removed_entry_ids;
1774        {
1775            let mut cursor = self.entries_by_path.cursor::<_, ()>();
1776            new_entries = cursor.slice(&PathSearch::Exact(path), Bias::Left, &());
1777            removed_entry_ids = cursor.slice(&PathSearch::Successor(path), Bias::Left, &());
1778            new_entries.push_tree(cursor.suffix(&()), &());
1779        }
1780        self.entries_by_path = new_entries;
1781
1782        let mut entries_by_id_edits = Vec::new();
1783        for entry in removed_entry_ids.cursor::<(), ()>() {
1784            let removed_entry_id = self
1785                .removed_entry_ids
1786                .entry(entry.inode)
1787                .or_insert(entry.id);
1788            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1789            entries_by_id_edits.push(Edit::Remove(entry.id));
1790        }
1791        self.entries_by_id.edit(entries_by_id_edits, &());
1792
1793        if path.file_name() == Some(&GITIGNORE) {
1794            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1795                *scan_id = self.scan_id;
1796            }
1797        }
1798    }
1799
1800    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1801        let mut new_ignores = Vec::new();
1802        for ancestor in path.ancestors().skip(1) {
1803            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1804                new_ignores.push((ancestor, Some(ignore.clone())));
1805            } else {
1806                new_ignores.push((ancestor, None));
1807            }
1808        }
1809
1810        let mut ignore_stack = IgnoreStack::none();
1811        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1812            if ignore_stack.is_path_ignored(&parent_path, true) {
1813                ignore_stack = IgnoreStack::all();
1814                break;
1815            } else if let Some(ignore) = ignore {
1816                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1817            }
1818        }
1819
1820        if ignore_stack.is_path_ignored(path, is_dir) {
1821            ignore_stack = IgnoreStack::all();
1822        }
1823
1824        ignore_stack
1825    }
1826}
1827
1828impl fmt::Debug for Snapshot {
1829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1830        for entry in self.entries_by_path.cursor::<(), ()>() {
1831            for _ in entry.path().ancestors().skip(1) {
1832                write!(f, " ")?;
1833            }
1834            writeln!(f, "{:?} (inode: {})", entry.path(), entry.inode())?;
1835        }
1836        Ok(())
1837    }
1838}
1839
1840#[derive(Clone, PartialEq)]
1841pub struct File {
1842    entry_id: Option<usize>,
1843    worktree: ModelHandle<Worktree>,
1844    pub path: Arc<Path>,
1845    pub mtime: SystemTime,
1846}
1847
1848impl File {
1849    pub fn new(
1850        entry_id: usize,
1851        worktree: ModelHandle<Worktree>,
1852        path: Arc<Path>,
1853        mtime: SystemTime,
1854    ) -> Self {
1855        Self {
1856            entry_id: Some(entry_id),
1857            worktree,
1858            path,
1859            mtime,
1860        }
1861    }
1862
1863    pub fn buffer_updated(&self, buffer_id: u64, operation: Operation, cx: &mut MutableAppContext) {
1864        self.worktree.update(cx, |worktree, cx| {
1865            if let Some((rpc, remote_id)) = match worktree {
1866                Worktree::Local(worktree) => worktree.rpc.clone(),
1867                Worktree::Remote(worktree) => Some((worktree.rpc.clone(), worktree.remote_id)),
1868            } {
1869                cx.spawn(|_, _| async move {
1870                    if let Err(error) = rpc
1871                        .send(proto::UpdateBuffer {
1872                            worktree_id: remote_id,
1873                            buffer_id,
1874                            operations: Some(operation).iter().map(Into::into).collect(),
1875                        })
1876                        .await
1877                    {
1878                        log::error!("error sending buffer operation: {}", error);
1879                    }
1880                })
1881                .detach();
1882            }
1883        });
1884    }
1885
1886    pub fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext) {
1887        self.worktree.update(cx, |worktree, cx| {
1888            if let Worktree::Remote(worktree) = worktree {
1889                let worktree_id = worktree.remote_id;
1890                let rpc = worktree.rpc.clone();
1891                cx.background()
1892                    .spawn(async move {
1893                        if let Err(error) = rpc
1894                            .send(proto::CloseBuffer {
1895                                worktree_id,
1896                                buffer_id,
1897                            })
1898                            .await
1899                        {
1900                            log::error!("error closing remote buffer: {}", error);
1901                        };
1902                    })
1903                    .detach();
1904            }
1905        });
1906    }
1907
1908    /// Returns this file's path relative to the root of its worktree.
1909    pub fn path(&self) -> Arc<Path> {
1910        self.path.clone()
1911    }
1912
1913    pub fn abs_path(&self, cx: &AppContext) -> PathBuf {
1914        self.worktree.read(cx).abs_path.join(&self.path)
1915    }
1916
1917    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1918    /// of its worktree, then this method will return the name of the worktree itself.
1919    pub fn file_name<'a>(&'a self, cx: &'a AppContext) -> Option<OsString> {
1920        dbg!(self.path.file_name())
1921            .or_else(|| Some(OsStr::new(dbg!(self.worktree.read(cx).root_name()))))
1922            .map(Into::into)
1923    }
1924
1925    pub fn is_deleted(&self) -> bool {
1926        self.entry_id.is_none()
1927    }
1928
1929    pub fn exists(&self) -> bool {
1930        !self.is_deleted()
1931    }
1932
1933    pub fn save(
1934        &self,
1935        buffer_id: u64,
1936        text: Rope,
1937        version: time::Global,
1938        cx: &mut MutableAppContext,
1939    ) -> Task<Result<(time::Global, SystemTime)>> {
1940        self.worktree.update(cx, |worktree, cx| match worktree {
1941            Worktree::Local(worktree) => {
1942                let rpc = worktree.rpc.clone();
1943                let save = worktree.save(self.path.clone(), text, cx);
1944                cx.spawn(|_, _| async move {
1945                    let entry = save.await?;
1946                    if let Some((rpc, worktree_id)) = rpc {
1947                        rpc.send(proto::BufferSaved {
1948                            worktree_id,
1949                            buffer_id,
1950                            version: (&version).into(),
1951                            mtime: Some(entry.mtime.into()),
1952                        })
1953                        .await?;
1954                    }
1955                    Ok((version, entry.mtime))
1956                })
1957            }
1958            Worktree::Remote(worktree) => {
1959                let rpc = worktree.rpc.clone();
1960                let worktree_id = worktree.remote_id;
1961                cx.spawn(|_, _| async move {
1962                    let response = rpc
1963                        .request(proto::SaveBuffer {
1964                            worktree_id,
1965                            buffer_id,
1966                        })
1967                        .await?;
1968                    let version = response.version.try_into()?;
1969                    let mtime = response
1970                        .mtime
1971                        .ok_or_else(|| anyhow!("missing mtime"))?
1972                        .into();
1973                    Ok((version, mtime))
1974                })
1975            }
1976        })
1977    }
1978
1979    pub fn worktree_id(&self) -> usize {
1980        self.worktree.id()
1981    }
1982
1983    pub fn entry_id(&self) -> (usize, Arc<Path>) {
1984        (self.worktree.id(), self.path())
1985    }
1986}
1987
1988#[derive(Clone, Debug)]
1989pub struct Entry {
1990    id: usize,
1991    kind: EntryKind,
1992    path: Arc<Path>,
1993    inode: u64,
1994    mtime: SystemTime,
1995    is_symlink: bool,
1996    is_ignored: bool,
1997}
1998
1999#[derive(Clone, Debug)]
2000pub enum EntryKind {
2001    PendingDir,
2002    Dir,
2003    File(CharBag),
2004}
2005
2006impl Entry {
2007    pub fn path(&self) -> &Arc<Path> {
2008        &self.path
2009    }
2010
2011    pub fn inode(&self) -> u64 {
2012        self.inode
2013    }
2014
2015    pub fn is_ignored(&self) -> bool {
2016        self.is_ignored
2017    }
2018
2019    fn is_dir(&self) -> bool {
2020        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2021    }
2022
2023    fn is_file(&self) -> bool {
2024        matches!(self.kind, EntryKind::File(_))
2025    }
2026}
2027
2028impl sum_tree::Item for Entry {
2029    type Summary = EntrySummary;
2030
2031    fn summary(&self) -> Self::Summary {
2032        let file_count;
2033        let visible_file_count;
2034        if self.is_file() {
2035            file_count = 1;
2036            if self.is_ignored {
2037                visible_file_count = 0;
2038            } else {
2039                visible_file_count = 1;
2040            }
2041        } else {
2042            file_count = 0;
2043            visible_file_count = 0;
2044        }
2045
2046        EntrySummary {
2047            max_path: self.path().clone(),
2048            file_count,
2049            visible_file_count,
2050        }
2051    }
2052}
2053
2054impl sum_tree::KeyedItem for Entry {
2055    type Key = PathKey;
2056
2057    fn key(&self) -> Self::Key {
2058        PathKey(self.path().clone())
2059    }
2060}
2061
2062#[derive(Clone, Debug)]
2063pub struct EntrySummary {
2064    max_path: Arc<Path>,
2065    file_count: usize,
2066    visible_file_count: usize,
2067}
2068
2069impl Default for EntrySummary {
2070    fn default() -> Self {
2071        Self {
2072            max_path: Arc::from(Path::new("")),
2073            file_count: 0,
2074            visible_file_count: 0,
2075        }
2076    }
2077}
2078
2079impl sum_tree::Summary for EntrySummary {
2080    type Context = ();
2081
2082    fn add_summary(&mut self, rhs: &Self, _: &()) {
2083        self.max_path = rhs.max_path.clone();
2084        self.file_count += rhs.file_count;
2085        self.visible_file_count += rhs.visible_file_count;
2086    }
2087}
2088
2089#[derive(Clone, Debug)]
2090struct PathEntry {
2091    id: usize,
2092    path: Arc<Path>,
2093    scan_id: usize,
2094}
2095
2096impl sum_tree::Item for PathEntry {
2097    type Summary = PathEntrySummary;
2098
2099    fn summary(&self) -> Self::Summary {
2100        PathEntrySummary { max_id: self.id }
2101    }
2102}
2103
2104impl sum_tree::KeyedItem for PathEntry {
2105    type Key = usize;
2106
2107    fn key(&self) -> Self::Key {
2108        self.id
2109    }
2110}
2111
2112#[derive(Clone, Debug, Default)]
2113struct PathEntrySummary {
2114    max_id: usize,
2115}
2116
2117impl sum_tree::Summary for PathEntrySummary {
2118    type Context = ();
2119
2120    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2121        self.max_id = summary.max_id;
2122    }
2123}
2124
2125impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for usize {
2126    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2127        *self = summary.max_id;
2128    }
2129}
2130
2131#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2132pub struct PathKey(Arc<Path>);
2133
2134impl Default for PathKey {
2135    fn default() -> Self {
2136        Self(Path::new("").into())
2137    }
2138}
2139
2140impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2141    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2142        self.0 = summary.max_path.clone();
2143    }
2144}
2145
2146#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2147enum PathSearch<'a> {
2148    Exact(&'a Path),
2149    Successor(&'a Path),
2150}
2151
2152impl<'a> Ord for PathSearch<'a> {
2153    fn cmp(&self, other: &Self) -> cmp::Ordering {
2154        match (self, other) {
2155            (Self::Exact(a), Self::Exact(b)) => a.cmp(b),
2156            (Self::Successor(a), Self::Exact(b)) => {
2157                if b.starts_with(a) {
2158                    cmp::Ordering::Greater
2159                } else {
2160                    a.cmp(b)
2161                }
2162            }
2163            _ => unreachable!("not sure we need the other two cases"),
2164        }
2165    }
2166}
2167
2168impl<'a> PartialOrd for PathSearch<'a> {
2169    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2170        Some(self.cmp(other))
2171    }
2172}
2173
2174impl<'a> Default for PathSearch<'a> {
2175    fn default() -> Self {
2176        Self::Exact(Path::new("").into())
2177    }
2178}
2179
2180impl<'a: 'b, 'b> sum_tree::Dimension<'a, EntrySummary> for PathSearch<'b> {
2181    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2182        *self = Self::Exact(summary.max_path.as_ref());
2183    }
2184}
2185
2186#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Ord, PartialOrd)]
2187pub struct FileCount(usize);
2188
2189impl<'a> sum_tree::Dimension<'a, EntrySummary> for FileCount {
2190    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2191        self.0 += summary.file_count;
2192    }
2193}
2194
2195#[derive(Copy, Clone, Default, Debug, Eq, PartialEq, Ord, PartialOrd)]
2196pub struct VisibleFileCount(usize);
2197
2198impl<'a> sum_tree::Dimension<'a, EntrySummary> for VisibleFileCount {
2199    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2200        self.0 += summary.visible_file_count;
2201    }
2202}
2203
2204struct BackgroundScanner {
2205    fs: Arc<dyn Fs>,
2206    snapshot: Arc<Mutex<Snapshot>>,
2207    notify: Sender<ScanState>,
2208    executor: Arc<executor::Background>,
2209}
2210
2211impl BackgroundScanner {
2212    fn new(
2213        snapshot: Arc<Mutex<Snapshot>>,
2214        notify: Sender<ScanState>,
2215        fs: Arc<dyn Fs>,
2216        executor: Arc<executor::Background>,
2217    ) -> Self {
2218        Self {
2219            fs,
2220            snapshot,
2221            notify,
2222            executor,
2223        }
2224    }
2225
2226    fn abs_path(&self) -> Arc<Path> {
2227        self.snapshot.lock().abs_path.clone()
2228    }
2229
2230    fn snapshot(&self) -> Snapshot {
2231        self.snapshot.lock().clone()
2232    }
2233
2234    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2235        if self.notify.send(ScanState::Scanning).await.is_err() {
2236            return;
2237        }
2238
2239        if let Err(err) = self.scan_dirs().await {
2240            if self
2241                .notify
2242                .send(ScanState::Err(Arc::new(err)))
2243                .await
2244                .is_err()
2245            {
2246                return;
2247            }
2248        }
2249
2250        if self.notify.send(ScanState::Idle).await.is_err() {
2251            return;
2252        }
2253
2254        futures::pin_mut!(events_rx);
2255        while let Some(events) = events_rx.next().await {
2256            if self.notify.send(ScanState::Scanning).await.is_err() {
2257                break;
2258            }
2259
2260            if !self.process_events(events).await {
2261                break;
2262            }
2263
2264            if self.notify.send(ScanState::Idle).await.is_err() {
2265                break;
2266            }
2267        }
2268    }
2269
2270    async fn scan_dirs(&mut self) -> Result<()> {
2271        let root_char_bag;
2272        let next_entry_id;
2273        let is_dir;
2274        {
2275            let snapshot = self.snapshot.lock();
2276            root_char_bag = snapshot.root_char_bag;
2277            next_entry_id = snapshot.next_entry_id.clone();
2278            is_dir = snapshot.root_entry().is_dir();
2279        }
2280
2281        if is_dir {
2282            let path: Arc<Path> = Arc::from(Path::new(""));
2283            let abs_path = self.abs_path();
2284            let (tx, rx) = channel::unbounded();
2285            tx.send(ScanJob {
2286                abs_path: abs_path.to_path_buf(),
2287                path,
2288                ignore_stack: IgnoreStack::none(),
2289                scan_queue: tx.clone(),
2290            })
2291            .await
2292            .unwrap();
2293            drop(tx);
2294
2295            self.executor
2296                .scoped(|scope| {
2297                    for _ in 0..self.executor.threads() {
2298                        scope.spawn(async {
2299                            while let Ok(job) = rx.recv().await {
2300                                if let Err(err) = self
2301                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2302                                    .await
2303                                {
2304                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2305                                }
2306                            }
2307                        });
2308                    }
2309                })
2310                .await;
2311        }
2312
2313        Ok(())
2314    }
2315
2316    async fn scan_dir(
2317        &self,
2318        root_char_bag: CharBag,
2319        next_entry_id: Arc<AtomicUsize>,
2320        job: &ScanJob,
2321    ) -> Result<()> {
2322        let mut new_entries: Vec<Entry> = Vec::new();
2323        let mut new_jobs: Vec<ScanJob> = Vec::new();
2324        let mut ignore_stack = job.ignore_stack.clone();
2325        let mut new_ignore = None;
2326
2327        let mut child_entries = self
2328            .fs
2329            .child_entries(
2330                root_char_bag,
2331                next_entry_id.as_ref(),
2332                &job.path,
2333                &job.abs_path,
2334            )
2335            .await?;
2336        while let Some(child_entry) = child_entries.next().await {
2337            let mut child_entry = match child_entry {
2338                Ok(child_entry) => child_entry,
2339                Err(error) => {
2340                    log::error!("error processing entry {:?}", error);
2341                    continue;
2342                }
2343            };
2344            let child_name = child_entry.path.file_name().unwrap();
2345            let child_abs_path = job.abs_path.join(&child_name);
2346            let child_path = child_entry.path.clone();
2347
2348            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2349            if child_name == *GITIGNORE {
2350                let (ignore, err) = Gitignore::new(&child_abs_path);
2351                if let Some(err) = err {
2352                    log::error!("error in ignore file {:?} - {:?}", child_entry.path, err);
2353                }
2354                let ignore = Arc::new(ignore);
2355                ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2356                new_ignore = Some(ignore);
2357
2358                // Update ignore status of any child entries we've already processed to reflect the
2359                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2360                // there should rarely be too numerous. Update the ignore stack associated with any
2361                // new jobs as well.
2362                let mut new_jobs = new_jobs.iter_mut();
2363                for entry in &mut new_entries {
2364                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2365                    if entry.is_dir() {
2366                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2367                            IgnoreStack::all()
2368                        } else {
2369                            ignore_stack.clone()
2370                        };
2371                    }
2372                }
2373            }
2374
2375            if child_entry.is_dir() {
2376                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2377                child_entry.is_ignored = is_ignored;
2378                new_entries.push(child_entry);
2379                new_jobs.push(ScanJob {
2380                    abs_path: child_abs_path,
2381                    path: child_path,
2382                    ignore_stack: if is_ignored {
2383                        IgnoreStack::all()
2384                    } else {
2385                        ignore_stack.clone()
2386                    },
2387                    scan_queue: job.scan_queue.clone(),
2388                });
2389            } else {
2390                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2391                new_entries.push(child_entry);
2392            };
2393        }
2394
2395        self.snapshot
2396            .lock()
2397            .populate_dir(job.path.clone(), new_entries, new_ignore);
2398        for new_job in new_jobs {
2399            job.scan_queue.send(new_job).await.unwrap();
2400        }
2401
2402        Ok(())
2403    }
2404
2405    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2406        let mut snapshot = self.snapshot();
2407        snapshot.scan_id += 1;
2408
2409        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
2410            abs_path
2411        } else {
2412            return false;
2413        };
2414        let root_char_bag = snapshot.root_char_bag;
2415        let next_entry_id = snapshot.next_entry_id.clone();
2416
2417        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2418        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2419
2420        for event in &events {
2421            match event.path.strip_prefix(&root_abs_path) {
2422                Ok(path) => snapshot.remove_path(&path),
2423                Err(_) => {
2424                    log::error!(
2425                        "unexpected event {:?} for root path {:?}",
2426                        event.path,
2427                        root_abs_path
2428                    );
2429                    continue;
2430                }
2431            }
2432        }
2433
2434        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2435        for event in events {
2436            let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2437                Ok(path) => Arc::from(path.to_path_buf()),
2438                Err(_) => {
2439                    log::error!(
2440                        "unexpected event {:?} for root path {:?}",
2441                        event.path,
2442                        root_abs_path
2443                    );
2444                    continue;
2445                }
2446            };
2447
2448            match self
2449                .fs
2450                .entry(
2451                    snapshot.root_char_bag,
2452                    &next_entry_id,
2453                    path.clone(),
2454                    &event.path,
2455                )
2456                .await
2457            {
2458                Ok(Some(mut fs_entry)) => {
2459                    let is_dir = fs_entry.is_dir();
2460                    let ignore_stack = snapshot.ignore_stack_for_path(&path, is_dir);
2461                    fs_entry.is_ignored = ignore_stack.is_all();
2462                    snapshot.insert_entry(fs_entry);
2463                    if is_dir {
2464                        scan_queue_tx
2465                            .send(ScanJob {
2466                                abs_path: event.path,
2467                                path,
2468                                ignore_stack,
2469                                scan_queue: scan_queue_tx.clone(),
2470                            })
2471                            .await
2472                            .unwrap();
2473                    }
2474                }
2475                Ok(None) => {}
2476                Err(err) => {
2477                    // TODO - create a special 'error' entry in the entries tree to mark this
2478                    log::error!("error reading file on event {:?}", err);
2479                }
2480            }
2481        }
2482
2483        *self.snapshot.lock() = snapshot;
2484
2485        // Scan any directories that were created as part of this event batch.
2486        drop(scan_queue_tx);
2487        self.executor
2488            .scoped(|scope| {
2489                for _ in 0..self.executor.threads() {
2490                    scope.spawn(async {
2491                        while let Ok(job) = scan_queue_rx.recv().await {
2492                            if let Err(err) = self
2493                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2494                                .await
2495                            {
2496                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2497                            }
2498                        }
2499                    });
2500                }
2501            })
2502            .await;
2503
2504        // Attempt to detect renames only over a single batch of file-system events.
2505        self.snapshot.lock().removed_entry_ids.clear();
2506
2507        self.update_ignore_statuses().await;
2508        true
2509    }
2510
2511    async fn update_ignore_statuses(&self) {
2512        let mut snapshot = self.snapshot();
2513
2514        let mut ignores_to_update = Vec::new();
2515        let mut ignores_to_delete = Vec::new();
2516        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2517            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2518                ignores_to_update.push(parent_path.clone());
2519            }
2520
2521            let ignore_path = parent_path.join(&*GITIGNORE);
2522            if snapshot.entry_for_path(ignore_path).is_none() {
2523                ignores_to_delete.push(parent_path.clone());
2524            }
2525        }
2526
2527        for parent_path in ignores_to_delete {
2528            snapshot.ignores.remove(&parent_path);
2529            self.snapshot.lock().ignores.remove(&parent_path);
2530        }
2531
2532        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2533        ignores_to_update.sort_unstable();
2534        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2535        while let Some(parent_path) = ignores_to_update.next() {
2536            while ignores_to_update
2537                .peek()
2538                .map_or(false, |p| p.starts_with(&parent_path))
2539            {
2540                ignores_to_update.next().unwrap();
2541            }
2542
2543            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2544            ignore_queue_tx
2545                .send(UpdateIgnoreStatusJob {
2546                    path: parent_path,
2547                    ignore_stack,
2548                    ignore_queue: ignore_queue_tx.clone(),
2549                })
2550                .await
2551                .unwrap();
2552        }
2553        drop(ignore_queue_tx);
2554
2555        self.executor
2556            .scoped(|scope| {
2557                for _ in 0..self.executor.threads() {
2558                    scope.spawn(async {
2559                        while let Ok(job) = ignore_queue_rx.recv().await {
2560                            self.update_ignore_status(job, &snapshot).await;
2561                        }
2562                    });
2563                }
2564            })
2565            .await;
2566    }
2567
2568    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &Snapshot) {
2569        let mut ignore_stack = job.ignore_stack;
2570        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2571            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2572        }
2573
2574        let mut edits = Vec::new();
2575        for mut entry in snapshot.child_entries(&job.path).cloned() {
2576            let was_ignored = entry.is_ignored;
2577            entry.is_ignored = ignore_stack.is_path_ignored(entry.path(), entry.is_dir());
2578            if entry.is_dir() {
2579                let child_ignore_stack = if entry.is_ignored {
2580                    IgnoreStack::all()
2581                } else {
2582                    ignore_stack.clone()
2583                };
2584                job.ignore_queue
2585                    .send(UpdateIgnoreStatusJob {
2586                        path: entry.path().clone(),
2587                        ignore_stack: child_ignore_stack,
2588                        ignore_queue: job.ignore_queue.clone(),
2589                    })
2590                    .await
2591                    .unwrap();
2592            }
2593
2594            if entry.is_ignored != was_ignored {
2595                edits.push(Edit::Insert(entry));
2596            }
2597        }
2598        self.snapshot.lock().entries_by_path.edit(edits, &());
2599    }
2600}
2601
2602async fn refresh_entry(
2603    fs: &dyn Fs,
2604    snapshot: &Mutex<Snapshot>,
2605    path: Arc<Path>,
2606    abs_path: &Path,
2607) -> Result<Entry> {
2608    let root_char_bag;
2609    let next_entry_id;
2610    {
2611        let snapshot = snapshot.lock();
2612        root_char_bag = snapshot.root_char_bag;
2613        next_entry_id = snapshot.next_entry_id.clone();
2614    }
2615    let entry = fs
2616        .entry(root_char_bag, &next_entry_id, path, abs_path)
2617        .await?
2618        .ok_or_else(|| anyhow!("could not read saved file metadata"))?;
2619    Ok(snapshot.lock().insert_entry(entry))
2620}
2621
2622fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2623    let mut result = root_char_bag;
2624    result.extend(
2625        path.to_string_lossy()
2626            .chars()
2627            .map(|c| c.to_ascii_lowercase()),
2628    );
2629    result
2630}
2631
2632struct ScanJob {
2633    abs_path: PathBuf,
2634    path: Arc<Path>,
2635    ignore_stack: Arc<IgnoreStack>,
2636    scan_queue: Sender<ScanJob>,
2637}
2638
2639struct UpdateIgnoreStatusJob {
2640    path: Arc<Path>,
2641    ignore_stack: Arc<IgnoreStack>,
2642    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2643}
2644
2645pub trait WorktreeHandle {
2646    #[cfg(test)]
2647    fn flush_fs_events<'a>(
2648        &self,
2649        cx: &'a gpui::TestAppContext,
2650    ) -> futures::future::LocalBoxFuture<'a, ()>;
2651}
2652
2653impl WorktreeHandle for ModelHandle<Worktree> {
2654    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2655    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2656    // extra directory scans, and emit extra scan-state notifications.
2657    //
2658    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2659    // to ensure that all redundant FS events have already been processed.
2660    #[cfg(test)]
2661    fn flush_fs_events<'a>(
2662        &self,
2663        cx: &'a gpui::TestAppContext,
2664    ) -> futures::future::LocalBoxFuture<'a, ()> {
2665        use smol::future::FutureExt;
2666
2667        let filename = "fs-event-sentinel";
2668        let root_path = cx.read(|cx| self.read(cx).abs_path.clone());
2669        let tree = self.clone();
2670        async move {
2671            std::fs::write(root_path.join(filename), "").unwrap();
2672            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2673                .await;
2674
2675            std::fs::remove_file(root_path.join(filename)).unwrap();
2676            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2677                .await;
2678
2679            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2680                .await;
2681        }
2682        .boxed_local()
2683    }
2684}
2685
2686pub enum FileIter<'a> {
2687    All(Cursor<'a, Entry, FileCount, ()>),
2688    Visible(Cursor<'a, Entry, VisibleFileCount, ()>),
2689}
2690
2691impl<'a> FileIter<'a> {
2692    fn all(snapshot: &'a Snapshot, start: usize) -> Self {
2693        let mut cursor = snapshot.entries_by_path.cursor();
2694        cursor.seek(&FileCount(start), Bias::Right, &());
2695        Self::All(cursor)
2696    }
2697
2698    fn visible(snapshot: &'a Snapshot, start: usize) -> Self {
2699        let mut cursor = snapshot.entries_by_path.cursor();
2700        cursor.seek(&VisibleFileCount(start), Bias::Right, &());
2701        Self::Visible(cursor)
2702    }
2703
2704    fn next_internal(&mut self) {
2705        match self {
2706            Self::All(cursor) => {
2707                let ix = *cursor.seek_start();
2708                cursor.seek_forward(&FileCount(ix.0 + 1), Bias::Right, &());
2709            }
2710            Self::Visible(cursor) => {
2711                let ix = *cursor.seek_start();
2712                cursor.seek_forward(&VisibleFileCount(ix.0 + 1), Bias::Right, &());
2713            }
2714        }
2715    }
2716
2717    fn item(&self) -> Option<&'a Entry> {
2718        match self {
2719            Self::All(cursor) => cursor.item(),
2720            Self::Visible(cursor) => cursor.item(),
2721        }
2722    }
2723}
2724
2725impl<'a> Iterator for FileIter<'a> {
2726    type Item = &'a Entry;
2727
2728    fn next(&mut self) -> Option<Self::Item> {
2729        if let Some(entry) = self.item() {
2730            self.next_internal();
2731            Some(entry)
2732        } else {
2733            None
2734        }
2735    }
2736}
2737
2738struct ChildEntriesIter<'a> {
2739    parent_path: &'a Path,
2740    cursor: Cursor<'a, Entry, PathSearch<'a>, ()>,
2741}
2742
2743impl<'a> ChildEntriesIter<'a> {
2744    fn new(parent_path: &'a Path, snapshot: &'a Snapshot) -> Self {
2745        let mut cursor = snapshot.entries_by_path.cursor();
2746        cursor.seek(&PathSearch::Exact(parent_path), Bias::Right, &());
2747        Self {
2748            parent_path,
2749            cursor,
2750        }
2751    }
2752}
2753
2754impl<'a> Iterator for ChildEntriesIter<'a> {
2755    type Item = &'a Entry;
2756
2757    fn next(&mut self) -> Option<Self::Item> {
2758        if let Some(item) = self.cursor.item() {
2759            if item.path().starts_with(self.parent_path) {
2760                self.cursor
2761                    .seek_forward(&PathSearch::Successor(item.path()), Bias::Left, &());
2762                Some(item)
2763            } else {
2764                None
2765            }
2766        } else {
2767            None
2768        }
2769    }
2770}
2771
2772impl<'a> From<&'a Entry> for proto::Entry {
2773    fn from(entry: &'a Entry) -> Self {
2774        Self {
2775            id: entry.id as u64,
2776            is_dir: entry.is_dir(),
2777            path: entry.path.to_string_lossy().to_string(),
2778            inode: entry.inode,
2779            mtime: Some(entry.mtime.into()),
2780            is_symlink: entry.is_symlink,
2781            is_ignored: entry.is_ignored,
2782        }
2783    }
2784}
2785
2786impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2787    type Error = anyhow::Error;
2788
2789    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2790        if let Some(mtime) = entry.mtime {
2791            let kind = if entry.is_dir {
2792                EntryKind::Dir
2793            } else {
2794                let mut char_bag = root_char_bag.clone();
2795                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2796                EntryKind::File(char_bag)
2797            };
2798            let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2799            Ok(Entry {
2800                id: entry.id as usize,
2801                kind,
2802                path: path.clone(),
2803                inode: entry.inode,
2804                mtime: mtime.into(),
2805                is_symlink: entry.is_symlink,
2806                is_ignored: entry.is_ignored,
2807            })
2808        } else {
2809            Err(anyhow!(
2810                "missing mtime in remote worktree entry {:?}",
2811                entry.path
2812            ))
2813        }
2814    }
2815}
2816
2817mod remote {
2818    use super::*;
2819
2820    pub async fn add_peer(
2821        envelope: TypedEnvelope<proto::AddPeer>,
2822        rpc: &rpc::Client,
2823        cx: &mut AsyncAppContext,
2824    ) -> anyhow::Result<()> {
2825        rpc.state
2826            .read()
2827            .await
2828            .shared_worktree(envelope.payload.worktree_id, cx)?
2829            .update(cx, |worktree, cx| worktree.add_peer(envelope, cx))
2830    }
2831
2832    pub async fn remove_peer(
2833        envelope: TypedEnvelope<proto::RemovePeer>,
2834        rpc: &rpc::Client,
2835        cx: &mut AsyncAppContext,
2836    ) -> anyhow::Result<()> {
2837        rpc.state
2838            .read()
2839            .await
2840            .shared_worktree(envelope.payload.worktree_id, cx)?
2841            .update(cx, |worktree, cx| worktree.remove_peer(envelope, cx))
2842    }
2843
2844    pub async fn update_worktree(
2845        envelope: TypedEnvelope<proto::UpdateWorktree>,
2846        rpc: &rpc::Client,
2847        cx: &mut AsyncAppContext,
2848    ) -> anyhow::Result<()> {
2849        rpc.state
2850            .read()
2851            .await
2852            .shared_worktree(envelope.payload.worktree_id, cx)?
2853            .update(cx, |worktree, _| {
2854                if let Some(worktree) = worktree.as_remote_mut() {
2855                    let mut tx = worktree.updates_tx.clone();
2856                    Ok(async move {
2857                        tx.send(envelope.payload)
2858                            .await
2859                            .expect("receiver runs to completion");
2860                    })
2861                } else {
2862                    Err(anyhow!(
2863                        "invalid update message for local worktree {}",
2864                        envelope.payload.worktree_id
2865                    ))
2866                }
2867            })?
2868            .await;
2869
2870        Ok(())
2871    }
2872
2873    pub async fn open_buffer(
2874        envelope: TypedEnvelope<proto::OpenBuffer>,
2875        rpc: &rpc::Client,
2876        cx: &mut AsyncAppContext,
2877    ) -> anyhow::Result<()> {
2878        let receipt = envelope.receipt();
2879        let worktree = rpc
2880            .state
2881            .read()
2882            .await
2883            .shared_worktree(envelope.payload.worktree_id, cx)?;
2884
2885        let response = worktree
2886            .update(cx, |worktree, cx| {
2887                worktree
2888                    .as_local_mut()
2889                    .unwrap()
2890                    .open_remote_buffer(envelope, cx)
2891            })
2892            .await?;
2893
2894        rpc.respond(receipt, response).await?;
2895
2896        Ok(())
2897    }
2898
2899    pub async fn close_buffer(
2900        envelope: TypedEnvelope<proto::CloseBuffer>,
2901        rpc: &rpc::Client,
2902        cx: &mut AsyncAppContext,
2903    ) -> anyhow::Result<()> {
2904        let worktree = rpc
2905            .state
2906            .read()
2907            .await
2908            .shared_worktree(envelope.payload.worktree_id, cx)?;
2909
2910        worktree.update(cx, |worktree, cx| {
2911            worktree
2912                .as_local_mut()
2913                .unwrap()
2914                .close_remote_buffer(envelope, cx)
2915        })
2916    }
2917
2918    pub async fn update_buffer(
2919        envelope: TypedEnvelope<proto::UpdateBuffer>,
2920        rpc: &rpc::Client,
2921        cx: &mut AsyncAppContext,
2922    ) -> anyhow::Result<()> {
2923        let message = envelope.payload;
2924        rpc.state
2925            .read()
2926            .await
2927            .shared_worktree(message.worktree_id, cx)?
2928            .update(cx, |tree, cx| tree.update_buffer(message, cx))?;
2929        Ok(())
2930    }
2931
2932    pub async fn save_buffer(
2933        envelope: TypedEnvelope<proto::SaveBuffer>,
2934        rpc: &rpc::Client,
2935        cx: &mut AsyncAppContext,
2936    ) -> anyhow::Result<()> {
2937        let state = rpc.state.read().await;
2938        let worktree = state.shared_worktree(envelope.payload.worktree_id, cx)?;
2939        let sender_id = envelope.original_sender_id()?;
2940        let buffer = worktree.read_with(cx, |tree, _| {
2941            tree.as_local()
2942                .unwrap()
2943                .shared_buffers
2944                .get(&sender_id)
2945                .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2946                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
2947        })?;
2948        let (version, mtime) = buffer.update(cx, |buffer, cx| buffer.save(cx))?.await?;
2949        rpc.respond(
2950            envelope.receipt(),
2951            proto::BufferSaved {
2952                worktree_id: envelope.payload.worktree_id,
2953                buffer_id: envelope.payload.buffer_id,
2954                version: (&version).into(),
2955                mtime: Some(mtime.into()),
2956            },
2957        )
2958        .await?;
2959        Ok(())
2960    }
2961
2962    pub async fn buffer_saved(
2963        envelope: TypedEnvelope<proto::BufferSaved>,
2964        rpc: &rpc::Client,
2965        cx: &mut AsyncAppContext,
2966    ) -> anyhow::Result<()> {
2967        eprintln!("got buffer_saved {:?}", envelope.payload);
2968
2969        rpc.state
2970            .read()
2971            .await
2972            .shared_worktree(envelope.payload.worktree_id, cx)?
2973            .update(cx, |worktree, cx| {
2974                worktree.buffer_saved(envelope.payload, cx)
2975            })?;
2976        Ok(())
2977    }
2978}
2979
2980#[cfg(test)]
2981mod tests {
2982    use super::*;
2983    use crate::test::*;
2984    use anyhow::Result;
2985    use rand::prelude::*;
2986    use serde_json::json;
2987    use std::time::UNIX_EPOCH;
2988    use std::{env, fmt::Write, os::unix, time::SystemTime};
2989
2990    #[gpui::test]
2991    async fn test_populate_and_search(cx: gpui::TestAppContext) {
2992        let dir = temp_tree(json!({
2993            "root": {
2994                "apple": "",
2995                "banana": {
2996                    "carrot": {
2997                        "date": "",
2998                        "endive": "",
2999                    }
3000                },
3001                "fennel": {
3002                    "grape": "",
3003                }
3004            }
3005        }));
3006
3007        let root_link_path = dir.path().join("root_link");
3008        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
3009        unix::fs::symlink(
3010            &dir.path().join("root/fennel"),
3011            &dir.path().join("root/finnochio"),
3012        )
3013        .unwrap();
3014
3015        let tree = Worktree::open_local(
3016            root_link_path,
3017            Default::default(),
3018            Arc::new(RealFs),
3019            &mut cx.to_async(),
3020        )
3021        .await
3022        .unwrap();
3023
3024        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3025            .await;
3026        let snapshot = cx.read(|cx| {
3027            let tree = tree.read(cx);
3028            assert_eq!(tree.file_count(), 5);
3029            assert_eq!(
3030                tree.inode_for_path("fennel/grape"),
3031                tree.inode_for_path("finnochio/grape")
3032            );
3033
3034            tree.snapshot()
3035        });
3036        let results = cx
3037            .read(|cx| {
3038                match_paths(
3039                    Some(&snapshot).into_iter(),
3040                    "bna",
3041                    false,
3042                    false,
3043                    false,
3044                    10,
3045                    Default::default(),
3046                    cx.thread_pool().clone(),
3047                )
3048            })
3049            .await;
3050        assert_eq!(
3051            results
3052                .into_iter()
3053                .map(|result| result.path)
3054                .collect::<Vec<Arc<Path>>>(),
3055            vec![
3056                PathBuf::from("banana/carrot/date").into(),
3057                PathBuf::from("banana/carrot/endive").into(),
3058            ]
3059        );
3060    }
3061
3062    #[gpui::test]
3063    async fn test_save_file(mut cx: gpui::TestAppContext) {
3064        let app_state = cx.read(build_app_state);
3065        let dir = temp_tree(json!({
3066            "file1": "the old contents",
3067        }));
3068        let tree = Worktree::open_local(
3069            dir.path(),
3070            app_state.languages.clone(),
3071            Arc::new(RealFs),
3072            &mut cx.to_async(),
3073        )
3074        .await
3075        .unwrap();
3076        let buffer = tree
3077            .update(&mut cx, |tree, cx| tree.open_buffer("file1", cx))
3078            .await
3079            .unwrap();
3080        let save = buffer.update(&mut cx, |buffer, cx| {
3081            buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3082            buffer.save(cx).unwrap()
3083        });
3084        save.await.unwrap();
3085
3086        let new_text = std::fs::read_to_string(dir.path().join("file1")).unwrap();
3087        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3088    }
3089
3090    #[gpui::test]
3091    async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3092        let app_state = cx.read(build_app_state);
3093        let dir = temp_tree(json!({
3094            "file1": "the old contents",
3095        }));
3096        let file_path = dir.path().join("file1");
3097
3098        let tree = Worktree::open_local(
3099            file_path.clone(),
3100            app_state.languages.clone(),
3101            Arc::new(RealFs),
3102            &mut cx.to_async(),
3103        )
3104        .await
3105        .unwrap();
3106        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3107            .await;
3108        cx.read(|cx| assert_eq!(tree.read(cx).file_count(), 1));
3109
3110        let buffer = tree
3111            .update(&mut cx, |tree, cx| tree.open_buffer("", cx))
3112            .await
3113            .unwrap();
3114        let save = buffer.update(&mut cx, |buffer, cx| {
3115            buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3116            buffer.save(cx).unwrap()
3117        });
3118        save.await.unwrap();
3119
3120        let new_text = std::fs::read_to_string(file_path).unwrap();
3121        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3122    }
3123
3124    #[gpui::test]
3125    async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3126        let dir = temp_tree(json!({
3127            "a": {
3128                "file1": "",
3129                "file2": "",
3130                "file3": "",
3131            },
3132            "b": {
3133                "c": {
3134                    "file4": "",
3135                    "file5": "",
3136                }
3137            }
3138        }));
3139
3140        let tree = Worktree::open_local(
3141            dir.path(),
3142            Default::default(),
3143            Arc::new(RealFs),
3144            &mut cx.to_async(),
3145        )
3146        .await
3147        .unwrap();
3148
3149        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3150            let buffer = tree.update(cx, |tree, cx| tree.open_buffer(path, cx));
3151            async move { buffer.await.unwrap() }
3152        };
3153        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3154            tree.read_with(cx, |tree, _| {
3155                tree.entry_for_path(path)
3156                    .expect(&format!("no entry for path {}", path))
3157                    .id
3158            })
3159        };
3160
3161        let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3162        let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3163        let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3164        let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3165
3166        let file2_id = id_for_path("a/file2", &cx);
3167        let file3_id = id_for_path("a/file3", &cx);
3168        let file4_id = id_for_path("b/c/file4", &cx);
3169
3170        // Wait for the initial scan.
3171        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3172            .await;
3173
3174        // Create a remote copy of this worktree.
3175        let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3176        let worktree_id = 1;
3177        let share_request = tree
3178            .update(&mut cx, |tree, cx| {
3179                tree.as_local().unwrap().share_request(cx)
3180            })
3181            .await;
3182        let remote = Worktree::remote(
3183            proto::OpenWorktreeResponse {
3184                worktree_id,
3185                worktree: share_request.worktree,
3186                replica_id: 1,
3187                peers: Vec::new(),
3188            },
3189            rpc::Client::new(Default::default()),
3190            Default::default(),
3191            &mut cx.to_async(),
3192        )
3193        .await
3194        .unwrap();
3195
3196        cx.read(|cx| {
3197            assert!(!buffer2.read(cx).is_dirty());
3198            assert!(!buffer3.read(cx).is_dirty());
3199            assert!(!buffer4.read(cx).is_dirty());
3200            assert!(!buffer5.read(cx).is_dirty());
3201        });
3202
3203        // Rename and delete files and directories.
3204        tree.flush_fs_events(&cx).await;
3205        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3206        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3207        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3208        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3209        tree.flush_fs_events(&cx).await;
3210
3211        let expected_paths = vec![
3212            "a",
3213            "a/file1",
3214            "a/file2.new",
3215            "b",
3216            "d",
3217            "d/file3",
3218            "d/file4",
3219        ];
3220
3221        cx.read(|app| {
3222            assert_eq!(
3223                tree.read(app)
3224                    .paths()
3225                    .map(|p| p.to_str().unwrap())
3226                    .collect::<Vec<_>>(),
3227                expected_paths
3228            );
3229
3230            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3231            assert_eq!(id_for_path("d/file3", &cx), file3_id);
3232            assert_eq!(id_for_path("d/file4", &cx), file4_id);
3233
3234            assert_eq!(
3235                buffer2.read(app).file().unwrap().path().as_ref(),
3236                Path::new("a/file2.new")
3237            );
3238            assert_eq!(
3239                buffer3.read(app).file().unwrap().path().as_ref(),
3240                Path::new("d/file3")
3241            );
3242            assert_eq!(
3243                buffer4.read(app).file().unwrap().path().as_ref(),
3244                Path::new("d/file4")
3245            );
3246            assert_eq!(
3247                buffer5.read(app).file().unwrap().path().as_ref(),
3248                Path::new("b/c/file5")
3249            );
3250
3251            assert!(!buffer2.read(app).file().unwrap().is_deleted());
3252            assert!(!buffer3.read(app).file().unwrap().is_deleted());
3253            assert!(!buffer4.read(app).file().unwrap().is_deleted());
3254            assert!(buffer5.read(app).file().unwrap().is_deleted());
3255        });
3256
3257        // Update the remote worktree. Check that it becomes consistent with the
3258        // local worktree.
3259        remote.update(&mut cx, |remote, cx| {
3260            let update_message = tree
3261                .read(cx)
3262                .snapshot()
3263                .build_update(&initial_snapshot, worktree_id);
3264            remote
3265                .as_remote_mut()
3266                .unwrap()
3267                .snapshot
3268                .apply_update(update_message)
3269                .unwrap();
3270
3271            assert_eq!(
3272                remote
3273                    .paths()
3274                    .map(|p| p.to_str().unwrap())
3275                    .collect::<Vec<_>>(),
3276                expected_paths
3277            );
3278        });
3279    }
3280
3281    #[gpui::test]
3282    async fn test_rescan_with_gitignore(cx: gpui::TestAppContext) {
3283        let dir = temp_tree(json!({
3284            ".git": {},
3285            ".gitignore": "ignored-dir\n",
3286            "tracked-dir": {
3287                "tracked-file1": "tracked contents",
3288            },
3289            "ignored-dir": {
3290                "ignored-file1": "ignored contents",
3291            }
3292        }));
3293
3294        let tree = Worktree::open_local(
3295            dir.path(),
3296            Default::default(),
3297            Arc::new(RealFs),
3298            &mut cx.to_async(),
3299        )
3300        .await
3301        .unwrap();
3302        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3303            .await;
3304        tree.flush_fs_events(&cx).await;
3305        cx.read(|cx| {
3306            let tree = tree.read(cx);
3307            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
3308            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
3309            assert_eq!(tracked.is_ignored(), false);
3310            assert_eq!(ignored.is_ignored(), true);
3311        });
3312
3313        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
3314        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
3315        tree.flush_fs_events(&cx).await;
3316        cx.read(|cx| {
3317            let tree = tree.read(cx);
3318            let dot_git = tree.entry_for_path(".git").unwrap();
3319            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
3320            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
3321            assert_eq!(tracked.is_ignored(), false);
3322            assert_eq!(ignored.is_ignored(), true);
3323            assert_eq!(dot_git.is_ignored(), true);
3324        });
3325    }
3326
3327    #[test]
3328    fn test_random() {
3329        let iterations = env::var("ITERATIONS")
3330            .map(|i| i.parse().unwrap())
3331            .unwrap_or(100);
3332        let operations = env::var("OPERATIONS")
3333            .map(|o| o.parse().unwrap())
3334            .unwrap_or(40);
3335        let initial_entries = env::var("INITIAL_ENTRIES")
3336            .map(|o| o.parse().unwrap())
3337            .unwrap_or(20);
3338        let seeds = if let Ok(seed) = env::var("SEED").map(|s| s.parse().unwrap()) {
3339            seed..seed + 1
3340        } else {
3341            0..iterations
3342        };
3343
3344        for seed in seeds {
3345            dbg!(seed);
3346            let mut rng = StdRng::seed_from_u64(seed);
3347
3348            let root_dir = tempdir::TempDir::new(&format!("test-{}", seed)).unwrap();
3349            for _ in 0..initial_entries {
3350                randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
3351            }
3352            log::info!("Generated initial tree");
3353
3354            let (notify_tx, _notify_rx) = smol::channel::unbounded();
3355            let fs = Arc::new(RealFs);
3356            let next_entry_id = Arc::new(AtomicUsize::new(0));
3357            let mut initial_snapshot = Snapshot {
3358                id: 0,
3359                scan_id: 0,
3360                abs_path: root_dir.path().into(),
3361                entries_by_path: Default::default(),
3362                entries_by_id: Default::default(),
3363                removed_entry_ids: Default::default(),
3364                ignores: Default::default(),
3365                root_name: Default::default(),
3366                root_char_bag: Default::default(),
3367                next_entry_id: next_entry_id.clone(),
3368            };
3369            initial_snapshot.insert_entry(
3370                smol::block_on(fs.entry(
3371                    Default::default(),
3372                    &next_entry_id,
3373                    Path::new("").into(),
3374                    root_dir.path().into(),
3375                ))
3376                .unwrap()
3377                .unwrap(),
3378            );
3379            let mut scanner = BackgroundScanner::new(
3380                Arc::new(Mutex::new(initial_snapshot.clone())),
3381                notify_tx,
3382                fs.clone(),
3383                Arc::new(gpui::executor::Background::new()),
3384            );
3385            smol::block_on(scanner.scan_dirs()).unwrap();
3386            scanner.snapshot().check_invariants();
3387
3388            let mut events = Vec::new();
3389            let mut mutations_len = operations;
3390            while mutations_len > 1 {
3391                if !events.is_empty() && rng.gen_bool(0.4) {
3392                    let len = rng.gen_range(0..=events.len());
3393                    let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3394                    log::info!("Delivering events: {:#?}", to_deliver);
3395                    smol::block_on(scanner.process_events(to_deliver));
3396                    scanner.snapshot().check_invariants();
3397                } else {
3398                    events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3399                    mutations_len -= 1;
3400                }
3401            }
3402            log::info!("Quiescing: {:#?}", events);
3403            smol::block_on(scanner.process_events(events));
3404            scanner.snapshot().check_invariants();
3405
3406            let (notify_tx, _notify_rx) = smol::channel::unbounded();
3407            let mut new_scanner = BackgroundScanner::new(
3408                Arc::new(Mutex::new(initial_snapshot)),
3409                notify_tx,
3410                scanner.fs.clone(),
3411                scanner.executor.clone(),
3412            );
3413            smol::block_on(new_scanner.scan_dirs()).unwrap();
3414            assert_eq!(scanner.snapshot().to_vec(), new_scanner.snapshot().to_vec());
3415        }
3416    }
3417
3418    fn randomly_mutate_tree(
3419        root_path: &Path,
3420        insertion_probability: f64,
3421        rng: &mut impl Rng,
3422    ) -> Result<Vec<fsevent::Event>> {
3423        let root_path = root_path.canonicalize().unwrap();
3424        let (dirs, files) = read_dir_recursive(root_path.clone());
3425
3426        let mut events = Vec::new();
3427        let mut record_event = |path: PathBuf| {
3428            events.push(fsevent::Event {
3429                event_id: SystemTime::now()
3430                    .duration_since(UNIX_EPOCH)
3431                    .unwrap()
3432                    .as_secs(),
3433                flags: fsevent::StreamFlags::empty(),
3434                path,
3435            });
3436        };
3437
3438        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3439            let path = dirs.choose(rng).unwrap();
3440            let new_path = path.join(gen_name(rng));
3441
3442            if rng.gen() {
3443                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3444                std::fs::create_dir(&new_path)?;
3445            } else {
3446                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3447                std::fs::write(&new_path, "")?;
3448            }
3449            record_event(new_path);
3450        } else if rng.gen_bool(0.05) {
3451            let ignore_dir_path = dirs.choose(rng).unwrap();
3452            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3453
3454            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3455            let files_to_ignore = {
3456                let len = rng.gen_range(0..=subfiles.len());
3457                subfiles.choose_multiple(rng, len)
3458            };
3459            let dirs_to_ignore = {
3460                let len = rng.gen_range(0..subdirs.len());
3461                subdirs.choose_multiple(rng, len)
3462            };
3463
3464            let mut ignore_contents = String::new();
3465            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3466                write!(
3467                    ignore_contents,
3468                    "{}\n",
3469                    path_to_ignore
3470                        .strip_prefix(&ignore_dir_path)?
3471                        .to_str()
3472                        .unwrap()
3473                )
3474                .unwrap();
3475            }
3476            log::info!(
3477                "Creating {:?} with contents:\n{}",
3478                ignore_path.strip_prefix(&root_path)?,
3479                ignore_contents
3480            );
3481            std::fs::write(&ignore_path, ignore_contents).unwrap();
3482            record_event(ignore_path);
3483        } else {
3484            let old_path = {
3485                let file_path = files.choose(rng);
3486                let dir_path = dirs[1..].choose(rng);
3487                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3488            };
3489
3490            let is_rename = rng.gen();
3491            if is_rename {
3492                let new_path_parent = dirs
3493                    .iter()
3494                    .filter(|d| !d.starts_with(old_path))
3495                    .choose(rng)
3496                    .unwrap();
3497
3498                let overwrite_existing_dir =
3499                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3500                let new_path = if overwrite_existing_dir {
3501                    std::fs::remove_dir_all(&new_path_parent).ok();
3502                    new_path_parent.to_path_buf()
3503                } else {
3504                    new_path_parent.join(gen_name(rng))
3505                };
3506
3507                log::info!(
3508                    "Renaming {:?} to {}{:?}",
3509                    old_path.strip_prefix(&root_path)?,
3510                    if overwrite_existing_dir {
3511                        "overwrite "
3512                    } else {
3513                        ""
3514                    },
3515                    new_path.strip_prefix(&root_path)?
3516                );
3517                std::fs::rename(&old_path, &new_path)?;
3518                record_event(old_path.clone());
3519                record_event(new_path);
3520            } else if old_path.is_dir() {
3521                let (dirs, files) = read_dir_recursive(old_path.clone());
3522
3523                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3524                std::fs::remove_dir_all(&old_path).unwrap();
3525                for file in files {
3526                    record_event(file);
3527                }
3528                for dir in dirs {
3529                    record_event(dir);
3530                }
3531            } else {
3532                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3533                std::fs::remove_file(old_path).unwrap();
3534                record_event(old_path.clone());
3535            }
3536        }
3537
3538        Ok(events)
3539    }
3540
3541    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3542        let child_entries = std::fs::read_dir(&path).unwrap();
3543        let mut dirs = vec![path];
3544        let mut files = Vec::new();
3545        for child_entry in child_entries {
3546            let child_path = child_entry.unwrap().path();
3547            if child_path.is_dir() {
3548                let (child_dirs, child_files) = read_dir_recursive(child_path);
3549                dirs.extend(child_dirs);
3550                files.extend(child_files);
3551            } else {
3552                files.push(child_path);
3553            }
3554        }
3555        (dirs, files)
3556    }
3557
3558    fn gen_name(rng: &mut impl Rng) -> String {
3559        (0..6)
3560            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3561            .map(char::from)
3562            .collect()
3563    }
3564
3565    impl Snapshot {
3566        fn check_invariants(&self) {
3567            let mut files = self.files(0);
3568            let mut visible_files = self.visible_files(0);
3569            for entry in self.entries_by_path.cursor::<(), ()>() {
3570                if entry.is_file() {
3571                    assert_eq!(files.next().unwrap().inode(), entry.inode);
3572                    if !entry.is_ignored {
3573                        assert_eq!(visible_files.next().unwrap().inode(), entry.inode);
3574                    }
3575                }
3576            }
3577            assert!(files.next().is_none());
3578            assert!(visible_files.next().is_none());
3579
3580            let mut bfs_paths = Vec::new();
3581            let mut stack = vec![Path::new("")];
3582            while let Some(path) = stack.pop() {
3583                bfs_paths.push(path);
3584                let ix = stack.len();
3585                for child_entry in self.child_entries(path) {
3586                    stack.insert(ix, child_entry.path());
3587                }
3588            }
3589
3590            let dfs_paths = self
3591                .entries_by_path
3592                .cursor::<(), ()>()
3593                .map(|e| e.path().as_ref())
3594                .collect::<Vec<_>>();
3595            assert_eq!(bfs_paths, dfs_paths);
3596
3597            for (ignore_parent_path, _) in &self.ignores {
3598                assert!(self.entry_for_path(ignore_parent_path).is_some());
3599                assert!(self
3600                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3601                    .is_some());
3602            }
3603        }
3604
3605        fn to_vec(&self) -> Vec<(&Path, u64, bool)> {
3606            let mut paths = Vec::new();
3607            for entry in self.entries_by_path.cursor::<(), ()>() {
3608                paths.push((entry.path().as_ref(), entry.inode(), entry.is_ignored()));
3609            }
3610            paths.sort_by(|a, b| a.0.cmp(&b.0));
3611            paths
3612        }
3613    }
3614}