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 as_any(&self) -> &dyn Any {
1419        self
1420    }
1421
1422    fn to_proto(&self) -> rpc::proto::File {
1423        rpc::proto::File {
1424            worktree_id: self.worktree.id() as u64,
1425            entry_id: self.entry_id.map(|entry_id| entry_id as u64),
1426            path: self.path.to_string_lossy().into(),
1427            mtime: Some(self.mtime.into()),
1428        }
1429    }
1430}
1431
1432impl language::LocalFile for File {
1433    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1434        self.worktree
1435            .read(cx)
1436            .as_local()
1437            .unwrap()
1438            .abs_path
1439            .join(&self.path)
1440    }
1441
1442    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1443        let worktree = self.worktree.read(cx).as_local().unwrap();
1444        let abs_path = worktree.absolutize(&self.path);
1445        let fs = worktree.fs.clone();
1446        cx.background()
1447            .spawn(async move { fs.load(&abs_path).await })
1448    }
1449
1450    fn buffer_reloaded(
1451        &self,
1452        buffer_id: u64,
1453        version: &clock::Global,
1454        mtime: SystemTime,
1455        cx: &mut MutableAppContext,
1456    ) {
1457        let worktree = self.worktree.read(cx).as_local().unwrap();
1458        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1459            worktree
1460                .client
1461                .send(proto::BufferReloaded {
1462                    project_id,
1463                    buffer_id,
1464                    version: serialize_version(&version),
1465                    mtime: Some(mtime.into()),
1466                })
1467                .log_err();
1468        }
1469    }
1470}
1471
1472impl File {
1473    pub fn from_proto(
1474        proto: rpc::proto::File,
1475        worktree: ModelHandle<Worktree>,
1476        cx: &AppContext,
1477    ) -> Result<Self> {
1478        let worktree_id = worktree
1479            .read(cx)
1480            .as_remote()
1481            .ok_or_else(|| anyhow!("not remote"))?
1482            .id();
1483
1484        if worktree_id.to_proto() != proto.worktree_id {
1485            return Err(anyhow!("worktree id does not match file"));
1486        }
1487
1488        Ok(Self {
1489            worktree,
1490            path: Path::new(&proto.path).into(),
1491            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1492            entry_id: proto.entry_id.map(|entry_id| entry_id as usize),
1493            is_local: false,
1494        })
1495    }
1496
1497    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1498        file.and_then(|f| f.as_any().downcast_ref())
1499    }
1500
1501    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1502        self.worktree.read(cx).id()
1503    }
1504}
1505
1506#[derive(Clone, Debug, PartialEq, Eq)]
1507pub struct Entry {
1508    pub id: usize,
1509    pub kind: EntryKind,
1510    pub path: Arc<Path>,
1511    pub inode: u64,
1512    pub mtime: SystemTime,
1513    pub is_symlink: bool,
1514    pub is_ignored: bool,
1515}
1516
1517#[derive(Clone, Debug, PartialEq, Eq)]
1518pub enum EntryKind {
1519    PendingDir,
1520    Dir,
1521    File(CharBag),
1522}
1523
1524impl Entry {
1525    fn new(
1526        path: Arc<Path>,
1527        metadata: &fs::Metadata,
1528        next_entry_id: &AtomicUsize,
1529        root_char_bag: CharBag,
1530    ) -> Self {
1531        Self {
1532            id: next_entry_id.fetch_add(1, SeqCst),
1533            kind: if metadata.is_dir {
1534                EntryKind::PendingDir
1535            } else {
1536                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1537            },
1538            path,
1539            inode: metadata.inode,
1540            mtime: metadata.mtime,
1541            is_symlink: metadata.is_symlink,
1542            is_ignored: false,
1543        }
1544    }
1545
1546    pub fn is_dir(&self) -> bool {
1547        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1548    }
1549
1550    pub fn is_file(&self) -> bool {
1551        matches!(self.kind, EntryKind::File(_))
1552    }
1553}
1554
1555impl sum_tree::Item for Entry {
1556    type Summary = EntrySummary;
1557
1558    fn summary(&self) -> Self::Summary {
1559        let visible_count = if self.is_ignored { 0 } else { 1 };
1560        let file_count;
1561        let visible_file_count;
1562        if self.is_file() {
1563            file_count = 1;
1564            visible_file_count = visible_count;
1565        } else {
1566            file_count = 0;
1567            visible_file_count = 0;
1568        }
1569
1570        EntrySummary {
1571            max_path: self.path.clone(),
1572            count: 1,
1573            visible_count,
1574            file_count,
1575            visible_file_count,
1576        }
1577    }
1578}
1579
1580impl sum_tree::KeyedItem for Entry {
1581    type Key = PathKey;
1582
1583    fn key(&self) -> Self::Key {
1584        PathKey(self.path.clone())
1585    }
1586}
1587
1588#[derive(Clone, Debug)]
1589pub struct EntrySummary {
1590    max_path: Arc<Path>,
1591    count: usize,
1592    visible_count: usize,
1593    file_count: usize,
1594    visible_file_count: usize,
1595}
1596
1597impl Default for EntrySummary {
1598    fn default() -> Self {
1599        Self {
1600            max_path: Arc::from(Path::new("")),
1601            count: 0,
1602            visible_count: 0,
1603            file_count: 0,
1604            visible_file_count: 0,
1605        }
1606    }
1607}
1608
1609impl sum_tree::Summary for EntrySummary {
1610    type Context = ();
1611
1612    fn add_summary(&mut self, rhs: &Self, _: &()) {
1613        self.max_path = rhs.max_path.clone();
1614        self.visible_count += rhs.visible_count;
1615        self.file_count += rhs.file_count;
1616        self.visible_file_count += rhs.visible_file_count;
1617    }
1618}
1619
1620#[derive(Clone, Debug)]
1621struct PathEntry {
1622    id: usize,
1623    path: Arc<Path>,
1624    is_ignored: bool,
1625    scan_id: usize,
1626}
1627
1628impl sum_tree::Item for PathEntry {
1629    type Summary = PathEntrySummary;
1630
1631    fn summary(&self) -> Self::Summary {
1632        PathEntrySummary { max_id: self.id }
1633    }
1634}
1635
1636impl sum_tree::KeyedItem for PathEntry {
1637    type Key = usize;
1638
1639    fn key(&self) -> Self::Key {
1640        self.id
1641    }
1642}
1643
1644#[derive(Clone, Debug, Default)]
1645struct PathEntrySummary {
1646    max_id: usize,
1647}
1648
1649impl sum_tree::Summary for PathEntrySummary {
1650    type Context = ();
1651
1652    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1653        self.max_id = summary.max_id;
1654    }
1655}
1656
1657impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for usize {
1658    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1659        *self = summary.max_id;
1660    }
1661}
1662
1663#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1664pub struct PathKey(Arc<Path>);
1665
1666impl Default for PathKey {
1667    fn default() -> Self {
1668        Self(Path::new("").into())
1669    }
1670}
1671
1672impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1673    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1674        self.0 = summary.max_path.clone();
1675    }
1676}
1677
1678struct BackgroundScanner {
1679    fs: Arc<dyn Fs>,
1680    snapshot: Arc<Mutex<LocalSnapshot>>,
1681    notify: UnboundedSender<ScanState>,
1682    executor: Arc<executor::Background>,
1683}
1684
1685impl BackgroundScanner {
1686    fn new(
1687        snapshot: Arc<Mutex<LocalSnapshot>>,
1688        notify: UnboundedSender<ScanState>,
1689        fs: Arc<dyn Fs>,
1690        executor: Arc<executor::Background>,
1691    ) -> Self {
1692        Self {
1693            fs,
1694            snapshot,
1695            notify,
1696            executor,
1697        }
1698    }
1699
1700    fn abs_path(&self) -> Arc<Path> {
1701        self.snapshot.lock().abs_path.clone()
1702    }
1703
1704    fn snapshot(&self) -> LocalSnapshot {
1705        self.snapshot.lock().clone()
1706    }
1707
1708    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1709        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1710            return;
1711        }
1712
1713        if let Err(err) = self.scan_dirs().await {
1714            if self
1715                .notify
1716                .unbounded_send(ScanState::Err(Arc::new(err)))
1717                .is_err()
1718            {
1719                return;
1720            }
1721        }
1722
1723        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1724            return;
1725        }
1726
1727        futures::pin_mut!(events_rx);
1728        while let Some(events) = events_rx.next().await {
1729            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
1730                break;
1731            }
1732
1733            if !self.process_events(events).await {
1734                break;
1735            }
1736
1737            if self.notify.unbounded_send(ScanState::Idle).is_err() {
1738                break;
1739            }
1740        }
1741    }
1742
1743    async fn scan_dirs(&mut self) -> Result<()> {
1744        let root_char_bag;
1745        let next_entry_id;
1746        let is_dir;
1747        {
1748            let snapshot = self.snapshot.lock();
1749            root_char_bag = snapshot.root_char_bag;
1750            next_entry_id = snapshot.next_entry_id.clone();
1751            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
1752        };
1753
1754        if is_dir {
1755            let path: Arc<Path> = Arc::from(Path::new(""));
1756            let abs_path = self.abs_path();
1757            let (tx, rx) = channel::unbounded();
1758            tx.send(ScanJob {
1759                abs_path: abs_path.to_path_buf(),
1760                path,
1761                ignore_stack: IgnoreStack::none(),
1762                scan_queue: tx.clone(),
1763            })
1764            .await
1765            .unwrap();
1766            drop(tx);
1767
1768            self.executor
1769                .scoped(|scope| {
1770                    for _ in 0..self.executor.num_cpus() {
1771                        scope.spawn(async {
1772                            while let Ok(job) = rx.recv().await {
1773                                if let Err(err) = self
1774                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1775                                    .await
1776                                {
1777                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
1778                                }
1779                            }
1780                        });
1781                    }
1782                })
1783                .await;
1784        }
1785
1786        Ok(())
1787    }
1788
1789    async fn scan_dir(
1790        &self,
1791        root_char_bag: CharBag,
1792        next_entry_id: Arc<AtomicUsize>,
1793        job: &ScanJob,
1794    ) -> Result<()> {
1795        let mut new_entries: Vec<Entry> = Vec::new();
1796        let mut new_jobs: Vec<ScanJob> = Vec::new();
1797        let mut ignore_stack = job.ignore_stack.clone();
1798        let mut new_ignore = None;
1799
1800        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
1801        while let Some(child_abs_path) = child_paths.next().await {
1802            let child_abs_path = match child_abs_path {
1803                Ok(child_abs_path) => child_abs_path,
1804                Err(error) => {
1805                    log::error!("error processing entry {:?}", error);
1806                    continue;
1807                }
1808            };
1809            let child_name = child_abs_path.file_name().unwrap();
1810            let child_path: Arc<Path> = job.path.join(child_name).into();
1811            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
1812                Some(metadata) => metadata,
1813                None => continue,
1814            };
1815
1816            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
1817            if child_name == *GITIGNORE {
1818                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
1819                    Ok(ignore) => {
1820                        let ignore = Arc::new(ignore);
1821                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
1822                        new_ignore = Some(ignore);
1823                    }
1824                    Err(error) => {
1825                        log::error!(
1826                            "error loading .gitignore file {:?} - {:?}",
1827                            child_name,
1828                            error
1829                        );
1830                    }
1831                }
1832
1833                // Update ignore status of any child entries we've already processed to reflect the
1834                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
1835                // there should rarely be too numerous. Update the ignore stack associated with any
1836                // new jobs as well.
1837                let mut new_jobs = new_jobs.iter_mut();
1838                for entry in &mut new_entries {
1839                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
1840                    if entry.is_dir() {
1841                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
1842                            IgnoreStack::all()
1843                        } else {
1844                            ignore_stack.clone()
1845                        };
1846                    }
1847                }
1848            }
1849
1850            let mut child_entry = Entry::new(
1851                child_path.clone(),
1852                &child_metadata,
1853                &next_entry_id,
1854                root_char_bag,
1855            );
1856
1857            if child_metadata.is_dir {
1858                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
1859                child_entry.is_ignored = is_ignored;
1860                new_entries.push(child_entry);
1861                new_jobs.push(ScanJob {
1862                    abs_path: child_abs_path,
1863                    path: child_path,
1864                    ignore_stack: if is_ignored {
1865                        IgnoreStack::all()
1866                    } else {
1867                        ignore_stack.clone()
1868                    },
1869                    scan_queue: job.scan_queue.clone(),
1870                });
1871            } else {
1872                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
1873                new_entries.push(child_entry);
1874            };
1875        }
1876
1877        self.snapshot
1878            .lock()
1879            .populate_dir(job.path.clone(), new_entries, new_ignore);
1880        for new_job in new_jobs {
1881            job.scan_queue.send(new_job).await.unwrap();
1882        }
1883
1884        Ok(())
1885    }
1886
1887    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
1888        let mut snapshot = self.snapshot();
1889        snapshot.scan_id += 1;
1890
1891        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&snapshot.abs_path).await {
1892            abs_path
1893        } else {
1894            return false;
1895        };
1896        let root_char_bag = snapshot.root_char_bag;
1897        let next_entry_id = snapshot.next_entry_id.clone();
1898
1899        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
1900        events.dedup_by(|a, b| a.path.starts_with(&b.path));
1901
1902        for event in &events {
1903            match event.path.strip_prefix(&root_abs_path) {
1904                Ok(path) => snapshot.remove_path(&path),
1905                Err(_) => {
1906                    log::error!(
1907                        "unexpected event {:?} for root path {:?}",
1908                        event.path,
1909                        root_abs_path
1910                    );
1911                    continue;
1912                }
1913            }
1914        }
1915
1916        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
1917        for event in events {
1918            let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
1919                Ok(path) => Arc::from(path.to_path_buf()),
1920                Err(_) => {
1921                    log::error!(
1922                        "unexpected event {:?} for root path {:?}",
1923                        event.path,
1924                        root_abs_path
1925                    );
1926                    continue;
1927                }
1928            };
1929
1930            match self.fs.metadata(&event.path).await {
1931                Ok(Some(metadata)) => {
1932                    let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
1933                    let mut fs_entry = Entry::new(
1934                        path.clone(),
1935                        &metadata,
1936                        snapshot.next_entry_id.as_ref(),
1937                        snapshot.root_char_bag,
1938                    );
1939                    fs_entry.is_ignored = ignore_stack.is_all();
1940                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
1941                    if metadata.is_dir {
1942                        scan_queue_tx
1943                            .send(ScanJob {
1944                                abs_path: event.path,
1945                                path,
1946                                ignore_stack,
1947                                scan_queue: scan_queue_tx.clone(),
1948                            })
1949                            .await
1950                            .unwrap();
1951                    }
1952                }
1953                Ok(None) => {}
1954                Err(err) => {
1955                    // TODO - create a special 'error' entry in the entries tree to mark this
1956                    log::error!("error reading file on event {:?}", err);
1957                }
1958            }
1959        }
1960
1961        *self.snapshot.lock() = snapshot;
1962
1963        // Scan any directories that were created as part of this event batch.
1964        drop(scan_queue_tx);
1965        self.executor
1966            .scoped(|scope| {
1967                for _ in 0..self.executor.num_cpus() {
1968                    scope.spawn(async {
1969                        while let Ok(job) = scan_queue_rx.recv().await {
1970                            if let Err(err) = self
1971                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
1972                                .await
1973                            {
1974                                log::error!("error scanning {:?}: {}", job.abs_path, err);
1975                            }
1976                        }
1977                    });
1978                }
1979            })
1980            .await;
1981
1982        // Attempt to detect renames only over a single batch of file-system events.
1983        self.snapshot.lock().removed_entry_ids.clear();
1984
1985        self.update_ignore_statuses().await;
1986        true
1987    }
1988
1989    async fn update_ignore_statuses(&self) {
1990        let mut snapshot = self.snapshot();
1991
1992        let mut ignores_to_update = Vec::new();
1993        let mut ignores_to_delete = Vec::new();
1994        for (parent_path, (_, scan_id)) in &snapshot.ignores {
1995            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
1996                ignores_to_update.push(parent_path.clone());
1997            }
1998
1999            let ignore_path = parent_path.join(&*GITIGNORE);
2000            if snapshot.entry_for_path(ignore_path).is_none() {
2001                ignores_to_delete.push(parent_path.clone());
2002            }
2003        }
2004
2005        for parent_path in ignores_to_delete {
2006            snapshot.ignores.remove(&parent_path);
2007            self.snapshot.lock().ignores.remove(&parent_path);
2008        }
2009
2010        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2011        ignores_to_update.sort_unstable();
2012        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2013        while let Some(parent_path) = ignores_to_update.next() {
2014            while ignores_to_update
2015                .peek()
2016                .map_or(false, |p| p.starts_with(&parent_path))
2017            {
2018                ignores_to_update.next().unwrap();
2019            }
2020
2021            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2022            ignore_queue_tx
2023                .send(UpdateIgnoreStatusJob {
2024                    path: parent_path,
2025                    ignore_stack,
2026                    ignore_queue: ignore_queue_tx.clone(),
2027                })
2028                .await
2029                .unwrap();
2030        }
2031        drop(ignore_queue_tx);
2032
2033        self.executor
2034            .scoped(|scope| {
2035                for _ in 0..self.executor.num_cpus() {
2036                    scope.spawn(async {
2037                        while let Ok(job) = ignore_queue_rx.recv().await {
2038                            self.update_ignore_status(job, &snapshot).await;
2039                        }
2040                    });
2041                }
2042            })
2043            .await;
2044    }
2045
2046    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2047        let mut ignore_stack = job.ignore_stack;
2048        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2049            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2050        }
2051
2052        let mut entries_by_id_edits = Vec::new();
2053        let mut entries_by_path_edits = Vec::new();
2054        for mut entry in snapshot.child_entries(&job.path).cloned() {
2055            let was_ignored = entry.is_ignored;
2056            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2057            if entry.is_dir() {
2058                let child_ignore_stack = if entry.is_ignored {
2059                    IgnoreStack::all()
2060                } else {
2061                    ignore_stack.clone()
2062                };
2063                job.ignore_queue
2064                    .send(UpdateIgnoreStatusJob {
2065                        path: entry.path.clone(),
2066                        ignore_stack: child_ignore_stack,
2067                        ignore_queue: job.ignore_queue.clone(),
2068                    })
2069                    .await
2070                    .unwrap();
2071            }
2072
2073            if entry.is_ignored != was_ignored {
2074                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2075                path_entry.scan_id = snapshot.scan_id;
2076                path_entry.is_ignored = entry.is_ignored;
2077                entries_by_id_edits.push(Edit::Insert(path_entry));
2078                entries_by_path_edits.push(Edit::Insert(entry));
2079            }
2080        }
2081
2082        let mut snapshot = self.snapshot.lock();
2083        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2084        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2085    }
2086}
2087
2088async fn refresh_entry(
2089    fs: &dyn Fs,
2090    snapshot: &Mutex<LocalSnapshot>,
2091    path: Arc<Path>,
2092    abs_path: &Path,
2093) -> Result<Entry> {
2094    let root_char_bag;
2095    let next_entry_id;
2096    {
2097        let snapshot = snapshot.lock();
2098        root_char_bag = snapshot.root_char_bag;
2099        next_entry_id = snapshot.next_entry_id.clone();
2100    }
2101    let entry = Entry::new(
2102        path,
2103        &fs.metadata(abs_path)
2104            .await?
2105            .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2106        &next_entry_id,
2107        root_char_bag,
2108    );
2109    Ok(snapshot.lock().insert_entry(entry, fs))
2110}
2111
2112fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2113    let mut result = root_char_bag;
2114    result.extend(
2115        path.to_string_lossy()
2116            .chars()
2117            .map(|c| c.to_ascii_lowercase()),
2118    );
2119    result
2120}
2121
2122struct ScanJob {
2123    abs_path: PathBuf,
2124    path: Arc<Path>,
2125    ignore_stack: Arc<IgnoreStack>,
2126    scan_queue: Sender<ScanJob>,
2127}
2128
2129struct UpdateIgnoreStatusJob {
2130    path: Arc<Path>,
2131    ignore_stack: Arc<IgnoreStack>,
2132    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2133}
2134
2135pub trait WorktreeHandle {
2136    #[cfg(any(test, feature = "test-support"))]
2137    fn flush_fs_events<'a>(
2138        &self,
2139        cx: &'a gpui::TestAppContext,
2140    ) -> futures::future::LocalBoxFuture<'a, ()>;
2141}
2142
2143impl WorktreeHandle for ModelHandle<Worktree> {
2144    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2145    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2146    // extra directory scans, and emit extra scan-state notifications.
2147    //
2148    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2149    // to ensure that all redundant FS events have already been processed.
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        use smol::future::FutureExt;
2156
2157        let filename = "fs-event-sentinel";
2158        let tree = self.clone();
2159        let (fs, root_path) = self.read_with(cx, |tree, _| {
2160            let tree = tree.as_local().unwrap();
2161            (tree.fs.clone(), tree.abs_path().clone())
2162        });
2163
2164        async move {
2165            fs.create_file(&root_path.join(filename), Default::default())
2166                .await
2167                .unwrap();
2168            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2169                .await;
2170
2171            fs.remove_file(&root_path.join(filename), Default::default())
2172                .await
2173                .unwrap();
2174            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2175                .await;
2176
2177            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2178                .await;
2179        }
2180        .boxed_local()
2181    }
2182}
2183
2184#[derive(Clone, Debug)]
2185struct TraversalProgress<'a> {
2186    max_path: &'a Path,
2187    count: usize,
2188    visible_count: usize,
2189    file_count: usize,
2190    visible_file_count: usize,
2191}
2192
2193impl<'a> TraversalProgress<'a> {
2194    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2195        match (include_ignored, include_dirs) {
2196            (true, true) => self.count,
2197            (true, false) => self.file_count,
2198            (false, true) => self.visible_count,
2199            (false, false) => self.visible_file_count,
2200        }
2201    }
2202}
2203
2204impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2205    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2206        self.max_path = summary.max_path.as_ref();
2207        self.count += summary.count;
2208        self.visible_count += summary.visible_count;
2209        self.file_count += summary.file_count;
2210        self.visible_file_count += summary.visible_file_count;
2211    }
2212}
2213
2214impl<'a> Default for TraversalProgress<'a> {
2215    fn default() -> Self {
2216        Self {
2217            max_path: Path::new(""),
2218            count: 0,
2219            visible_count: 0,
2220            file_count: 0,
2221            visible_file_count: 0,
2222        }
2223    }
2224}
2225
2226pub struct Traversal<'a> {
2227    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2228    include_ignored: bool,
2229    include_dirs: bool,
2230}
2231
2232impl<'a> Traversal<'a> {
2233    pub fn advance(&mut self) -> bool {
2234        self.advance_to_offset(self.offset() + 1)
2235    }
2236
2237    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2238        self.cursor.seek_forward(
2239            &TraversalTarget::Count {
2240                count: offset,
2241                include_dirs: self.include_dirs,
2242                include_ignored: self.include_ignored,
2243            },
2244            Bias::Right,
2245            &(),
2246        )
2247    }
2248
2249    pub fn advance_to_sibling(&mut self) -> bool {
2250        while let Some(entry) = self.cursor.item() {
2251            self.cursor.seek_forward(
2252                &TraversalTarget::PathSuccessor(&entry.path),
2253                Bias::Left,
2254                &(),
2255            );
2256            if let Some(entry) = self.cursor.item() {
2257                if (self.include_dirs || !entry.is_dir())
2258                    && (self.include_ignored || !entry.is_ignored)
2259                {
2260                    return true;
2261                }
2262            }
2263        }
2264        false
2265    }
2266
2267    pub fn entry(&self) -> Option<&'a Entry> {
2268        self.cursor.item()
2269    }
2270
2271    pub fn offset(&self) -> usize {
2272        self.cursor
2273            .start()
2274            .count(self.include_dirs, self.include_ignored)
2275    }
2276}
2277
2278impl<'a> Iterator for Traversal<'a> {
2279    type Item = &'a Entry;
2280
2281    fn next(&mut self) -> Option<Self::Item> {
2282        if let Some(item) = self.entry() {
2283            self.advance();
2284            Some(item)
2285        } else {
2286            None
2287        }
2288    }
2289}
2290
2291#[derive(Debug)]
2292enum TraversalTarget<'a> {
2293    Path(&'a Path),
2294    PathSuccessor(&'a Path),
2295    Count {
2296        count: usize,
2297        include_ignored: bool,
2298        include_dirs: bool,
2299    },
2300}
2301
2302impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2303    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2304        match self {
2305            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2306            TraversalTarget::PathSuccessor(path) => {
2307                if !cursor_location.max_path.starts_with(path) {
2308                    Ordering::Equal
2309                } else {
2310                    Ordering::Greater
2311                }
2312            }
2313            TraversalTarget::Count {
2314                count,
2315                include_dirs,
2316                include_ignored,
2317            } => Ord::cmp(
2318                count,
2319                &cursor_location.count(*include_dirs, *include_ignored),
2320            ),
2321        }
2322    }
2323}
2324
2325struct ChildEntriesIter<'a> {
2326    parent_path: &'a Path,
2327    traversal: Traversal<'a>,
2328}
2329
2330impl<'a> Iterator for ChildEntriesIter<'a> {
2331    type Item = &'a Entry;
2332
2333    fn next(&mut self) -> Option<Self::Item> {
2334        if let Some(item) = self.traversal.entry() {
2335            if item.path.starts_with(&self.parent_path) {
2336                self.traversal.advance_to_sibling();
2337                return Some(item);
2338            }
2339        }
2340        None
2341    }
2342}
2343
2344impl<'a> From<&'a Entry> for proto::Entry {
2345    fn from(entry: &'a Entry) -> Self {
2346        Self {
2347            id: entry.id as u64,
2348            is_dir: entry.is_dir(),
2349            path: entry.path.to_string_lossy().to_string(),
2350            inode: entry.inode,
2351            mtime: Some(entry.mtime.into()),
2352            is_symlink: entry.is_symlink,
2353            is_ignored: entry.is_ignored,
2354        }
2355    }
2356}
2357
2358impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2359    type Error = anyhow::Error;
2360
2361    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2362        if let Some(mtime) = entry.mtime {
2363            let kind = if entry.is_dir {
2364                EntryKind::Dir
2365            } else {
2366                let mut char_bag = root_char_bag.clone();
2367                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2368                EntryKind::File(char_bag)
2369            };
2370            let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2371            Ok(Entry {
2372                id: entry.id as usize,
2373                kind,
2374                path: path.clone(),
2375                inode: entry.inode,
2376                mtime: mtime.into(),
2377                is_symlink: entry.is_symlink,
2378                is_ignored: entry.is_ignored,
2379            })
2380        } else {
2381            Err(anyhow!(
2382                "missing mtime in remote worktree entry {:?}",
2383                entry.path
2384            ))
2385        }
2386    }
2387}
2388
2389#[cfg(test)]
2390mod tests {
2391    use super::*;
2392    use crate::fs::FakeFs;
2393    use anyhow::Result;
2394    use client::test::FakeHttpClient;
2395    use fs::RealFs;
2396    use rand::prelude::*;
2397    use serde_json::json;
2398    use std::{
2399        env,
2400        fmt::Write,
2401        time::{SystemTime, UNIX_EPOCH},
2402    };
2403    use util::test::temp_tree;
2404
2405    #[gpui::test]
2406    async fn test_traversal(cx: &mut gpui::TestAppContext) {
2407        let fs = FakeFs::new(cx.background());
2408        fs.insert_tree(
2409            "/root",
2410            json!({
2411               ".gitignore": "a/b\n",
2412               "a": {
2413                   "b": "",
2414                   "c": "",
2415               }
2416            }),
2417        )
2418        .await;
2419
2420        let http_client = FakeHttpClient::with_404_response();
2421        let client = Client::new(http_client);
2422
2423        let tree = Worktree::local(
2424            client,
2425            Arc::from(Path::new("/root")),
2426            true,
2427            fs,
2428            &mut cx.to_async(),
2429        )
2430        .await
2431        .unwrap();
2432        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2433            .await;
2434
2435        tree.read_with(cx, |tree, _| {
2436            assert_eq!(
2437                tree.entries(false)
2438                    .map(|entry| entry.path.as_ref())
2439                    .collect::<Vec<_>>(),
2440                vec![
2441                    Path::new(""),
2442                    Path::new(".gitignore"),
2443                    Path::new("a"),
2444                    Path::new("a/c"),
2445                ]
2446            );
2447        })
2448    }
2449
2450    #[gpui::test]
2451    async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2452        let dir = temp_tree(json!({
2453            ".git": {},
2454            ".gitignore": "ignored-dir\n",
2455            "tracked-dir": {
2456                "tracked-file1": "tracked contents",
2457            },
2458            "ignored-dir": {
2459                "ignored-file1": "ignored contents",
2460            }
2461        }));
2462
2463        let http_client = FakeHttpClient::with_404_response();
2464        let client = Client::new(http_client.clone());
2465
2466        let tree = Worktree::local(
2467            client,
2468            dir.path(),
2469            true,
2470            Arc::new(RealFs),
2471            &mut cx.to_async(),
2472        )
2473        .await
2474        .unwrap();
2475        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2476            .await;
2477        tree.flush_fs_events(&cx).await;
2478        cx.read(|cx| {
2479            let tree = tree.read(cx);
2480            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2481            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2482            assert_eq!(tracked.is_ignored, false);
2483            assert_eq!(ignored.is_ignored, true);
2484        });
2485
2486        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2487        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2488        tree.flush_fs_events(&cx).await;
2489        cx.read(|cx| {
2490            let tree = tree.read(cx);
2491            let dot_git = tree.entry_for_path(".git").unwrap();
2492            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2493            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2494            assert_eq!(tracked.is_ignored, false);
2495            assert_eq!(ignored.is_ignored, true);
2496            assert_eq!(dot_git.is_ignored, true);
2497        });
2498    }
2499
2500    #[gpui::test(iterations = 100)]
2501    fn test_random(mut rng: StdRng) {
2502        let operations = env::var("OPERATIONS")
2503            .map(|o| o.parse().unwrap())
2504            .unwrap_or(40);
2505        let initial_entries = env::var("INITIAL_ENTRIES")
2506            .map(|o| o.parse().unwrap())
2507            .unwrap_or(20);
2508
2509        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2510        for _ in 0..initial_entries {
2511            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2512        }
2513        log::info!("Generated initial tree");
2514
2515        let (notify_tx, _notify_rx) = mpsc::unbounded();
2516        let fs = Arc::new(RealFs);
2517        let next_entry_id = Arc::new(AtomicUsize::new(0));
2518        let mut initial_snapshot = LocalSnapshot {
2519            abs_path: root_dir.path().into(),
2520            scan_id: 0,
2521            removed_entry_ids: Default::default(),
2522            ignores: Default::default(),
2523            next_entry_id: next_entry_id.clone(),
2524            snapshot: Snapshot {
2525                id: WorktreeId::from_usize(0),
2526                entries_by_path: Default::default(),
2527                entries_by_id: Default::default(),
2528                root_name: Default::default(),
2529                root_char_bag: Default::default(),
2530            },
2531        };
2532        initial_snapshot.insert_entry(
2533            Entry::new(
2534                Path::new("").into(),
2535                &smol::block_on(fs.metadata(root_dir.path()))
2536                    .unwrap()
2537                    .unwrap(),
2538                &next_entry_id,
2539                Default::default(),
2540            ),
2541            fs.as_ref(),
2542        );
2543        let mut scanner = BackgroundScanner::new(
2544            Arc::new(Mutex::new(initial_snapshot.clone())),
2545            notify_tx,
2546            fs.clone(),
2547            Arc::new(gpui::executor::Background::new()),
2548        );
2549        smol::block_on(scanner.scan_dirs()).unwrap();
2550        scanner.snapshot().check_invariants();
2551
2552        let mut events = Vec::new();
2553        let mut snapshots = Vec::new();
2554        let mut mutations_len = operations;
2555        while mutations_len > 1 {
2556            if !events.is_empty() && rng.gen_bool(0.4) {
2557                let len = rng.gen_range(0..=events.len());
2558                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2559                log::info!("Delivering events: {:#?}", to_deliver);
2560                smol::block_on(scanner.process_events(to_deliver));
2561                scanner.snapshot().check_invariants();
2562            } else {
2563                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2564                mutations_len -= 1;
2565            }
2566
2567            if rng.gen_bool(0.2) {
2568                snapshots.push(scanner.snapshot());
2569            }
2570        }
2571        log::info!("Quiescing: {:#?}", events);
2572        smol::block_on(scanner.process_events(events));
2573        scanner.snapshot().check_invariants();
2574
2575        let (notify_tx, _notify_rx) = mpsc::unbounded();
2576        let mut new_scanner = BackgroundScanner::new(
2577            Arc::new(Mutex::new(initial_snapshot)),
2578            notify_tx,
2579            scanner.fs.clone(),
2580            scanner.executor.clone(),
2581        );
2582        smol::block_on(new_scanner.scan_dirs()).unwrap();
2583        assert_eq!(
2584            scanner.snapshot().to_vec(true),
2585            new_scanner.snapshot().to_vec(true)
2586        );
2587
2588        for mut prev_snapshot in snapshots {
2589            let include_ignored = rng.gen::<bool>();
2590            if !include_ignored {
2591                let mut entries_by_path_edits = Vec::new();
2592                let mut entries_by_id_edits = Vec::new();
2593                for entry in prev_snapshot
2594                    .entries_by_id
2595                    .cursor::<()>()
2596                    .filter(|e| e.is_ignored)
2597                {
2598                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2599                    entries_by_id_edits.push(Edit::Remove(entry.id));
2600                }
2601
2602                prev_snapshot
2603                    .entries_by_path
2604                    .edit(entries_by_path_edits, &());
2605                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2606            }
2607
2608            let update = scanner
2609                .snapshot()
2610                .build_update(&prev_snapshot, 0, 0, include_ignored);
2611            prev_snapshot.apply_remote_update(update).unwrap();
2612            assert_eq!(
2613                prev_snapshot.to_vec(true),
2614                scanner.snapshot().to_vec(include_ignored)
2615            );
2616        }
2617    }
2618
2619    fn randomly_mutate_tree(
2620        root_path: &Path,
2621        insertion_probability: f64,
2622        rng: &mut impl Rng,
2623    ) -> Result<Vec<fsevent::Event>> {
2624        let root_path = root_path.canonicalize().unwrap();
2625        let (dirs, files) = read_dir_recursive(root_path.clone());
2626
2627        let mut events = Vec::new();
2628        let mut record_event = |path: PathBuf| {
2629            events.push(fsevent::Event {
2630                event_id: SystemTime::now()
2631                    .duration_since(UNIX_EPOCH)
2632                    .unwrap()
2633                    .as_secs(),
2634                flags: fsevent::StreamFlags::empty(),
2635                path,
2636            });
2637        };
2638
2639        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2640            let path = dirs.choose(rng).unwrap();
2641            let new_path = path.join(gen_name(rng));
2642
2643            if rng.gen() {
2644                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2645                std::fs::create_dir(&new_path)?;
2646            } else {
2647                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2648                std::fs::write(&new_path, "")?;
2649            }
2650            record_event(new_path);
2651        } else if rng.gen_bool(0.05) {
2652            let ignore_dir_path = dirs.choose(rng).unwrap();
2653            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2654
2655            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2656            let files_to_ignore = {
2657                let len = rng.gen_range(0..=subfiles.len());
2658                subfiles.choose_multiple(rng, len)
2659            };
2660            let dirs_to_ignore = {
2661                let len = rng.gen_range(0..subdirs.len());
2662                subdirs.choose_multiple(rng, len)
2663            };
2664
2665            let mut ignore_contents = String::new();
2666            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2667                write!(
2668                    ignore_contents,
2669                    "{}\n",
2670                    path_to_ignore
2671                        .strip_prefix(&ignore_dir_path)?
2672                        .to_str()
2673                        .unwrap()
2674                )
2675                .unwrap();
2676            }
2677            log::info!(
2678                "Creating {:?} with contents:\n{}",
2679                ignore_path.strip_prefix(&root_path)?,
2680                ignore_contents
2681            );
2682            std::fs::write(&ignore_path, ignore_contents).unwrap();
2683            record_event(ignore_path);
2684        } else {
2685            let old_path = {
2686                let file_path = files.choose(rng);
2687                let dir_path = dirs[1..].choose(rng);
2688                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2689            };
2690
2691            let is_rename = rng.gen();
2692            if is_rename {
2693                let new_path_parent = dirs
2694                    .iter()
2695                    .filter(|d| !d.starts_with(old_path))
2696                    .choose(rng)
2697                    .unwrap();
2698
2699                let overwrite_existing_dir =
2700                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2701                let new_path = if overwrite_existing_dir {
2702                    std::fs::remove_dir_all(&new_path_parent).ok();
2703                    new_path_parent.to_path_buf()
2704                } else {
2705                    new_path_parent.join(gen_name(rng))
2706                };
2707
2708                log::info!(
2709                    "Renaming {:?} to {}{:?}",
2710                    old_path.strip_prefix(&root_path)?,
2711                    if overwrite_existing_dir {
2712                        "overwrite "
2713                    } else {
2714                        ""
2715                    },
2716                    new_path.strip_prefix(&root_path)?
2717                );
2718                std::fs::rename(&old_path, &new_path)?;
2719                record_event(old_path.clone());
2720                record_event(new_path);
2721            } else if old_path.is_dir() {
2722                let (dirs, files) = read_dir_recursive(old_path.clone());
2723
2724                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2725                std::fs::remove_dir_all(&old_path).unwrap();
2726                for file in files {
2727                    record_event(file);
2728                }
2729                for dir in dirs {
2730                    record_event(dir);
2731                }
2732            } else {
2733                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2734                std::fs::remove_file(old_path).unwrap();
2735                record_event(old_path.clone());
2736            }
2737        }
2738
2739        Ok(events)
2740    }
2741
2742    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2743        let child_entries = std::fs::read_dir(&path).unwrap();
2744        let mut dirs = vec![path];
2745        let mut files = Vec::new();
2746        for child_entry in child_entries {
2747            let child_path = child_entry.unwrap().path();
2748            if child_path.is_dir() {
2749                let (child_dirs, child_files) = read_dir_recursive(child_path);
2750                dirs.extend(child_dirs);
2751                files.extend(child_files);
2752            } else {
2753                files.push(child_path);
2754            }
2755        }
2756        (dirs, files)
2757    }
2758
2759    fn gen_name(rng: &mut impl Rng) -> String {
2760        (0..6)
2761            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2762            .map(char::from)
2763            .collect()
2764    }
2765
2766    impl LocalSnapshot {
2767        fn check_invariants(&self) {
2768            let mut files = self.files(true, 0);
2769            let mut visible_files = self.files(false, 0);
2770            for entry in self.entries_by_path.cursor::<()>() {
2771                if entry.is_file() {
2772                    assert_eq!(files.next().unwrap().inode, entry.inode);
2773                    if !entry.is_ignored {
2774                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2775                    }
2776                }
2777            }
2778            assert!(files.next().is_none());
2779            assert!(visible_files.next().is_none());
2780
2781            let mut bfs_paths = Vec::new();
2782            let mut stack = vec![Path::new("")];
2783            while let Some(path) = stack.pop() {
2784                bfs_paths.push(path);
2785                let ix = stack.len();
2786                for child_entry in self.child_entries(path) {
2787                    stack.insert(ix, &child_entry.path);
2788                }
2789            }
2790
2791            let dfs_paths = self
2792                .entries_by_path
2793                .cursor::<()>()
2794                .map(|e| e.path.as_ref())
2795                .collect::<Vec<_>>();
2796            assert_eq!(bfs_paths, dfs_paths);
2797
2798            for (ignore_parent_path, _) in &self.ignores {
2799                assert!(self.entry_for_path(ignore_parent_path).is_some());
2800                assert!(self
2801                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2802                    .is_some());
2803            }
2804        }
2805
2806        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2807            let mut paths = Vec::new();
2808            for entry in self.entries_by_path.cursor::<()>() {
2809                if include_ignored || !entry.is_ignored {
2810                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2811                }
2812            }
2813            paths.sort_by(|a, b| a.0.cmp(&b.0));
2814            paths
2815        }
2816    }
2817}