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, TypedEnvelope};
   9use clock::ReplicaId;
  10use collections::HashMap;
  11use futures::{
  12    channel::mpsc::{self, UnboundedSender},
  13    Stream, StreamExt,
  14};
  15use fuzzy::CharBag;
  16use gpui::{
  17    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  18    Task,
  19};
  20use language::{
  21    proto::{deserialize_version, serialize_version},
  22    Buffer, DiagnosticEntry, PointUtf16, Rope,
  23};
  24use lazy_static::lazy_static;
  25use parking_lot::Mutex;
  26use postage::{
  27    oneshot,
  28    prelude::{Sink as _, Stream as _},
  29    watch,
  30};
  31use serde::Deserialize;
  32use smol::channel::{self, Sender};
  33use std::{
  34    any::Any,
  35    cmp::{self, Ordering},
  36    convert::TryFrom,
  37    ffi::{OsStr, OsString},
  38    fmt,
  39    future::Future,
  40    ops::{Deref, DerefMut},
  41    path::{Path, PathBuf},
  42    sync::{
  43        atomic::{AtomicUsize, Ordering::SeqCst},
  44        Arc,
  45    },
  46    time::{Duration, SystemTime},
  47};
  48use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap};
  49use util::{ResultExt, TryFutureExt};
  50
  51lazy_static! {
  52    static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
  53}
  54
  55#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  56pub struct WorktreeId(usize);
  57
  58pub enum Worktree {
  59    Local(LocalWorktree),
  60    Remote(RemoteWorktree),
  61}
  62
  63pub struct LocalWorktree {
  64    snapshot: LocalSnapshot,
  65    config: WorktreeConfig,
  66    background_snapshot: Arc<Mutex<LocalSnapshot>>,
  67    last_scan_state_rx: watch::Receiver<ScanState>,
  68    _background_scanner_task: Option<Task<()>>,
  69    poll_task: Option<Task<()>>,
  70    registration: Registration,
  71    share: Option<ShareState>,
  72    diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
  73    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  74    client: Arc<Client>,
  75    fs: Arc<dyn Fs>,
  76    visible: bool,
  77}
  78
  79pub struct RemoteWorktree {
  80    pub(crate) snapshot: Snapshot,
  81    project_id: u64,
  82    snapshot_rx: watch::Receiver<Snapshot>,
  83    client: Arc<Client>,
  84    updates_tx: UnboundedSender<proto::UpdateWorktree>,
  85    replica_id: ReplicaId,
  86    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  87    visible: bool,
  88}
  89
  90#[derive(Clone)]
  91pub struct Snapshot {
  92    id: WorktreeId,
  93    root_name: String,
  94    root_char_bag: CharBag,
  95    entries_by_path: SumTree<Entry>,
  96    entries_by_id: SumTree<PathEntry>,
  97}
  98
  99#[derive(Clone)]
 100pub struct LocalSnapshot {
 101    abs_path: Arc<Path>,
 102    scan_id: usize,
 103    ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 104    removed_entry_ids: HashMap<u64, usize>,
 105    next_entry_id: Arc<AtomicUsize>,
 106    snapshot: Snapshot,
 107}
 108
 109impl Deref for LocalSnapshot {
 110    type Target = Snapshot;
 111
 112    fn deref(&self) -> &Self::Target {
 113        &self.snapshot
 114    }
 115}
 116
 117impl DerefMut for LocalSnapshot {
 118    fn deref_mut(&mut self) -> &mut Self::Target {
 119        &mut self.snapshot
 120    }
 121}
 122
 123#[derive(Clone, Debug)]
 124enum ScanState {
 125    Idle,
 126    Scanning,
 127    Err(Arc<anyhow::Error>),
 128}
 129
 130#[derive(Debug, Eq, PartialEq)]
 131enum Registration {
 132    None,
 133    Pending,
 134    Done { project_id: u64 },
 135}
 136
 137struct ShareState {
 138    project_id: u64,
 139    snapshots_tx: Sender<LocalSnapshot>,
 140    _maintain_remote_snapshot: Option<Task<Option<()>>>,
 141}
 142
 143#[derive(Default, Deserialize)]
 144struct WorktreeConfig {
 145    collaborators: Vec<String>,
 146}
 147
 148pub enum Event {
 149    UpdatedEntries,
 150}
 151
 152impl Entity for Worktree {
 153    type Event = Event;
 154
 155    fn release(&mut self, _: &mut MutableAppContext) {
 156        if let Some(worktree) = self.as_local_mut() {
 157            if let Registration::Done { project_id } = worktree.registration {
 158                let client = worktree.client.clone();
 159                let unregister_message = proto::UnregisterWorktree {
 160                    project_id,
 161                    worktree_id: worktree.id().to_proto(),
 162                };
 163                client.send(unregister_message).log_err();
 164            }
 165        }
 166    }
 167}
 168
 169impl Worktree {
 170    pub async fn local(
 171        client: Arc<Client>,
 172        path: impl Into<Arc<Path>>,
 173        visible: bool,
 174        fs: Arc<dyn Fs>,
 175        cx: &mut AsyncAppContext,
 176    ) -> Result<ModelHandle<Self>> {
 177        let (tree, scan_states_tx) =
 178            LocalWorktree::new(client, path, visible, fs.clone(), cx).await?;
 179        tree.update(cx, |tree, cx| {
 180            let tree = tree.as_local_mut().unwrap();
 181            let abs_path = tree.abs_path().clone();
 182            let background_snapshot = tree.background_snapshot.clone();
 183            let background = cx.background().clone();
 184            tree._background_scanner_task = Some(cx.background().spawn(async move {
 185                let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 186                let scanner =
 187                    BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
 188                scanner.run(events).await;
 189            }));
 190        });
 191        Ok(tree)
 192    }
 193
 194    pub fn remote(
 195        project_remote_id: u64,
 196        replica_id: ReplicaId,
 197        worktree: proto::Worktree,
 198        client: Arc<Client>,
 199        cx: &mut MutableAppContext,
 200    ) -> (ModelHandle<Self>, Task<()>) {
 201        let remote_id = worktree.id;
 202        let root_char_bag: CharBag = worktree
 203            .root_name
 204            .chars()
 205            .map(|c| c.to_ascii_lowercase())
 206            .collect();
 207        let root_name = worktree.root_name.clone();
 208        let visible = worktree.visible;
 209        let snapshot = Snapshot {
 210            id: WorktreeId(remote_id as usize),
 211            root_name,
 212            root_char_bag,
 213            entries_by_path: Default::default(),
 214            entries_by_id: Default::default(),
 215        };
 216
 217        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 218        let (mut snapshot_tx, snapshot_rx) = watch::channel_with(snapshot.clone());
 219        let worktree_handle = cx.add_model(|_: &mut ModelContext<Worktree>| {
 220            Worktree::Remote(RemoteWorktree {
 221                project_id: project_remote_id,
 222                replica_id,
 223                snapshot: snapshot.clone(),
 224                snapshot_rx: snapshot_rx.clone(),
 225                updates_tx,
 226                client: client.clone(),
 227                diagnostic_summaries: TreeMap::from_ordered_entries(
 228                    worktree.diagnostic_summaries.into_iter().map(|summary| {
 229                        (
 230                            PathKey(PathBuf::from(summary.path).into()),
 231                            DiagnosticSummary {
 232                                error_count: summary.error_count as usize,
 233                                warning_count: summary.warning_count as usize,
 234                                info_count: summary.info_count as usize,
 235                                hint_count: summary.hint_count as usize,
 236                            },
 237                        )
 238                    }),
 239                ),
 240                visible,
 241            })
 242        });
 243
 244        let deserialize_task = cx.spawn({
 245            let worktree_handle = worktree_handle.clone();
 246            |cx| async move {
 247                let (entries_by_path, entries_by_id) = cx
 248                    .background()
 249                    .spawn(async move {
 250                        let mut entries_by_path_edits = Vec::new();
 251                        let mut entries_by_id_edits = Vec::new();
 252                        for entry in worktree.entries {
 253                            match Entry::try_from((&root_char_bag, entry)) {
 254                                Ok(entry) => {
 255                                    entries_by_id_edits.push(Edit::Insert(PathEntry {
 256                                        id: entry.id,
 257                                        path: entry.path.clone(),
 258                                        is_ignored: entry.is_ignored,
 259                                        scan_id: 0,
 260                                    }));
 261                                    entries_by_path_edits.push(Edit::Insert(entry));
 262                                }
 263                                Err(err) => log::warn!("error for remote worktree entry {:?}", err),
 264                            }
 265                        }
 266
 267                        let mut entries_by_path = SumTree::new();
 268                        let mut entries_by_id = SumTree::new();
 269                        entries_by_path.edit(entries_by_path_edits, &());
 270                        entries_by_id.edit(entries_by_id_edits, &());
 271
 272                        (entries_by_path, entries_by_id)
 273                    })
 274                    .await;
 275
 276                {
 277                    let mut snapshot = snapshot_tx.borrow_mut();
 278                    snapshot.entries_by_path = entries_by_path;
 279                    snapshot.entries_by_id = entries_by_id;
 280                }
 281
 282                cx.background()
 283                    .spawn(async move {
 284                        while let Some(update) = updates_rx.next().await {
 285                            let mut snapshot = snapshot_tx.borrow().clone();
 286                            if let Err(error) = snapshot.apply_remote_update(update) {
 287                                log::error!("error applying worktree update: {}", error);
 288                            }
 289                            *snapshot_tx.borrow_mut() = snapshot;
 290                        }
 291                    })
 292                    .detach();
 293
 294                {
 295                    let mut snapshot_rx = snapshot_rx.clone();
 296                    let this = worktree_handle.downgrade();
 297                    cx.spawn(|mut cx| async move {
 298                        while let Some(_) = snapshot_rx.recv().await {
 299                            if let Some(this) = this.upgrade(&cx) {
 300                                this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 301                            } else {
 302                                break;
 303                            }
 304                        }
 305                    })
 306                    .detach();
 307                }
 308            }
 309        });
 310        (worktree_handle, deserialize_task)
 311    }
 312
 313    pub fn as_local(&self) -> Option<&LocalWorktree> {
 314        if let Worktree::Local(worktree) = self {
 315            Some(worktree)
 316        } else {
 317            None
 318        }
 319    }
 320
 321    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 322        if let Worktree::Remote(worktree) = self {
 323            Some(worktree)
 324        } else {
 325            None
 326        }
 327    }
 328
 329    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 330        if let Worktree::Local(worktree) = self {
 331            Some(worktree)
 332        } else {
 333            None
 334        }
 335    }
 336
 337    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 338        if let Worktree::Remote(worktree) = self {
 339            Some(worktree)
 340        } else {
 341            None
 342        }
 343    }
 344
 345    pub fn is_local(&self) -> bool {
 346        matches!(self, Worktree::Local(_))
 347    }
 348
 349    pub fn is_remote(&self) -> bool {
 350        !self.is_local()
 351    }
 352
 353    pub fn snapshot(&self) -> Snapshot {
 354        match self {
 355            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 356            Worktree::Remote(worktree) => worktree.snapshot(),
 357        }
 358    }
 359
 360    pub fn is_visible(&self) -> bool {
 361        match self {
 362            Worktree::Local(worktree) => worktree.visible,
 363            Worktree::Remote(worktree) => worktree.visible,
 364        }
 365    }
 366
 367    pub fn replica_id(&self) -> ReplicaId {
 368        match self {
 369            Worktree::Local(_) => 0,
 370            Worktree::Remote(worktree) => worktree.replica_id,
 371        }
 372    }
 373
 374    pub fn diagnostic_summaries<'a>(
 375        &'a self,
 376    ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + 'a {
 377        match self {
 378            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 379            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 380        }
 381        .iter()
 382        .map(|(path, summary)| (path.0.clone(), summary.clone()))
 383    }
 384
 385    fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
 386        match self {
 387            Self::Local(worktree) => {
 388                let is_fake_fs = worktree.fs.is_fake();
 389                worktree.snapshot = worktree.background_snapshot.lock().clone();
 390                if worktree.is_scanning() {
 391                    if worktree.poll_task.is_none() {
 392                        worktree.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
 393                            if is_fake_fs {
 394                                #[cfg(any(test, feature = "test-support"))]
 395                                cx.background().simulate_random_delay().await;
 396                            } else {
 397                                smol::Timer::after(Duration::from_millis(100)).await;
 398                            }
 399                            if let Some(this) = this.upgrade(&cx) {
 400                                this.update(&mut cx, |this, cx| {
 401                                    this.as_local_mut().unwrap().poll_task = None;
 402                                    this.poll_snapshot(cx);
 403                                });
 404                            }
 405                        }));
 406                    }
 407                } else {
 408                    worktree.poll_task.take();
 409                    cx.emit(Event::UpdatedEntries);
 410                }
 411            }
 412            Self::Remote(worktree) => {
 413                worktree.snapshot = worktree.snapshot_rx.borrow().clone();
 414                cx.emit(Event::UpdatedEntries);
 415            }
 416        };
 417
 418        cx.notify();
 419    }
 420}
 421
 422impl LocalWorktree {
 423    async fn new(
 424        client: Arc<Client>,
 425        path: impl Into<Arc<Path>>,
 426        visible: bool,
 427        fs: Arc<dyn Fs>,
 428        cx: &mut AsyncAppContext,
 429    ) -> Result<(ModelHandle<Worktree>, UnboundedSender<ScanState>)> {
 430        let abs_path = path.into();
 431        let path: Arc<Path> = Arc::from(Path::new(""));
 432        let next_entry_id = AtomicUsize::new(0);
 433
 434        // After determining whether the root entry is a file or a directory, populate the
 435        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 436        let root_name = abs_path
 437            .file_name()
 438            .map_or(String::new(), |f| f.to_string_lossy().to_string());
 439        let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
 440        let metadata = fs
 441            .metadata(&abs_path)
 442            .await
 443            .context("failed to stat worktree path")?;
 444
 445        let mut config = WorktreeConfig::default();
 446        if let Ok(zed_toml) = fs.load(&abs_path.join(".zed.toml")).await {
 447            if let Ok(parsed) = toml::from_str(&zed_toml) {
 448                config = parsed;
 449            }
 450        }
 451
 452        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 453        let (mut last_scan_state_tx, last_scan_state_rx) = watch::channel_with(ScanState::Scanning);
 454        let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 455            let mut snapshot = LocalSnapshot {
 456                abs_path,
 457                scan_id: 0,
 458                ignores: Default::default(),
 459                removed_entry_ids: Default::default(),
 460                next_entry_id: Arc::new(next_entry_id),
 461                snapshot: Snapshot {
 462                    id: WorktreeId::from_usize(cx.model_id()),
 463                    root_name: root_name.clone(),
 464                    root_char_bag,
 465                    entries_by_path: Default::default(),
 466                    entries_by_id: Default::default(),
 467                },
 468            };
 469            if let Some(metadata) = metadata {
 470                let entry = Entry::new(
 471                    path.into(),
 472                    &metadata,
 473                    &snapshot.next_entry_id,
 474                    snapshot.root_char_bag,
 475                );
 476                snapshot.insert_entry(entry, fs.as_ref());
 477            }
 478
 479            let tree = Self {
 480                snapshot: snapshot.clone(),
 481                config,
 482                background_snapshot: Arc::new(Mutex::new(snapshot)),
 483                last_scan_state_rx,
 484                _background_scanner_task: None,
 485                registration: Registration::None,
 486                share: None,
 487                poll_task: None,
 488                diagnostics: Default::default(),
 489                diagnostic_summaries: Default::default(),
 490                client,
 491                fs,
 492                visible,
 493            };
 494
 495            cx.spawn_weak(|this, mut cx| async move {
 496                while let Some(scan_state) = scan_states_rx.next().await {
 497                    if let Some(handle) = this.upgrade(&cx) {
 498                        let to_send = handle.update(&mut cx, |this, cx| {
 499                            last_scan_state_tx.blocking_send(scan_state).ok();
 500                            this.poll_snapshot(cx);
 501                            let tree = this.as_local_mut().unwrap();
 502                            if !tree.is_scanning() {
 503                                if let Some(share) = tree.share.as_ref() {
 504                                    return Some((tree.snapshot(), share.snapshots_tx.clone()));
 505                                }
 506                            }
 507                            None
 508                        });
 509
 510                        if let Some((snapshot, snapshots_to_send_tx)) = to_send {
 511                            if let Err(err) = snapshots_to_send_tx.send(snapshot).await {
 512                                log::error!("error submitting snapshot to send {}", err);
 513                            }
 514                        }
 515                    } else {
 516                        break;
 517                    }
 518                }
 519            })
 520            .detach();
 521
 522            Worktree::Local(tree)
 523        });
 524
 525        Ok((tree, scan_states_tx))
 526    }
 527
 528    pub fn contains_abs_path(&self, path: &Path) -> bool {
 529        path.starts_with(&self.abs_path)
 530    }
 531
 532    fn absolutize(&self, path: &Path) -> PathBuf {
 533        if path.file_name().is_some() {
 534            self.abs_path.join(path)
 535        } else {
 536            self.abs_path.to_path_buf()
 537        }
 538    }
 539
 540    pub fn authorized_logins(&self) -> Vec<String> {
 541        self.config.collaborators.clone()
 542    }
 543
 544    pub(crate) fn load_buffer(
 545        &mut self,
 546        path: &Path,
 547        cx: &mut ModelContext<Worktree>,
 548    ) -> Task<Result<ModelHandle<Buffer>>> {
 549        let path = Arc::from(path);
 550        cx.spawn(move |this, mut cx| async move {
 551            let (file, contents) = this
 552                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 553                .await?;
 554            Ok(cx.add_model(|cx| Buffer::from_file(0, contents, Box::new(file), cx)))
 555        })
 556    }
 557
 558    pub fn diagnostics_for_path(&self, path: &Path) -> Option<Vec<DiagnosticEntry<PointUtf16>>> {
 559        self.diagnostics.get(path).cloned()
 560    }
 561
 562    pub fn update_diagnostics(
 563        &mut self,
 564        worktree_path: Arc<Path>,
 565        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
 566        _: &mut ModelContext<Worktree>,
 567    ) -> Result<()> {
 568        let summary = DiagnosticSummary::new(&diagnostics);
 569        self.diagnostic_summaries
 570            .insert(PathKey(worktree_path.clone()), summary.clone());
 571        self.diagnostics.insert(worktree_path.clone(), diagnostics);
 572
 573        if let Some(share) = self.share.as_ref() {
 574            self.client
 575                .send(proto::UpdateDiagnosticSummary {
 576                    project_id: share.project_id,
 577                    worktree_id: self.id().to_proto(),
 578                    summary: Some(proto::DiagnosticSummary {
 579                        path: worktree_path.to_string_lossy().to_string(),
 580                        error_count: summary.error_count as u32,
 581                        warning_count: summary.warning_count as u32,
 582                        info_count: summary.info_count as u32,
 583                        hint_count: summary.hint_count as u32,
 584                    }),
 585                })
 586                .log_err();
 587        }
 588
 589        Ok(())
 590    }
 591
 592    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 593        let mut scan_state_rx = self.last_scan_state_rx.clone();
 594        async move {
 595            let mut scan_state = Some(scan_state_rx.borrow().clone());
 596            while let Some(ScanState::Scanning) = scan_state {
 597                scan_state = scan_state_rx.recv().await;
 598            }
 599        }
 600    }
 601
 602    fn is_scanning(&self) -> bool {
 603        if let ScanState::Scanning = *self.last_scan_state_rx.borrow() {
 604            true
 605        } else {
 606            false
 607        }
 608    }
 609
 610    pub fn snapshot(&self) -> LocalSnapshot {
 611        self.snapshot.clone()
 612    }
 613
 614    fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
 615        let handle = cx.handle();
 616        let path = Arc::from(path);
 617        let abs_path = self.absolutize(&path);
 618        let background_snapshot = self.background_snapshot.clone();
 619        let fs = self.fs.clone();
 620        cx.spawn(|this, mut cx| async move {
 621            let text = fs.load(&abs_path).await?;
 622            // Eagerly populate the snapshot with an updated entry for the loaded file
 623            let entry = refresh_entry(fs.as_ref(), &background_snapshot, path, &abs_path).await?;
 624            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 625            Ok((
 626                File {
 627                    entry_id: Some(entry.id),
 628                    worktree: handle,
 629                    path: entry.path,
 630                    mtime: entry.mtime,
 631                    is_local: true,
 632                },
 633                text,
 634            ))
 635        })
 636    }
 637
 638    pub fn save_buffer_as(
 639        &self,
 640        buffer_handle: ModelHandle<Buffer>,
 641        path: impl Into<Arc<Path>>,
 642        cx: &mut ModelContext<Worktree>,
 643    ) -> Task<Result<()>> {
 644        let buffer = buffer_handle.read(cx);
 645        let text = buffer.as_rope().clone();
 646        let version = buffer.version();
 647        let save = self.save(path, text, cx);
 648        let handle = cx.handle();
 649        cx.as_mut().spawn(|mut cx| async move {
 650            let entry = save.await?;
 651            let file = File {
 652                entry_id: Some(entry.id),
 653                worktree: handle,
 654                path: entry.path,
 655                mtime: entry.mtime,
 656                is_local: true,
 657            };
 658
 659            buffer_handle.update(&mut cx, |buffer, cx| {
 660                buffer.did_save(version, file.mtime, Some(Box::new(file)), cx);
 661            });
 662
 663            Ok(())
 664        })
 665    }
 666
 667    fn save(
 668        &self,
 669        path: impl Into<Arc<Path>>,
 670        text: Rope,
 671        cx: &mut ModelContext<Worktree>,
 672    ) -> Task<Result<Entry>> {
 673        let path = path.into();
 674        let abs_path = self.absolutize(&path);
 675        let background_snapshot = self.background_snapshot.clone();
 676        let fs = self.fs.clone();
 677        let save = cx.background().spawn(async move {
 678            fs.save(&abs_path, &text).await?;
 679            refresh_entry(fs.as_ref(), &background_snapshot, path.clone(), &abs_path).await
 680        });
 681
 682        cx.spawn(|this, mut cx| async move {
 683            let entry = save.await?;
 684            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 685            Ok(entry)
 686        })
 687    }
 688
 689    pub fn register(
 690        &mut self,
 691        project_id: u64,
 692        cx: &mut ModelContext<Worktree>,
 693    ) -> Task<anyhow::Result<()>> {
 694        if self.registration != Registration::None {
 695            return Task::ready(Ok(()));
 696        }
 697
 698        self.registration = Registration::Pending;
 699        let client = self.client.clone();
 700        let register_message = proto::RegisterWorktree {
 701            project_id,
 702            worktree_id: self.id().to_proto(),
 703            root_name: self.root_name().to_string(),
 704            authorized_logins: self.authorized_logins(),
 705            visible: self.visible,
 706        };
 707        let request = client.request(register_message);
 708        cx.spawn(|this, mut cx| async move {
 709            let response = request.await;
 710            this.update(&mut cx, |this, _| {
 711                let worktree = this.as_local_mut().unwrap();
 712                match response {
 713                    Ok(_) => {
 714                        worktree.registration = Registration::Done { project_id };
 715                        Ok(())
 716                    }
 717                    Err(error) => {
 718                        worktree.registration = Registration::None;
 719                        Err(error)
 720                    }
 721                }
 722            })
 723        })
 724    }
 725
 726    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 727        let register = self.register(project_id, cx);
 728        let (mut share_tx, mut share_rx) = oneshot::channel();
 729        let (snapshots_to_send_tx, snapshots_to_send_rx) =
 730            smol::channel::unbounded::<LocalSnapshot>();
 731        if self.share.is_some() {
 732            let _ = share_tx.try_send(Ok(()));
 733        } else {
 734            let rpc = self.client.clone();
 735            let worktree_id = cx.model_id() as u64;
 736            let maintain_remote_snapshot = cx.background().spawn({
 737                let rpc = rpc.clone();
 738                let diagnostic_summaries = self.diagnostic_summaries.clone();
 739                async move {
 740                    let mut prev_snapshot = match snapshots_to_send_rx.recv().await {
 741                        Ok(snapshot) => {
 742                            if let Err(error) = rpc
 743                                .request(proto::UpdateWorktree {
 744                                    project_id,
 745                                    worktree_id,
 746                                    root_name: snapshot.root_name().to_string(),
 747                                    updated_entries: snapshot
 748                                        .entries_by_path
 749                                        .iter()
 750                                        .filter(|e| !e.is_ignored)
 751                                        .map(Into::into)
 752                                        .collect(),
 753                                    removed_entries: Default::default(),
 754                                })
 755                                .await
 756                            {
 757                                let _ = share_tx.try_send(Err(error));
 758                                return Err(anyhow!("failed to send initial update worktree"));
 759                            } else {
 760                                let _ = share_tx.try_send(Ok(()));
 761                                snapshot
 762                            }
 763                        }
 764                        Err(error) => {
 765                            let _ = share_tx.try_send(Err(error.into()));
 766                            return Err(anyhow!("failed to send initial update worktree"));
 767                        }
 768                    };
 769
 770                    for (path, summary) in diagnostic_summaries.iter() {
 771                        rpc.send(proto::UpdateDiagnosticSummary {
 772                            project_id,
 773                            worktree_id,
 774                            summary: Some(summary.to_proto(&path.0)),
 775                        })?;
 776                    }
 777
 778                    while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
 779                        let message =
 780                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, false);
 781                        rpc.request(message).await?;
 782                        prev_snapshot = snapshot;
 783                    }
 784
 785                    Ok::<_, anyhow::Error>(())
 786                }
 787                .log_err()
 788            });
 789            self.share = Some(ShareState {
 790                project_id,
 791                snapshots_tx: snapshots_to_send_tx.clone(),
 792                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
 793            });
 794        }
 795
 796        cx.spawn_weak(|this, cx| async move {
 797            register.await?;
 798            if let Some(this) = this.upgrade(&cx) {
 799                this.read_with(&cx, |this, _| {
 800                    let this = this.as_local().unwrap();
 801                    let _ = snapshots_to_send_tx.try_send(this.snapshot());
 802                });
 803            }
 804            share_rx
 805                .next()
 806                .await
 807                .unwrap_or_else(|| Err(anyhow!("share ended")))
 808        })
 809    }
 810
 811    pub fn unshare(&mut self) {
 812        self.share.take();
 813    }
 814
 815    pub fn is_shared(&self) -> bool {
 816        self.share.is_some()
 817    }
 818}
 819
 820impl RemoteWorktree {
 821    fn snapshot(&self) -> Snapshot {
 822        self.snapshot.clone()
 823    }
 824
 825    pub fn update_from_remote(
 826        &mut self,
 827        envelope: TypedEnvelope<proto::UpdateWorktree>,
 828    ) -> Result<()> {
 829        self.updates_tx
 830            .unbounded_send(envelope.payload)
 831            .expect("consumer runs to completion");
 832
 833        Ok(())
 834    }
 835
 836    pub fn update_diagnostic_summary(
 837        &mut self,
 838        path: Arc<Path>,
 839        summary: &proto::DiagnosticSummary,
 840    ) {
 841        self.diagnostic_summaries.insert(
 842            PathKey(path.clone()),
 843            DiagnosticSummary {
 844                error_count: summary.error_count as usize,
 845                warning_count: summary.warning_count as usize,
 846                info_count: summary.info_count as usize,
 847                hint_count: summary.hint_count as usize,
 848            },
 849        );
 850    }
 851}
 852
 853impl Snapshot {
 854    pub fn id(&self) -> WorktreeId {
 855        self.id
 856    }
 857
 858    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
 859        let mut entries_by_path_edits = Vec::new();
 860        let mut entries_by_id_edits = Vec::new();
 861        for entry_id in update.removed_entries {
 862            let entry_id = entry_id as usize;
 863            let entry = self
 864                .entry_for_id(entry_id)
 865                .ok_or_else(|| anyhow!("unknown entry"))?;
 866            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
 867            entries_by_id_edits.push(Edit::Remove(entry.id));
 868        }
 869
 870        for entry in update.updated_entries {
 871            let entry = Entry::try_from((&self.root_char_bag, entry))?;
 872            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
 873                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
 874            }
 875            entries_by_id_edits.push(Edit::Insert(PathEntry {
 876                id: entry.id,
 877                path: entry.path.clone(),
 878                is_ignored: entry.is_ignored,
 879                scan_id: 0,
 880            }));
 881            entries_by_path_edits.push(Edit::Insert(entry));
 882        }
 883
 884        self.entries_by_path.edit(entries_by_path_edits, &());
 885        self.entries_by_id.edit(entries_by_id_edits, &());
 886
 887        Ok(())
 888    }
 889
 890    pub fn file_count(&self) -> usize {
 891        self.entries_by_path.summary().file_count
 892    }
 893
 894    pub fn visible_file_count(&self) -> usize {
 895        self.entries_by_path.summary().visible_file_count
 896    }
 897
 898    fn traverse_from_offset(
 899        &self,
 900        include_dirs: bool,
 901        include_ignored: bool,
 902        start_offset: usize,
 903    ) -> Traversal {
 904        let mut cursor = self.entries_by_path.cursor();
 905        cursor.seek(
 906            &TraversalTarget::Count {
 907                count: start_offset,
 908                include_dirs,
 909                include_ignored,
 910            },
 911            Bias::Right,
 912            &(),
 913        );
 914        Traversal {
 915            cursor,
 916            include_dirs,
 917            include_ignored,
 918        }
 919    }
 920
 921    fn traverse_from_path(
 922        &self,
 923        include_dirs: bool,
 924        include_ignored: bool,
 925        path: &Path,
 926    ) -> Traversal {
 927        let mut cursor = self.entries_by_path.cursor();
 928        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
 929        Traversal {
 930            cursor,
 931            include_dirs,
 932            include_ignored,
 933        }
 934    }
 935
 936    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
 937        self.traverse_from_offset(false, include_ignored, start)
 938    }
 939
 940    pub fn entries(&self, include_ignored: bool) -> Traversal {
 941        self.traverse_from_offset(true, include_ignored, 0)
 942    }
 943
 944    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
 945        let empty_path = Path::new("");
 946        self.entries_by_path
 947            .cursor::<()>()
 948            .filter(move |entry| entry.path.as_ref() != empty_path)
 949            .map(|entry| &entry.path)
 950    }
 951
 952    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
 953        let mut cursor = self.entries_by_path.cursor();
 954        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
 955        let traversal = Traversal {
 956            cursor,
 957            include_dirs: true,
 958            include_ignored: true,
 959        };
 960        ChildEntriesIter {
 961            traversal,
 962            parent_path,
 963        }
 964    }
 965
 966    pub fn root_entry(&self) -> Option<&Entry> {
 967        self.entry_for_path("")
 968    }
 969
 970    pub fn root_name(&self) -> &str {
 971        &self.root_name
 972    }
 973
 974    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
 975        let path = path.as_ref();
 976        self.traverse_from_path(true, true, path)
 977            .entry()
 978            .and_then(|entry| {
 979                if entry.path.as_ref() == path {
 980                    Some(entry)
 981                } else {
 982                    None
 983                }
 984            })
 985    }
 986
 987    pub fn entry_for_id(&self, id: usize) -> Option<&Entry> {
 988        let entry = self.entries_by_id.get(&id, &())?;
 989        self.entry_for_path(&entry.path)
 990    }
 991
 992    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
 993        self.entry_for_path(path.as_ref()).map(|e| e.inode)
 994    }
 995}
 996
 997impl LocalSnapshot {
 998    pub fn abs_path(&self) -> &Arc<Path> {
 999        &self.abs_path
1000    }
1001
1002    #[cfg(test)]
1003    pub(crate) fn to_proto(
1004        &self,
1005        diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1006        visible: bool,
1007    ) -> proto::Worktree {
1008        let root_name = self.root_name.clone();
1009        proto::Worktree {
1010            id: self.id.0 as u64,
1011            root_name,
1012            entries: self
1013                .entries_by_path
1014                .iter()
1015                .filter(|e| !e.is_ignored)
1016                .map(Into::into)
1017                .collect(),
1018            diagnostic_summaries: diagnostic_summaries
1019                .iter()
1020                .map(|(path, summary)| summary.to_proto(&path.0))
1021                .collect(),
1022            visible,
1023        }
1024    }
1025
1026    pub(crate) fn build_update(
1027        &self,
1028        other: &Self,
1029        project_id: u64,
1030        worktree_id: u64,
1031        include_ignored: bool,
1032    ) -> proto::UpdateWorktree {
1033        let mut updated_entries = Vec::new();
1034        let mut removed_entries = Vec::new();
1035        let mut self_entries = self
1036            .entries_by_id
1037            .cursor::<()>()
1038            .filter(|e| include_ignored || !e.is_ignored)
1039            .peekable();
1040        let mut other_entries = other
1041            .entries_by_id
1042            .cursor::<()>()
1043            .filter(|e| include_ignored || !e.is_ignored)
1044            .peekable();
1045        loop {
1046            match (self_entries.peek(), other_entries.peek()) {
1047                (Some(self_entry), Some(other_entry)) => {
1048                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1049                        Ordering::Less => {
1050                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1051                            updated_entries.push(entry);
1052                            self_entries.next();
1053                        }
1054                        Ordering::Equal => {
1055                            if self_entry.scan_id != other_entry.scan_id {
1056                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1057                                updated_entries.push(entry);
1058                            }
1059
1060                            self_entries.next();
1061                            other_entries.next();
1062                        }
1063                        Ordering::Greater => {
1064                            removed_entries.push(other_entry.id as u64);
1065                            other_entries.next();
1066                        }
1067                    }
1068                }
1069                (Some(self_entry), None) => {
1070                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1071                    updated_entries.push(entry);
1072                    self_entries.next();
1073                }
1074                (None, Some(other_entry)) => {
1075                    removed_entries.push(other_entry.id as u64);
1076                    other_entries.next();
1077                }
1078                (None, None) => break,
1079            }
1080        }
1081
1082        proto::UpdateWorktree {
1083            project_id,
1084            worktree_id,
1085            root_name: self.root_name().to_string(),
1086            updated_entries,
1087            removed_entries,
1088        }
1089    }
1090
1091    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1092        if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1093            let abs_path = self.abs_path.join(&entry.path);
1094            match build_gitignore(&abs_path, fs) {
1095                Ok(ignore) => {
1096                    let ignore_dir_path = entry.path.parent().unwrap();
1097                    self.ignores
1098                        .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1099                }
1100                Err(error) => {
1101                    log::error!(
1102                        "error loading .gitignore file {:?} - {:?}",
1103                        &entry.path,
1104                        error
1105                    );
1106                }
1107            }
1108        }
1109
1110        self.reuse_entry_id(&mut entry);
1111        self.entries_by_path.insert_or_replace(entry.clone(), &());
1112        let scan_id = self.scan_id;
1113        self.entries_by_id.insert_or_replace(
1114            PathEntry {
1115                id: entry.id,
1116                path: entry.path.clone(),
1117                is_ignored: entry.is_ignored,
1118                scan_id,
1119            },
1120            &(),
1121        );
1122        entry
1123    }
1124
1125    fn populate_dir(
1126        &mut self,
1127        parent_path: Arc<Path>,
1128        entries: impl IntoIterator<Item = Entry>,
1129        ignore: Option<Arc<Gitignore>>,
1130    ) {
1131        let mut parent_entry = self
1132            .entries_by_path
1133            .get(&PathKey(parent_path.clone()), &())
1134            .unwrap()
1135            .clone();
1136        if let Some(ignore) = ignore {
1137            self.ignores.insert(parent_path, (ignore, self.scan_id));
1138        }
1139        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1140            parent_entry.kind = EntryKind::Dir;
1141        } else {
1142            unreachable!();
1143        }
1144
1145        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1146        let mut entries_by_id_edits = Vec::new();
1147
1148        for mut entry in entries {
1149            self.reuse_entry_id(&mut entry);
1150            entries_by_id_edits.push(Edit::Insert(PathEntry {
1151                id: entry.id,
1152                path: entry.path.clone(),
1153                is_ignored: entry.is_ignored,
1154                scan_id: self.scan_id,
1155            }));
1156            entries_by_path_edits.push(Edit::Insert(entry));
1157        }
1158
1159        self.entries_by_path.edit(entries_by_path_edits, &());
1160        self.entries_by_id.edit(entries_by_id_edits, &());
1161    }
1162
1163    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1164        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1165            entry.id = removed_entry_id;
1166        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1167            entry.id = existing_entry.id;
1168        }
1169    }
1170
1171    fn remove_path(&mut self, path: &Path) {
1172        let mut new_entries;
1173        let removed_entries;
1174        {
1175            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1176            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1177            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1178            new_entries.push_tree(cursor.suffix(&()), &());
1179        }
1180        self.entries_by_path = new_entries;
1181
1182        let mut entries_by_id_edits = Vec::new();
1183        for entry in removed_entries.cursor::<()>() {
1184            let removed_entry_id = self
1185                .removed_entry_ids
1186                .entry(entry.inode)
1187                .or_insert(entry.id);
1188            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1189            entries_by_id_edits.push(Edit::Remove(entry.id));
1190        }
1191        self.entries_by_id.edit(entries_by_id_edits, &());
1192
1193        if path.file_name() == Some(&GITIGNORE) {
1194            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1195                *scan_id = self.scan_id;
1196            }
1197        }
1198    }
1199
1200    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1201        let mut new_ignores = Vec::new();
1202        for ancestor in path.ancestors().skip(1) {
1203            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1204                new_ignores.push((ancestor, Some(ignore.clone())));
1205            } else {
1206                new_ignores.push((ancestor, None));
1207            }
1208        }
1209
1210        let mut ignore_stack = IgnoreStack::none();
1211        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1212            if ignore_stack.is_path_ignored(&parent_path, true) {
1213                ignore_stack = IgnoreStack::all();
1214                break;
1215            } else if let Some(ignore) = ignore {
1216                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1217            }
1218        }
1219
1220        if ignore_stack.is_path_ignored(path, is_dir) {
1221            ignore_stack = IgnoreStack::all();
1222        }
1223
1224        ignore_stack
1225    }
1226}
1227
1228fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1229    let contents = smol::block_on(fs.load(&abs_path))?;
1230    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1231    let mut builder = GitignoreBuilder::new(parent);
1232    for line in contents.lines() {
1233        builder.add_line(Some(abs_path.into()), line)?;
1234    }
1235    Ok(builder.build()?)
1236}
1237
1238impl WorktreeId {
1239    pub fn from_usize(handle_id: usize) -> Self {
1240        Self(handle_id)
1241    }
1242
1243    pub(crate) fn from_proto(id: u64) -> Self {
1244        Self(id as usize)
1245    }
1246
1247    pub fn to_proto(&self) -> u64 {
1248        self.0 as u64
1249    }
1250
1251    pub fn to_usize(&self) -> usize {
1252        self.0
1253    }
1254}
1255
1256impl fmt::Display for WorktreeId {
1257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258        self.0.fmt(f)
1259    }
1260}
1261
1262impl Deref for Worktree {
1263    type Target = Snapshot;
1264
1265    fn deref(&self) -> &Self::Target {
1266        match self {
1267            Worktree::Local(worktree) => &worktree.snapshot,
1268            Worktree::Remote(worktree) => &worktree.snapshot,
1269        }
1270    }
1271}
1272
1273impl Deref for LocalWorktree {
1274    type Target = LocalSnapshot;
1275
1276    fn deref(&self) -> &Self::Target {
1277        &self.snapshot
1278    }
1279}
1280
1281impl Deref for RemoteWorktree {
1282    type Target = Snapshot;
1283
1284    fn deref(&self) -> &Self::Target {
1285        &self.snapshot
1286    }
1287}
1288
1289impl fmt::Debug for LocalWorktree {
1290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1291        self.snapshot.fmt(f)
1292    }
1293}
1294
1295impl fmt::Debug for Snapshot {
1296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1297        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1298        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1299
1300        impl<'a> fmt::Debug for EntriesByPath<'a> {
1301            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1302                f.debug_map()
1303                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1304                    .finish()
1305            }
1306        }
1307
1308        impl<'a> fmt::Debug for EntriesById<'a> {
1309            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1310                f.debug_list().entries(self.0.iter()).finish()
1311            }
1312        }
1313
1314        f.debug_struct("Snapshot")
1315            .field("id", &self.id)
1316            .field("root_name", &self.root_name)
1317            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1318            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1319            .finish()
1320    }
1321}
1322
1323#[derive(Clone, PartialEq)]
1324pub struct File {
1325    pub worktree: ModelHandle<Worktree>,
1326    pub path: Arc<Path>,
1327    pub mtime: SystemTime,
1328    pub(crate) entry_id: Option<usize>,
1329    pub(crate) is_local: bool,
1330}
1331
1332impl language::File for File {
1333    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1334        if self.is_local {
1335            Some(self)
1336        } else {
1337            None
1338        }
1339    }
1340
1341    fn mtime(&self) -> SystemTime {
1342        self.mtime
1343    }
1344
1345    fn path(&self) -> &Arc<Path> {
1346        &self.path
1347    }
1348
1349    fn full_path(&self, cx: &AppContext) -> PathBuf {
1350        let mut full_path = PathBuf::new();
1351        full_path.push(self.worktree.read(cx).root_name());
1352        if self.path.components().next().is_some() {
1353            full_path.push(&self.path);
1354        }
1355        full_path
1356    }
1357
1358    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1359    /// of its worktree, then this method will return the name of the worktree itself.
1360    fn file_name(&self, cx: &AppContext) -> OsString {
1361        self.path
1362            .file_name()
1363            .map(|name| name.into())
1364            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1365    }
1366
1367    fn is_deleted(&self) -> bool {
1368        self.entry_id.is_none()
1369    }
1370
1371    fn save(
1372        &self,
1373        buffer_id: u64,
1374        text: Rope,
1375        version: clock::Global,
1376        cx: &mut MutableAppContext,
1377    ) -> Task<Result<(clock::Global, SystemTime)>> {
1378        self.worktree.update(cx, |worktree, cx| match worktree {
1379            Worktree::Local(worktree) => {
1380                let rpc = worktree.client.clone();
1381                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1382                let save = worktree.save(self.path.clone(), text, cx);
1383                cx.background().spawn(async move {
1384                    let entry = save.await?;
1385                    if let Some(project_id) = project_id {
1386                        rpc.send(proto::BufferSaved {
1387                            project_id,
1388                            buffer_id,
1389                            version: serialize_version(&version),
1390                            mtime: Some(entry.mtime.into()),
1391                        })?;
1392                    }
1393                    Ok((version, entry.mtime))
1394                })
1395            }
1396            Worktree::Remote(worktree) => {
1397                let rpc = worktree.client.clone();
1398                let project_id = worktree.project_id;
1399                cx.foreground().spawn(async move {
1400                    let response = rpc
1401                        .request(proto::SaveBuffer {
1402                            project_id,
1403                            buffer_id,
1404                            version: serialize_version(&version),
1405                        })
1406                        .await?;
1407                    let version = deserialize_version(response.version);
1408                    let mtime = response
1409                        .mtime
1410                        .ok_or_else(|| anyhow!("missing mtime"))?
1411                        .into();
1412                    Ok((version, mtime))
1413                })
1414            }
1415        })
1416    }
1417
1418    fn buffer_removed(&self, buffer_id: u64, cx: &mut MutableAppContext) {
1419        self.worktree.update(cx, |worktree, _| {
1420            if let Worktree::Remote(worktree) = worktree {
1421                worktree
1422                    .client
1423                    .send(proto::CloseBuffer {
1424                        project_id: worktree.project_id,
1425                        buffer_id,
1426                    })
1427                    .log_err();
1428            }
1429        });
1430    }
1431
1432    fn as_any(&self) -> &dyn Any {
1433        self
1434    }
1435
1436    fn to_proto(&self) -> rpc::proto::File {
1437        rpc::proto::File {
1438            worktree_id: self.worktree.id() as u64,
1439            entry_id: self.entry_id.map(|entry_id| entry_id as u64),
1440            path: self.path.to_string_lossy().into(),
1441            mtime: Some(self.mtime.into()),
1442        }
1443    }
1444}
1445
1446impl language::LocalFile for File {
1447    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1448        self.worktree
1449            .read(cx)
1450            .as_local()
1451            .unwrap()
1452            .abs_path
1453            .join(&self.path)
1454    }
1455
1456    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1457        let worktree = self.worktree.read(cx).as_local().unwrap();
1458        let abs_path = worktree.absolutize(&self.path);
1459        let fs = worktree.fs.clone();
1460        cx.background()
1461            .spawn(async move { fs.load(&abs_path).await })
1462    }
1463
1464    fn buffer_reloaded(
1465        &self,
1466        buffer_id: u64,
1467        version: &clock::Global,
1468        mtime: SystemTime,
1469        cx: &mut MutableAppContext,
1470    ) {
1471        let worktree = self.worktree.read(cx).as_local().unwrap();
1472        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1473            worktree
1474                .client
1475                .send(proto::BufferReloaded {
1476                    project_id,
1477                    buffer_id,
1478                    version: serialize_version(&version),
1479                    mtime: Some(mtime.into()),
1480                })
1481                .log_err();
1482        }
1483    }
1484}
1485
1486impl File {
1487    pub fn from_proto(
1488        proto: rpc::proto::File,
1489        worktree: ModelHandle<Worktree>,
1490        cx: &AppContext,
1491    ) -> Result<Self> {
1492        let worktree_id = worktree
1493            .read(cx)
1494            .as_remote()
1495            .ok_or_else(|| anyhow!("not remote"))?
1496            .id();
1497
1498        if worktree_id.to_proto() != proto.worktree_id {
1499            return Err(anyhow!("worktree id does not match file"));
1500        }
1501
1502        Ok(Self {
1503            worktree,
1504            path: Path::new(&proto.path).into(),
1505            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1506            entry_id: proto.entry_id.map(|entry_id| entry_id as usize),
1507            is_local: false,
1508        })
1509    }
1510
1511    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1512        file.and_then(|f| f.as_any().downcast_ref())
1513    }
1514
1515    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1516        self.worktree.read(cx).id()
1517    }
1518}
1519
1520#[derive(Clone, Debug, PartialEq, Eq)]
1521pub struct Entry {
1522    pub id: usize,
1523    pub kind: EntryKind,
1524    pub path: Arc<Path>,
1525    pub inode: u64,
1526    pub mtime: SystemTime,
1527    pub is_symlink: bool,
1528    pub is_ignored: bool,
1529}
1530
1531#[derive(Clone, Debug, PartialEq, Eq)]
1532pub enum EntryKind {
1533    PendingDir,
1534    Dir,
1535    File(CharBag),
1536}
1537
1538impl Entry {
1539    fn new(
1540        path: Arc<Path>,
1541        metadata: &fs::Metadata,
1542        next_entry_id: &AtomicUsize,
1543        root_char_bag: CharBag,
1544    ) -> Self {
1545        Self {
1546            id: next_entry_id.fetch_add(1, SeqCst),
1547            kind: if metadata.is_dir {
1548                EntryKind::PendingDir
1549            } else {
1550                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1551            },
1552            path,
1553            inode: metadata.inode,
1554            mtime: metadata.mtime,
1555            is_symlink: metadata.is_symlink,
1556            is_ignored: false,
1557        }
1558    }
1559
1560    pub fn is_dir(&self) -> bool {
1561        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1562    }
1563
1564    pub fn is_file(&self) -> bool {
1565        matches!(self.kind, EntryKind::File(_))
1566    }
1567}
1568
1569impl sum_tree::Item for Entry {
1570    type Summary = EntrySummary;
1571
1572    fn summary(&self) -> Self::Summary {
1573        let visible_count = if self.is_ignored { 0 } else { 1 };
1574        let file_count;
1575        let visible_file_count;
1576        if self.is_file() {
1577            file_count = 1;
1578            visible_file_count = visible_count;
1579        } else {
1580            file_count = 0;
1581            visible_file_count = 0;
1582        }
1583
1584        EntrySummary {
1585            max_path: self.path.clone(),
1586            count: 1,
1587            visible_count,
1588            file_count,
1589            visible_file_count,
1590        }
1591    }
1592}
1593
1594impl sum_tree::KeyedItem for Entry {
1595    type Key = PathKey;
1596
1597    fn key(&self) -> Self::Key {
1598        PathKey(self.path.clone())
1599    }
1600}
1601
1602#[derive(Clone, Debug)]
1603pub struct EntrySummary {
1604    max_path: Arc<Path>,
1605    count: usize,
1606    visible_count: usize,
1607    file_count: usize,
1608    visible_file_count: usize,
1609}
1610
1611impl Default for EntrySummary {
1612    fn default() -> Self {
1613        Self {
1614            max_path: Arc::from(Path::new("")),
1615            count: 0,
1616            visible_count: 0,
1617            file_count: 0,
1618            visible_file_count: 0,
1619        }
1620    }
1621}
1622
1623impl sum_tree::Summary for EntrySummary {
1624    type Context = ();
1625
1626    fn add_summary(&mut self, rhs: &Self, _: &()) {
1627        self.max_path = rhs.max_path.clone();
1628        self.visible_count += rhs.visible_count;
1629        self.file_count += rhs.file_count;
1630        self.visible_file_count += rhs.visible_file_count;
1631    }
1632}
1633
1634#[derive(Clone, Debug)]
1635struct PathEntry {
1636    id: usize,
1637    path: Arc<Path>,
1638    is_ignored: bool,
1639    scan_id: usize,
1640}
1641
1642impl sum_tree::Item for PathEntry {
1643    type Summary = PathEntrySummary;
1644
1645    fn summary(&self) -> Self::Summary {
1646        PathEntrySummary { max_id: self.id }
1647    }
1648}
1649
1650impl sum_tree::KeyedItem for PathEntry {
1651    type Key = usize;
1652
1653    fn key(&self) -> Self::Key {
1654        self.id
1655    }
1656}
1657
1658#[derive(Clone, Debug, Default)]
1659struct PathEntrySummary {
1660    max_id: usize,
1661}
1662
1663impl sum_tree::Summary for PathEntrySummary {
1664    type Context = ();
1665
1666    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1667        self.max_id = summary.max_id;
1668    }
1669}
1670
1671impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for usize {
1672    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1673        *self = summary.max_id;
1674    }
1675}
1676
1677#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1678pub struct PathKey(Arc<Path>);
1679
1680impl Default for PathKey {
1681    fn default() -> Self {
1682        Self(Path::new("").into())
1683    }
1684}
1685
1686impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1687    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1688        self.0 = summary.max_path.clone();
1689    }
1690}
1691
1692struct BackgroundScanner {
1693    fs: Arc<dyn Fs>,
1694    snapshot: Arc<Mutex<LocalSnapshot>>,
1695    notify: UnboundedSender<ScanState>,
1696    executor: Arc<executor::Background>,
1697}
1698
1699impl BackgroundScanner {
1700    fn new(
1701        snapshot: Arc<Mutex<LocalSnapshot>>,
1702        notify: UnboundedSender<ScanState>,
1703        fs: Arc<dyn Fs>,
1704        executor: Arc<executor::Background>,
1705    ) -> Self {
1706        Self {
1707            fs,
1708            snapshot,
1709            notify,
1710            executor,
1711        }
1712    }
1713
1714    fn abs_path(&self) -> Arc<Path> {
1715        self.snapshot.lock().abs_path.clone()
1716    }
1717
1718    fn snapshot(&self) -> LocalSnapshot {
1719        self.snapshot.lock().clone()
1720    }
1721
1722    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1723        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1724            return;
1725        }
1726
1727        if let Err(err) = self.scan_dirs().await {
1728            if self
1729                .notify
1730                .unbounded_send(ScanState::Err(Arc::new(err)))
1731                .is_err()
1732            {
1733                return;
1734            }
1735        }
1736
1737        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1738            return;
1739        }
1740
1741        futures::pin_mut!(events_rx);
1742        while let Some(events) = events_rx.next().await {
1743            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1744                break;
1745            }
1746
1747            if !self.process_events(events).await {
1748                break;
1749            }
1750
1751            if self.notify.unbounded_send(ScanState::Idle).is_err() {
1752                break;
1753            }
1754        }
1755    }
1756
1757    async fn scan_dirs(&mut self) -> Result<()> {
1758        let root_char_bag;
1759        let next_entry_id;
1760        let is_dir;
1761        {
1762            let snapshot = self.snapshot.lock();
1763            root_char_bag = snapshot.root_char_bag;
1764            next_entry_id = snapshot.next_entry_id.clone();
1765            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1766        };
1767
1768        if is_dir {
1769            let path: Arc<Path> = Arc::from(Path::new(""));
1770            let abs_path = self.abs_path();
1771            let (tx, rx) = channel::unbounded();
1772            tx.send(ScanJob {
1773                abs_path: abs_path.to_path_buf(),
1774                path,
1775                ignore_stack: IgnoreStack::none(),
1776                scan_queue: tx.clone(),
1777            })
1778            .await
1779            .unwrap();
1780            drop(tx);
1781
1782            self.executor
1783                .scoped(|scope| {
1784                    for _ in 0..self.executor.num_cpus() {
1785                        scope.spawn(async {
1786                            while let Ok(job) = rx.recv().await {
1787                                if let Err(err) = self
1788                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1789                                    .await
1790                                {
1791                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
1792                                }
1793                            }
1794                        });
1795                    }
1796                })
1797                .await;
1798        }
1799
1800        Ok(())
1801    }
1802
1803    async fn scan_dir(
1804        &self,
1805        root_char_bag: CharBag,
1806        next_entry_id: Arc<AtomicUsize>,
1807        job: &ScanJob,
1808    ) -> Result<()> {
1809        let mut new_entries: Vec<Entry> = Vec::new();
1810        let mut new_jobs: Vec<ScanJob> = Vec::new();
1811        let mut ignore_stack = job.ignore_stack.clone();
1812        let mut new_ignore = None;
1813
1814        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1815        while let Some(child_abs_path) = child_paths.next().await {
1816            let child_abs_path = match child_abs_path {
1817                Ok(child_abs_path) => child_abs_path,
1818                Err(error) => {
1819                    log::error!("error processing entry {:?}", error);
1820                    continue;
1821                }
1822            };
1823            let child_name = child_abs_path.file_name().unwrap();
1824            let child_path: Arc<Path> = job.path.join(child_name).into();
1825            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
1826                Some(metadata) => metadata,
1827                None => continue,
1828            };
1829
1830            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
1831            if child_name == *GITIGNORE {
1832                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
1833                    Ok(ignore) => {
1834                        let ignore = Arc::new(ignore);
1835                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
1836                        new_ignore = Some(ignore);
1837                    }
1838                    Err(error) => {
1839                        log::error!(
1840                            "error loading .gitignore file {:?} - {:?}",
1841                            child_name,
1842                            error
1843                        );
1844                    }
1845                }
1846
1847                // Update ignore status of any child entries we've already processed to reflect the
1848                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
1849                // there should rarely be too numerous. Update the ignore stack associated with any
1850                // new jobs as well.
1851                let mut new_jobs = new_jobs.iter_mut();
1852                for entry in &mut new_entries {
1853                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
1854                    if entry.is_dir() {
1855                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
1856                            IgnoreStack::all()
1857                        } else {
1858                            ignore_stack.clone()
1859                        };
1860                    }
1861                }
1862            }
1863
1864            let mut child_entry = Entry::new(
1865                child_path.clone(),
1866                &child_metadata,
1867                &next_entry_id,
1868                root_char_bag,
1869            );
1870
1871            if child_metadata.is_dir {
1872                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
1873                child_entry.is_ignored = is_ignored;
1874                new_entries.push(child_entry);
1875                new_jobs.push(ScanJob {
1876                    abs_path: child_abs_path,
1877                    path: child_path,
1878                    ignore_stack: if is_ignored {
1879                        IgnoreStack::all()
1880                    } else {
1881                        ignore_stack.clone()
1882                    },
1883                    scan_queue: job.scan_queue.clone(),
1884                });
1885            } else {
1886                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
1887                new_entries.push(child_entry);
1888            };
1889        }
1890
1891        self.snapshot
1892            .lock()
1893            .populate_dir(job.path.clone(), new_entries, new_ignore);
1894        for new_job in new_jobs {
1895            job.scan_queue.send(new_job).await.unwrap();
1896        }
1897
1898        Ok(())
1899    }
1900
1901    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
1902        let mut snapshot = self.snapshot();
1903        snapshot.scan_id += 1;
1904
1905        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
1906            abs_path
1907        } else {
1908            return false;
1909        };
1910        let root_char_bag = snapshot.root_char_bag;
1911        let next_entry_id = snapshot.next_entry_id.clone();
1912
1913        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
1914        events.dedup_by(|a, b| a.path.starts_with(&b.path));
1915
1916        for event in &events {
1917            match event.path.strip_prefix(&root_abs_path) {
1918                Ok(path) => snapshot.remove_path(&path),
1919                Err(_) => {
1920                    log::error!(
1921                        "unexpected event {:?} for root path {:?}",
1922                        event.path,
1923                        root_abs_path
1924                    );
1925                    continue;
1926                }
1927            }
1928        }
1929
1930        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
1931        for event in events {
1932            let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
1933                Ok(path) => Arc::from(path.to_path_buf()),
1934                Err(_) => {
1935                    log::error!(
1936                        "unexpected event {:?} for root path {:?}",
1937                        event.path,
1938                        root_abs_path
1939                    );
1940                    continue;
1941                }
1942            };
1943
1944            match self.fs.metadata(&event.path).await {
1945                Ok(Some(metadata)) => {
1946                    let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
1947                    let mut fs_entry = Entry::new(
1948                        path.clone(),
1949                        &metadata,
1950                        snapshot.next_entry_id.as_ref(),
1951                        snapshot.root_char_bag,
1952                    );
1953                    fs_entry.is_ignored = ignore_stack.is_all();
1954                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
1955                    if metadata.is_dir {
1956                        scan_queue_tx
1957                            .send(ScanJob {
1958                                abs_path: event.path,
1959                                path,
1960                                ignore_stack,
1961                                scan_queue: scan_queue_tx.clone(),
1962                            })
1963                            .await
1964                            .unwrap();
1965                    }
1966                }
1967                Ok(None) => {}
1968                Err(err) => {
1969                    // TODO - create a special 'error' entry in the entries tree to mark this
1970                    log::error!("error reading file on event {:?}", err);
1971                }
1972            }
1973        }
1974
1975        *self.snapshot.lock() = snapshot;
1976
1977        // Scan any directories that were created as part of this event batch.
1978        drop(scan_queue_tx);
1979        self.executor
1980            .scoped(|scope| {
1981                for _ in 0..self.executor.num_cpus() {
1982                    scope.spawn(async {
1983                        while let Ok(job) = scan_queue_rx.recv().await {
1984                            if let Err(err) = self
1985                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1986                                .await
1987                            {
1988                                log::error!("error scanning {:?}: {}", job.abs_path, err);
1989                            }
1990                        }
1991                    });
1992                }
1993            })
1994            .await;
1995
1996        // Attempt to detect renames only over a single batch of file-system events.
1997        self.snapshot.lock().removed_entry_ids.clear();
1998
1999        self.update_ignore_statuses().await;
2000        true
2001    }
2002
2003    async fn update_ignore_statuses(&self) {
2004        let mut snapshot = self.snapshot();
2005
2006        let mut ignores_to_update = Vec::new();
2007        let mut ignores_to_delete = Vec::new();
2008        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2009            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2010                ignores_to_update.push(parent_path.clone());
2011            }
2012
2013            let ignore_path = parent_path.join(&*GITIGNORE);
2014            if snapshot.entry_for_path(ignore_path).is_none() {
2015                ignores_to_delete.push(parent_path.clone());
2016            }
2017        }
2018
2019        for parent_path in ignores_to_delete {
2020            snapshot.ignores.remove(&parent_path);
2021            self.snapshot.lock().ignores.remove(&parent_path);
2022        }
2023
2024        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2025        ignores_to_update.sort_unstable();
2026        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2027        while let Some(parent_path) = ignores_to_update.next() {
2028            while ignores_to_update
2029                .peek()
2030                .map_or(false, |p| p.starts_with(&parent_path))
2031            {
2032                ignores_to_update.next().unwrap();
2033            }
2034
2035            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2036            ignore_queue_tx
2037                .send(UpdateIgnoreStatusJob {
2038                    path: parent_path,
2039                    ignore_stack,
2040                    ignore_queue: ignore_queue_tx.clone(),
2041                })
2042                .await
2043                .unwrap();
2044        }
2045        drop(ignore_queue_tx);
2046
2047        self.executor
2048            .scoped(|scope| {
2049                for _ in 0..self.executor.num_cpus() {
2050                    scope.spawn(async {
2051                        while let Ok(job) = ignore_queue_rx.recv().await {
2052                            self.update_ignore_status(job, &snapshot).await;
2053                        }
2054                    });
2055                }
2056            })
2057            .await;
2058    }
2059
2060    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2061        let mut ignore_stack = job.ignore_stack;
2062        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2063            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2064        }
2065
2066        let mut entries_by_id_edits = Vec::new();
2067        let mut entries_by_path_edits = Vec::new();
2068        for mut entry in snapshot.child_entries(&job.path).cloned() {
2069            let was_ignored = entry.is_ignored;
2070            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2071            if entry.is_dir() {
2072                let child_ignore_stack = if entry.is_ignored {
2073                    IgnoreStack::all()
2074                } else {
2075                    ignore_stack.clone()
2076                };
2077                job.ignore_queue
2078                    .send(UpdateIgnoreStatusJob {
2079                        path: entry.path.clone(),
2080                        ignore_stack: child_ignore_stack,
2081                        ignore_queue: job.ignore_queue.clone(),
2082                    })
2083                    .await
2084                    .unwrap();
2085            }
2086
2087            if entry.is_ignored != was_ignored {
2088                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2089                path_entry.scan_id = snapshot.scan_id;
2090                path_entry.is_ignored = entry.is_ignored;
2091                entries_by_id_edits.push(Edit::Insert(path_entry));
2092                entries_by_path_edits.push(Edit::Insert(entry));
2093            }
2094        }
2095
2096        let mut snapshot = self.snapshot.lock();
2097        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2098        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2099    }
2100}
2101
2102async fn refresh_entry(
2103    fs: &dyn Fs,
2104    snapshot: &Mutex<LocalSnapshot>,
2105    path: Arc<Path>,
2106    abs_path: &Path,
2107) -> Result<Entry> {
2108    let root_char_bag;
2109    let next_entry_id;
2110    {
2111        let snapshot = snapshot.lock();
2112        root_char_bag = snapshot.root_char_bag;
2113        next_entry_id = snapshot.next_entry_id.clone();
2114    }
2115    let entry = Entry::new(
2116        path,
2117        &fs.metadata(abs_path)
2118            .await?
2119            .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2120        &next_entry_id,
2121        root_char_bag,
2122    );
2123    Ok(snapshot.lock().insert_entry(entry, fs))
2124}
2125
2126fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2127    let mut result = root_char_bag;
2128    result.extend(
2129        path.to_string_lossy()
2130            .chars()
2131            .map(|c| c.to_ascii_lowercase()),
2132    );
2133    result
2134}
2135
2136struct ScanJob {
2137    abs_path: PathBuf,
2138    path: Arc<Path>,
2139    ignore_stack: Arc<IgnoreStack>,
2140    scan_queue: Sender<ScanJob>,
2141}
2142
2143struct UpdateIgnoreStatusJob {
2144    path: Arc<Path>,
2145    ignore_stack: Arc<IgnoreStack>,
2146    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2147}
2148
2149pub trait WorktreeHandle {
2150    #[cfg(any(test, feature = "test-support"))]
2151    fn flush_fs_events<'a>(
2152        &self,
2153        cx: &'a gpui::TestAppContext,
2154    ) -> futures::future::LocalBoxFuture<'a, ()>;
2155}
2156
2157impl WorktreeHandle for ModelHandle<Worktree> {
2158    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2159    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2160    // extra directory scans, and emit extra scan-state notifications.
2161    //
2162    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2163    // to ensure that all redundant FS events have already been processed.
2164    #[cfg(any(test, feature = "test-support"))]
2165    fn flush_fs_events<'a>(
2166        &self,
2167        cx: &'a gpui::TestAppContext,
2168    ) -> futures::future::LocalBoxFuture<'a, ()> {
2169        use smol::future::FutureExt;
2170
2171        let filename = "fs-event-sentinel";
2172        let tree = self.clone();
2173        let (fs, root_path) = self.read_with(cx, |tree, _| {
2174            let tree = tree.as_local().unwrap();
2175            (tree.fs.clone(), tree.abs_path().clone())
2176        });
2177
2178        async move {
2179            fs.create_file(&root_path.join(filename), Default::default())
2180                .await
2181                .unwrap();
2182            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2183                .await;
2184
2185            fs.remove_file(&root_path.join(filename), Default::default())
2186                .await
2187                .unwrap();
2188            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2189                .await;
2190
2191            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2192                .await;
2193        }
2194        .boxed_local()
2195    }
2196}
2197
2198#[derive(Clone, Debug)]
2199struct TraversalProgress<'a> {
2200    max_path: &'a Path,
2201    count: usize,
2202    visible_count: usize,
2203    file_count: usize,
2204    visible_file_count: usize,
2205}
2206
2207impl<'a> TraversalProgress<'a> {
2208    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2209        match (include_ignored, include_dirs) {
2210            (true, true) => self.count,
2211            (true, false) => self.file_count,
2212            (false, true) => self.visible_count,
2213            (false, false) => self.visible_file_count,
2214        }
2215    }
2216}
2217
2218impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2219    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2220        self.max_path = summary.max_path.as_ref();
2221        self.count += summary.count;
2222        self.visible_count += summary.visible_count;
2223        self.file_count += summary.file_count;
2224        self.visible_file_count += summary.visible_file_count;
2225    }
2226}
2227
2228impl<'a> Default for TraversalProgress<'a> {
2229    fn default() -> Self {
2230        Self {
2231            max_path: Path::new(""),
2232            count: 0,
2233            visible_count: 0,
2234            file_count: 0,
2235            visible_file_count: 0,
2236        }
2237    }
2238}
2239
2240pub struct Traversal<'a> {
2241    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2242    include_ignored: bool,
2243    include_dirs: bool,
2244}
2245
2246impl<'a> Traversal<'a> {
2247    pub fn advance(&mut self) -> bool {
2248        self.advance_to_offset(self.offset() + 1)
2249    }
2250
2251    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2252        self.cursor.seek_forward(
2253            &TraversalTarget::Count {
2254                count: offset,
2255                include_dirs: self.include_dirs,
2256                include_ignored: self.include_ignored,
2257            },
2258            Bias::Right,
2259            &(),
2260        )
2261    }
2262
2263    pub fn advance_to_sibling(&mut self) -> bool {
2264        while let Some(entry) = self.cursor.item() {
2265            self.cursor.seek_forward(
2266                &TraversalTarget::PathSuccessor(&entry.path),
2267                Bias::Left,
2268                &(),
2269            );
2270            if let Some(entry) = self.cursor.item() {
2271                if (self.include_dirs || !entry.is_dir())
2272                    && (self.include_ignored || !entry.is_ignored)
2273                {
2274                    return true;
2275                }
2276            }
2277        }
2278        false
2279    }
2280
2281    pub fn entry(&self) -> Option<&'a Entry> {
2282        self.cursor.item()
2283    }
2284
2285    pub fn offset(&self) -> usize {
2286        self.cursor
2287            .start()
2288            .count(self.include_dirs, self.include_ignored)
2289    }
2290}
2291
2292impl<'a> Iterator for Traversal<'a> {
2293    type Item = &'a Entry;
2294
2295    fn next(&mut self) -> Option<Self::Item> {
2296        if let Some(item) = self.entry() {
2297            self.advance();
2298            Some(item)
2299        } else {
2300            None
2301        }
2302    }
2303}
2304
2305#[derive(Debug)]
2306enum TraversalTarget<'a> {
2307    Path(&'a Path),
2308    PathSuccessor(&'a Path),
2309    Count {
2310        count: usize,
2311        include_ignored: bool,
2312        include_dirs: bool,
2313    },
2314}
2315
2316impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2317    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2318        match self {
2319            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2320            TraversalTarget::PathSuccessor(path) => {
2321                if !cursor_location.max_path.starts_with(path) {
2322                    Ordering::Equal
2323                } else {
2324                    Ordering::Greater
2325                }
2326            }
2327            TraversalTarget::Count {
2328                count,
2329                include_dirs,
2330                include_ignored,
2331            } => Ord::cmp(
2332                count,
2333                &cursor_location.count(*include_dirs, *include_ignored),
2334            ),
2335        }
2336    }
2337}
2338
2339struct ChildEntriesIter<'a> {
2340    parent_path: &'a Path,
2341    traversal: Traversal<'a>,
2342}
2343
2344impl<'a> Iterator for ChildEntriesIter<'a> {
2345    type Item = &'a Entry;
2346
2347    fn next(&mut self) -> Option<Self::Item> {
2348        if let Some(item) = self.traversal.entry() {
2349            if item.path.starts_with(&self.parent_path) {
2350                self.traversal.advance_to_sibling();
2351                return Some(item);
2352            }
2353        }
2354        None
2355    }
2356}
2357
2358impl<'a> From<&'a Entry> for proto::Entry {
2359    fn from(entry: &'a Entry) -> Self {
2360        Self {
2361            id: entry.id as u64,
2362            is_dir: entry.is_dir(),
2363            path: entry.path.to_string_lossy().to_string(),
2364            inode: entry.inode,
2365            mtime: Some(entry.mtime.into()),
2366            is_symlink: entry.is_symlink,
2367            is_ignored: entry.is_ignored,
2368        }
2369    }
2370}
2371
2372impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2373    type Error = anyhow::Error;
2374
2375    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2376        if let Some(mtime) = entry.mtime {
2377            let kind = if entry.is_dir {
2378                EntryKind::Dir
2379            } else {
2380                let mut char_bag = root_char_bag.clone();
2381                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2382                EntryKind::File(char_bag)
2383            };
2384            let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2385            Ok(Entry {
2386                id: entry.id as usize,
2387                kind,
2388                path: path.clone(),
2389                inode: entry.inode,
2390                mtime: mtime.into(),
2391                is_symlink: entry.is_symlink,
2392                is_ignored: entry.is_ignored,
2393            })
2394        } else {
2395            Err(anyhow!(
2396                "missing mtime in remote worktree entry {:?}",
2397                entry.path
2398            ))
2399        }
2400    }
2401}
2402
2403#[cfg(test)]
2404mod tests {
2405    use super::*;
2406    use crate::fs::FakeFs;
2407    use anyhow::Result;
2408    use client::test::FakeHttpClient;
2409    use fs::RealFs;
2410    use rand::prelude::*;
2411    use serde_json::json;
2412    use std::{
2413        env,
2414        fmt::Write,
2415        time::{SystemTime, UNIX_EPOCH},
2416    };
2417    use util::test::temp_tree;
2418
2419    #[gpui::test]
2420    async fn test_traversal(cx: &mut gpui::TestAppContext) {
2421        let fs = FakeFs::new(cx.background());
2422        fs.insert_tree(
2423            "/root",
2424            json!({
2425               ".gitignore": "a/b\n",
2426               "a": {
2427                   "b": "",
2428                   "c": "",
2429               }
2430            }),
2431        )
2432        .await;
2433
2434        let http_client = FakeHttpClient::with_404_response();
2435        let client = Client::new(http_client);
2436
2437        let tree = Worktree::local(
2438            client,
2439            Arc::from(Path::new("/root")),
2440            true,
2441            fs,
2442            &mut cx.to_async(),
2443        )
2444        .await
2445        .unwrap();
2446        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2447            .await;
2448
2449        tree.read_with(cx, |tree, _| {
2450            assert_eq!(
2451                tree.entries(false)
2452                    .map(|entry| entry.path.as_ref())
2453                    .collect::<Vec<_>>(),
2454                vec![
2455                    Path::new(""),
2456                    Path::new(".gitignore"),
2457                    Path::new("a"),
2458                    Path::new("a/c"),
2459                ]
2460            );
2461        })
2462    }
2463
2464    #[gpui::test]
2465    async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2466        let dir = temp_tree(json!({
2467            ".git": {},
2468            ".gitignore": "ignored-dir\n",
2469            "tracked-dir": {
2470                "tracked-file1": "tracked contents",
2471            },
2472            "ignored-dir": {
2473                "ignored-file1": "ignored contents",
2474            }
2475        }));
2476
2477        let http_client = FakeHttpClient::with_404_response();
2478        let client = Client::new(http_client.clone());
2479
2480        let tree = Worktree::local(
2481            client,
2482            dir.path(),
2483            true,
2484            Arc::new(RealFs),
2485            &mut cx.to_async(),
2486        )
2487        .await
2488        .unwrap();
2489        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2490            .await;
2491        tree.flush_fs_events(&cx).await;
2492        cx.read(|cx| {
2493            let tree = tree.read(cx);
2494            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2495            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2496            assert_eq!(tracked.is_ignored, false);
2497            assert_eq!(ignored.is_ignored, true);
2498        });
2499
2500        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2501        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2502        tree.flush_fs_events(&cx).await;
2503        cx.read(|cx| {
2504            let tree = tree.read(cx);
2505            let dot_git = tree.entry_for_path(".git").unwrap();
2506            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2507            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2508            assert_eq!(tracked.is_ignored, false);
2509            assert_eq!(ignored.is_ignored, true);
2510            assert_eq!(dot_git.is_ignored, true);
2511        });
2512    }
2513
2514    #[gpui::test(iterations = 100)]
2515    fn test_random(mut rng: StdRng) {
2516        let operations = env::var("OPERATIONS")
2517            .map(|o| o.parse().unwrap())
2518            .unwrap_or(40);
2519        let initial_entries = env::var("INITIAL_ENTRIES")
2520            .map(|o| o.parse().unwrap())
2521            .unwrap_or(20);
2522
2523        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2524        for _ in 0..initial_entries {
2525            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2526        }
2527        log::info!("Generated initial tree");
2528
2529        let (notify_tx, _notify_rx) = mpsc::unbounded();
2530        let fs = Arc::new(RealFs);
2531        let next_entry_id = Arc::new(AtomicUsize::new(0));
2532        let mut initial_snapshot = LocalSnapshot {
2533            abs_path: root_dir.path().into(),
2534            scan_id: 0,
2535            removed_entry_ids: Default::default(),
2536            ignores: Default::default(),
2537            next_entry_id: next_entry_id.clone(),
2538            snapshot: Snapshot {
2539                id: WorktreeId::from_usize(0),
2540                entries_by_path: Default::default(),
2541                entries_by_id: Default::default(),
2542                root_name: Default::default(),
2543                root_char_bag: Default::default(),
2544            },
2545        };
2546        initial_snapshot.insert_entry(
2547            Entry::new(
2548                Path::new("").into(),
2549                &smol::block_on(fs.metadata(root_dir.path()))
2550                    .unwrap()
2551                    .unwrap(),
2552                &next_entry_id,
2553                Default::default(),
2554            ),
2555            fs.as_ref(),
2556        );
2557        let mut scanner = BackgroundScanner::new(
2558            Arc::new(Mutex::new(initial_snapshot.clone())),
2559            notify_tx,
2560            fs.clone(),
2561            Arc::new(gpui::executor::Background::new()),
2562        );
2563        smol::block_on(scanner.scan_dirs()).unwrap();
2564        scanner.snapshot().check_invariants();
2565
2566        let mut events = Vec::new();
2567        let mut snapshots = Vec::new();
2568        let mut mutations_len = operations;
2569        while mutations_len > 1 {
2570            if !events.is_empty() && rng.gen_bool(0.4) {
2571                let len = rng.gen_range(0..=events.len());
2572                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2573                log::info!("Delivering events: {:#?}", to_deliver);
2574                smol::block_on(scanner.process_events(to_deliver));
2575                scanner.snapshot().check_invariants();
2576            } else {
2577                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2578                mutations_len -= 1;
2579            }
2580
2581            if rng.gen_bool(0.2) {
2582                snapshots.push(scanner.snapshot());
2583            }
2584        }
2585        log::info!("Quiescing: {:#?}", events);
2586        smol::block_on(scanner.process_events(events));
2587        scanner.snapshot().check_invariants();
2588
2589        let (notify_tx, _notify_rx) = mpsc::unbounded();
2590        let mut new_scanner = BackgroundScanner::new(
2591            Arc::new(Mutex::new(initial_snapshot)),
2592            notify_tx,
2593            scanner.fs.clone(),
2594            scanner.executor.clone(),
2595        );
2596        smol::block_on(new_scanner.scan_dirs()).unwrap();
2597        assert_eq!(
2598            scanner.snapshot().to_vec(true),
2599            new_scanner.snapshot().to_vec(true)
2600        );
2601
2602        for mut prev_snapshot in snapshots {
2603            let include_ignored = rng.gen::<bool>();
2604            if !include_ignored {
2605                let mut entries_by_path_edits = Vec::new();
2606                let mut entries_by_id_edits = Vec::new();
2607                for entry in prev_snapshot
2608                    .entries_by_id
2609                    .cursor::<()>()
2610                    .filter(|e| e.is_ignored)
2611                {
2612                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2613                    entries_by_id_edits.push(Edit::Remove(entry.id));
2614                }
2615
2616                prev_snapshot
2617                    .entries_by_path
2618                    .edit(entries_by_path_edits, &());
2619                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2620            }
2621
2622            let update = scanner
2623                .snapshot()
2624                .build_update(&prev_snapshot, 0, 0, include_ignored);
2625            prev_snapshot.apply_remote_update(update).unwrap();
2626            assert_eq!(
2627                prev_snapshot.to_vec(true),
2628                scanner.snapshot().to_vec(include_ignored)
2629            );
2630        }
2631    }
2632
2633    fn randomly_mutate_tree(
2634        root_path: &Path,
2635        insertion_probability: f64,
2636        rng: &mut impl Rng,
2637    ) -> Result<Vec<fsevent::Event>> {
2638        let root_path = root_path.canonicalize().unwrap();
2639        let (dirs, files) = read_dir_recursive(root_path.clone());
2640
2641        let mut events = Vec::new();
2642        let mut record_event = |path: PathBuf| {
2643            events.push(fsevent::Event {
2644                event_id: SystemTime::now()
2645                    .duration_since(UNIX_EPOCH)
2646                    .unwrap()
2647                    .as_secs(),
2648                flags: fsevent::StreamFlags::empty(),
2649                path,
2650            });
2651        };
2652
2653        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2654            let path = dirs.choose(rng).unwrap();
2655            let new_path = path.join(gen_name(rng));
2656
2657            if rng.gen() {
2658                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2659                std::fs::create_dir(&new_path)?;
2660            } else {
2661                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2662                std::fs::write(&new_path, "")?;
2663            }
2664            record_event(new_path);
2665        } else if rng.gen_bool(0.05) {
2666            let ignore_dir_path = dirs.choose(rng).unwrap();
2667            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2668
2669            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2670            let files_to_ignore = {
2671                let len = rng.gen_range(0..=subfiles.len());
2672                subfiles.choose_multiple(rng, len)
2673            };
2674            let dirs_to_ignore = {
2675                let len = rng.gen_range(0..subdirs.len());
2676                subdirs.choose_multiple(rng, len)
2677            };
2678
2679            let mut ignore_contents = String::new();
2680            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2681                write!(
2682                    ignore_contents,
2683                    "{}\n",
2684                    path_to_ignore
2685                        .strip_prefix(&ignore_dir_path)?
2686                        .to_str()
2687                        .unwrap()
2688                )
2689                .unwrap();
2690            }
2691            log::info!(
2692                "Creating {:?} with contents:\n{}",
2693                ignore_path.strip_prefix(&root_path)?,
2694                ignore_contents
2695            );
2696            std::fs::write(&ignore_path, ignore_contents).unwrap();
2697            record_event(ignore_path);
2698        } else {
2699            let old_path = {
2700                let file_path = files.choose(rng);
2701                let dir_path = dirs[1..].choose(rng);
2702                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2703            };
2704
2705            let is_rename = rng.gen();
2706            if is_rename {
2707                let new_path_parent = dirs
2708                    .iter()
2709                    .filter(|d| !d.starts_with(old_path))
2710                    .choose(rng)
2711                    .unwrap();
2712
2713                let overwrite_existing_dir =
2714                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2715                let new_path = if overwrite_existing_dir {
2716                    std::fs::remove_dir_all(&new_path_parent).ok();
2717                    new_path_parent.to_path_buf()
2718                } else {
2719                    new_path_parent.join(gen_name(rng))
2720                };
2721
2722                log::info!(
2723                    "Renaming {:?} to {}{:?}",
2724                    old_path.strip_prefix(&root_path)?,
2725                    if overwrite_existing_dir {
2726                        "overwrite "
2727                    } else {
2728                        ""
2729                    },
2730                    new_path.strip_prefix(&root_path)?
2731                );
2732                std::fs::rename(&old_path, &new_path)?;
2733                record_event(old_path.clone());
2734                record_event(new_path);
2735            } else if old_path.is_dir() {
2736                let (dirs, files) = read_dir_recursive(old_path.clone());
2737
2738                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2739                std::fs::remove_dir_all(&old_path).unwrap();
2740                for file in files {
2741                    record_event(file);
2742                }
2743                for dir in dirs {
2744                    record_event(dir);
2745                }
2746            } else {
2747                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2748                std::fs::remove_file(old_path).unwrap();
2749                record_event(old_path.clone());
2750            }
2751        }
2752
2753        Ok(events)
2754    }
2755
2756    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2757        let child_entries = std::fs::read_dir(&path).unwrap();
2758        let mut dirs = vec![path];
2759        let mut files = Vec::new();
2760        for child_entry in child_entries {
2761            let child_path = child_entry.unwrap().path();
2762            if child_path.is_dir() {
2763                let (child_dirs, child_files) = read_dir_recursive(child_path);
2764                dirs.extend(child_dirs);
2765                files.extend(child_files);
2766            } else {
2767                files.push(child_path);
2768            }
2769        }
2770        (dirs, files)
2771    }
2772
2773    fn gen_name(rng: &mut impl Rng) -> String {
2774        (0..6)
2775            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2776            .map(char::from)
2777            .collect()
2778    }
2779
2780    impl LocalSnapshot {
2781        fn check_invariants(&self) {
2782            let mut files = self.files(true, 0);
2783            let mut visible_files = self.files(false, 0);
2784            for entry in self.entries_by_path.cursor::<()>() {
2785                if entry.is_file() {
2786                    assert_eq!(files.next().unwrap().inode, entry.inode);
2787                    if !entry.is_ignored {
2788                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2789                    }
2790                }
2791            }
2792            assert!(files.next().is_none());
2793            assert!(visible_files.next().is_none());
2794
2795            let mut bfs_paths = Vec::new();
2796            let mut stack = vec![Path::new("")];
2797            while let Some(path) = stack.pop() {
2798                bfs_paths.push(path);
2799                let ix = stack.len();
2800                for child_entry in self.child_entries(path) {
2801                    stack.insert(ix, &child_entry.path);
2802                }
2803            }
2804
2805            let dfs_paths = self
2806                .entries_by_path
2807                .cursor::<()>()
2808                .map(|e| e.path.as_ref())
2809                .collect::<Vec<_>>();
2810            assert_eq!(bfs_paths, dfs_paths);
2811
2812            for (ignore_parent_path, _) in &self.ignores {
2813                assert!(self.entry_for_path(ignore_parent_path).is_some());
2814                assert!(self
2815                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2816                    .is_some());
2817            }
2818        }
2819
2820        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2821            let mut paths = Vec::new();
2822            for entry in self.entries_by_path.cursor::<()>() {
2823                if include_ignored || !entry.is_ignored {
2824                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2825                }
2826            }
2827            paths.sort_by(|a, b| a.0.cmp(&b.0));
2828            paths
2829        }
2830    }
2831}