worktree.rs

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