worktree.rs

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