worktree.rs

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