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