worktree.rs

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