worktree.rs

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