worktree.rs

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