worktree.rs

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