worktree.rs

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