worktree.rs

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