worktree.rs

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