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        if worktree.is_visible() {
1844            full_path.push(worktree.root_name());
1845        } else {
1846            if let Some(path) = worktree.as_local().map(|local| local.abs_path.clone()) {
1847                if let Ok(trimmed_path) = path.strip_prefix(cx.global::<HomeDir>().0.as_path()) {
1848                    full_path.push("~");
1849                    full_path.push(trimmed_path);
1850                } else {
1851                    full_path.push(path)
1852                }
1853            } else {
1854                full_path.push(Path::new("/host-filesystem/"))
1855            }
1856        }
1857        if self.path.components().next().is_some() {
1858            full_path.push(&self.path);
1859        }
1860        full_path
1861    }
1862
1863    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1864    /// of its worktree, then this method will return the name of the worktree itself.
1865    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
1866        self.path
1867            .file_name()
1868            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
1869    }
1870
1871    fn is_deleted(&self) -> bool {
1872        self.is_deleted
1873    }
1874
1875    fn save(
1876        &self,
1877        buffer_id: u64,
1878        text: Rope,
1879        version: clock::Global,
1880        line_ending: LineEnding,
1881        cx: &mut MutableAppContext,
1882    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1883        self.worktree.update(cx, |worktree, cx| match worktree {
1884            Worktree::Local(worktree) => {
1885                let rpc = worktree.client.clone();
1886                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1887                let fingerprint = text.fingerprint();
1888                let save = worktree.write_file(self.path.clone(), text, line_ending, cx);
1889                cx.background().spawn(async move {
1890                    let entry = save.await?;
1891                    if let Some(project_id) = project_id {
1892                        rpc.send(proto::BufferSaved {
1893                            project_id,
1894                            buffer_id,
1895                            version: serialize_version(&version),
1896                            mtime: Some(entry.mtime.into()),
1897                            fingerprint: fingerprint.clone(),
1898                        })?;
1899                    }
1900                    Ok((version, fingerprint, entry.mtime))
1901                })
1902            }
1903            Worktree::Remote(worktree) => {
1904                let rpc = worktree.client.clone();
1905                let project_id = worktree.project_id;
1906                cx.foreground().spawn(async move {
1907                    let response = rpc
1908                        .request(proto::SaveBuffer {
1909                            project_id,
1910                            buffer_id,
1911                            version: serialize_version(&version),
1912                        })
1913                        .await?;
1914                    let version = deserialize_version(response.version);
1915                    let mtime = response
1916                        .mtime
1917                        .ok_or_else(|| anyhow!("missing mtime"))?
1918                        .into();
1919                    Ok((version, response.fingerprint, mtime))
1920                })
1921            }
1922        })
1923    }
1924
1925    fn as_any(&self) -> &dyn Any {
1926        self
1927    }
1928
1929    fn to_proto(&self) -> rpc::proto::File {
1930        rpc::proto::File {
1931            worktree_id: self.worktree.id() as u64,
1932            entry_id: self.entry_id.to_proto(),
1933            path: self.path.to_string_lossy().into(),
1934            mtime: Some(self.mtime.into()),
1935            is_deleted: self.is_deleted,
1936        }
1937    }
1938}
1939
1940impl language::LocalFile for File {
1941    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1942        self.worktree
1943            .read(cx)
1944            .as_local()
1945            .unwrap()
1946            .abs_path
1947            .join(&self.path)
1948    }
1949
1950    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1951        let worktree = self.worktree.read(cx).as_local().unwrap();
1952        let abs_path = worktree.absolutize(&self.path);
1953        let fs = worktree.fs.clone();
1954        cx.background()
1955            .spawn(async move { fs.load(&abs_path).await })
1956    }
1957
1958    fn buffer_reloaded(
1959        &self,
1960        buffer_id: u64,
1961        version: &clock::Global,
1962        fingerprint: String,
1963        line_ending: LineEnding,
1964        mtime: SystemTime,
1965        cx: &mut MutableAppContext,
1966    ) {
1967        let worktree = self.worktree.read(cx).as_local().unwrap();
1968        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1969            worktree
1970                .client
1971                .send(proto::BufferReloaded {
1972                    project_id,
1973                    buffer_id,
1974                    version: serialize_version(version),
1975                    mtime: Some(mtime.into()),
1976                    fingerprint,
1977                    line_ending: serialize_line_ending(line_ending) as i32,
1978                })
1979                .log_err();
1980        }
1981    }
1982}
1983
1984impl File {
1985    pub fn from_proto(
1986        proto: rpc::proto::File,
1987        worktree: ModelHandle<Worktree>,
1988        cx: &AppContext,
1989    ) -> Result<Self> {
1990        let worktree_id = worktree
1991            .read(cx)
1992            .as_remote()
1993            .ok_or_else(|| anyhow!("not remote"))?
1994            .id();
1995
1996        if worktree_id.to_proto() != proto.worktree_id {
1997            return Err(anyhow!("worktree id does not match file"));
1998        }
1999
2000        Ok(Self {
2001            worktree,
2002            path: Path::new(&proto.path).into(),
2003            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2004            entry_id: ProjectEntryId::from_proto(proto.entry_id),
2005            is_local: false,
2006            is_deleted: proto.is_deleted,
2007        })
2008    }
2009
2010    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
2011        file.and_then(|f| f.as_any().downcast_ref())
2012    }
2013
2014    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2015        self.worktree.read(cx).id()
2016    }
2017
2018    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2019        if self.is_deleted {
2020            None
2021        } else {
2022            Some(self.entry_id)
2023        }
2024    }
2025}
2026
2027#[derive(Clone, Debug, PartialEq, Eq)]
2028pub struct Entry {
2029    pub id: ProjectEntryId,
2030    pub kind: EntryKind,
2031    pub path: Arc<Path>,
2032    pub inode: u64,
2033    pub mtime: SystemTime,
2034    pub is_symlink: bool,
2035    pub is_ignored: bool,
2036}
2037
2038#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2039pub enum EntryKind {
2040    PendingDir,
2041    Dir,
2042    File(CharBag),
2043}
2044
2045impl Entry {
2046    fn new(
2047        path: Arc<Path>,
2048        metadata: &fs::Metadata,
2049        next_entry_id: &AtomicUsize,
2050        root_char_bag: CharBag,
2051    ) -> Self {
2052        Self {
2053            id: ProjectEntryId::new(next_entry_id),
2054            kind: if metadata.is_dir {
2055                EntryKind::PendingDir
2056            } else {
2057                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2058            },
2059            path,
2060            inode: metadata.inode,
2061            mtime: metadata.mtime,
2062            is_symlink: metadata.is_symlink,
2063            is_ignored: false,
2064        }
2065    }
2066
2067    pub fn is_dir(&self) -> bool {
2068        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2069    }
2070
2071    pub fn is_file(&self) -> bool {
2072        matches!(self.kind, EntryKind::File(_))
2073    }
2074}
2075
2076impl sum_tree::Item for Entry {
2077    type Summary = EntrySummary;
2078
2079    fn summary(&self) -> Self::Summary {
2080        let visible_count = if self.is_ignored { 0 } else { 1 };
2081        let file_count;
2082        let visible_file_count;
2083        if self.is_file() {
2084            file_count = 1;
2085            visible_file_count = visible_count;
2086        } else {
2087            file_count = 0;
2088            visible_file_count = 0;
2089        }
2090
2091        EntrySummary {
2092            max_path: self.path.clone(),
2093            count: 1,
2094            visible_count,
2095            file_count,
2096            visible_file_count,
2097        }
2098    }
2099}
2100
2101impl sum_tree::KeyedItem for Entry {
2102    type Key = PathKey;
2103
2104    fn key(&self) -> Self::Key {
2105        PathKey(self.path.clone())
2106    }
2107}
2108
2109#[derive(Clone, Debug)]
2110pub struct EntrySummary {
2111    max_path: Arc<Path>,
2112    count: usize,
2113    visible_count: usize,
2114    file_count: usize,
2115    visible_file_count: usize,
2116}
2117
2118impl Default for EntrySummary {
2119    fn default() -> Self {
2120        Self {
2121            max_path: Arc::from(Path::new("")),
2122            count: 0,
2123            visible_count: 0,
2124            file_count: 0,
2125            visible_file_count: 0,
2126        }
2127    }
2128}
2129
2130impl sum_tree::Summary for EntrySummary {
2131    type Context = ();
2132
2133    fn add_summary(&mut self, rhs: &Self, _: &()) {
2134        self.max_path = rhs.max_path.clone();
2135        self.count += rhs.count;
2136        self.visible_count += rhs.visible_count;
2137        self.file_count += rhs.file_count;
2138        self.visible_file_count += rhs.visible_file_count;
2139    }
2140}
2141
2142#[derive(Clone, Debug)]
2143struct PathEntry {
2144    id: ProjectEntryId,
2145    path: Arc<Path>,
2146    is_ignored: bool,
2147    scan_id: usize,
2148}
2149
2150impl sum_tree::Item for PathEntry {
2151    type Summary = PathEntrySummary;
2152
2153    fn summary(&self) -> Self::Summary {
2154        PathEntrySummary { max_id: self.id }
2155    }
2156}
2157
2158impl sum_tree::KeyedItem for PathEntry {
2159    type Key = ProjectEntryId;
2160
2161    fn key(&self) -> Self::Key {
2162        self.id
2163    }
2164}
2165
2166#[derive(Clone, Debug, Default)]
2167struct PathEntrySummary {
2168    max_id: ProjectEntryId,
2169}
2170
2171impl sum_tree::Summary for PathEntrySummary {
2172    type Context = ();
2173
2174    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2175        self.max_id = summary.max_id;
2176    }
2177}
2178
2179impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2180    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2181        *self = summary.max_id;
2182    }
2183}
2184
2185#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2186pub struct PathKey(Arc<Path>);
2187
2188impl Default for PathKey {
2189    fn default() -> Self {
2190        Self(Path::new("").into())
2191    }
2192}
2193
2194impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2195    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2196        self.0 = summary.max_path.clone();
2197    }
2198}
2199
2200struct BackgroundScanner {
2201    fs: Arc<dyn Fs>,
2202    snapshot: Arc<Mutex<LocalSnapshot>>,
2203    notify: UnboundedSender<ScanState>,
2204    executor: Arc<executor::Background>,
2205}
2206
2207impl BackgroundScanner {
2208    fn new(
2209        snapshot: Arc<Mutex<LocalSnapshot>>,
2210        notify: UnboundedSender<ScanState>,
2211        fs: Arc<dyn Fs>,
2212        executor: Arc<executor::Background>,
2213    ) -> Self {
2214        Self {
2215            fs,
2216            snapshot,
2217            notify,
2218            executor,
2219        }
2220    }
2221
2222    fn abs_path(&self) -> Arc<Path> {
2223        self.snapshot.lock().abs_path.clone()
2224    }
2225
2226    fn snapshot(&self) -> LocalSnapshot {
2227        self.snapshot.lock().clone()
2228    }
2229
2230    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2231        if self.notify.unbounded_send(ScanState::Initializing).is_err() {
2232            return;
2233        }
2234
2235        if let Err(err) = self.scan_dirs().await {
2236            if self
2237                .notify
2238                .unbounded_send(ScanState::Err(Arc::new(err)))
2239                .is_err()
2240            {
2241                return;
2242            }
2243        }
2244
2245        if self.notify.unbounded_send(ScanState::Idle).is_err() {
2246            return;
2247        }
2248
2249        futures::pin_mut!(events_rx);
2250
2251        while let Some(mut events) = events_rx.next().await {
2252            while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2253                events.extend(additional_events);
2254            }
2255
2256            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2257                break;
2258            }
2259
2260            if !self.process_events(events).await {
2261                break;
2262            }
2263
2264            if self.notify.unbounded_send(ScanState::Idle).is_err() {
2265                break;
2266            }
2267        }
2268    }
2269
2270    async fn scan_dirs(&mut self) -> Result<()> {
2271        let root_char_bag;
2272        let root_abs_path;
2273        let root_inode;
2274        let is_dir;
2275        let next_entry_id;
2276        {
2277            let snapshot = self.snapshot.lock();
2278            root_char_bag = snapshot.root_char_bag;
2279            root_abs_path = snapshot.abs_path.clone();
2280            root_inode = snapshot.root_entry().map(|e| e.inode);
2281            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir());
2282            next_entry_id = snapshot.next_entry_id.clone();
2283        };
2284
2285        // Populate ignores above the root.
2286        for ancestor in root_abs_path.ancestors().skip(1) {
2287            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2288            {
2289                self.snapshot
2290                    .lock()
2291                    .ignores_by_parent_abs_path
2292                    .insert(ancestor.into(), (ignore.into(), 0));
2293            }
2294        }
2295
2296        let ignore_stack = {
2297            let mut snapshot = self.snapshot.lock();
2298            let ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2299            if ignore_stack.is_all() {
2300                if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2301                    root_entry.is_ignored = true;
2302                    snapshot.insert_entry(root_entry, self.fs.as_ref());
2303                }
2304            }
2305            ignore_stack
2306        };
2307
2308        if is_dir {
2309            let path: Arc<Path> = Arc::from(Path::new(""));
2310            let mut ancestor_inodes = TreeSet::default();
2311            if let Some(root_inode) = root_inode {
2312                ancestor_inodes.insert(root_inode);
2313            }
2314
2315            let (tx, rx) = channel::unbounded();
2316            self.executor
2317                .block(tx.send(ScanJob {
2318                    abs_path: root_abs_path.to_path_buf(),
2319                    path,
2320                    ignore_stack,
2321                    ancestor_inodes,
2322                    scan_queue: tx.clone(),
2323                }))
2324                .unwrap();
2325            drop(tx);
2326
2327            self.executor
2328                .scoped(|scope| {
2329                    for _ in 0..self.executor.num_cpus() {
2330                        scope.spawn(async {
2331                            while let Ok(job) = rx.recv().await {
2332                                if let Err(err) = self
2333                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2334                                    .await
2335                                {
2336                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2337                                }
2338                            }
2339                        });
2340                    }
2341                })
2342                .await;
2343        }
2344
2345        Ok(())
2346    }
2347
2348    async fn scan_dir(
2349        &self,
2350        root_char_bag: CharBag,
2351        next_entry_id: Arc<AtomicUsize>,
2352        job: &ScanJob,
2353    ) -> Result<()> {
2354        let mut new_entries: Vec<Entry> = Vec::new();
2355        let mut new_jobs: Vec<ScanJob> = Vec::new();
2356        let mut ignore_stack = job.ignore_stack.clone();
2357        let mut new_ignore = None;
2358
2359        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2360        while let Some(child_abs_path) = child_paths.next().await {
2361            let child_abs_path = match child_abs_path {
2362                Ok(child_abs_path) => child_abs_path,
2363                Err(error) => {
2364                    log::error!("error processing entry {:?}", error);
2365                    continue;
2366                }
2367            };
2368            let child_name = child_abs_path.file_name().unwrap();
2369            let child_path: Arc<Path> = job.path.join(child_name).into();
2370            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2371                Ok(Some(metadata)) => metadata,
2372                Ok(None) => continue,
2373                Err(err) => {
2374                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2375                    continue;
2376                }
2377            };
2378
2379            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2380            if child_name == *GITIGNORE {
2381                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2382                    Ok(ignore) => {
2383                        let ignore = Arc::new(ignore);
2384                        ignore_stack =
2385                            ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2386                        new_ignore = Some(ignore);
2387                    }
2388                    Err(error) => {
2389                        log::error!(
2390                            "error loading .gitignore file {:?} - {:?}",
2391                            child_name,
2392                            error
2393                        );
2394                    }
2395                }
2396
2397                // Update ignore status of any child entries we've already processed to reflect the
2398                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2399                // there should rarely be too numerous. Update the ignore stack associated with any
2400                // new jobs as well.
2401                let mut new_jobs = new_jobs.iter_mut();
2402                for entry in &mut new_entries {
2403                    let entry_abs_path = self.abs_path().join(&entry.path);
2404                    entry.is_ignored =
2405                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2406                    if entry.is_dir() {
2407                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2408                            IgnoreStack::all()
2409                        } else {
2410                            ignore_stack.clone()
2411                        };
2412                    }
2413                }
2414            }
2415
2416            let mut child_entry = Entry::new(
2417                child_path.clone(),
2418                &child_metadata,
2419                &next_entry_id,
2420                root_char_bag,
2421            );
2422
2423            if child_entry.is_dir() {
2424                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2425                child_entry.is_ignored = is_ignored;
2426
2427                if !job.ancestor_inodes.contains(&child_entry.inode) {
2428                    let mut ancestor_inodes = job.ancestor_inodes.clone();
2429                    ancestor_inodes.insert(child_entry.inode);
2430                    new_jobs.push(ScanJob {
2431                        abs_path: child_abs_path,
2432                        path: child_path,
2433                        ignore_stack: if is_ignored {
2434                            IgnoreStack::all()
2435                        } else {
2436                            ignore_stack.clone()
2437                        },
2438                        ancestor_inodes,
2439                        scan_queue: job.scan_queue.clone(),
2440                    });
2441                }
2442            } else {
2443                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2444            }
2445
2446            new_entries.push(child_entry);
2447        }
2448
2449        self.snapshot.lock().populate_dir(
2450            job.path.clone(),
2451            new_entries,
2452            new_ignore,
2453            self.fs.as_ref(),
2454        );
2455        for new_job in new_jobs {
2456            job.scan_queue.send(new_job).await.unwrap();
2457        }
2458
2459        Ok(())
2460    }
2461
2462    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2463        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2464        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2465
2466        let root_char_bag;
2467        let root_abs_path;
2468        let next_entry_id;
2469        {
2470            let snapshot = self.snapshot.lock();
2471            root_char_bag = snapshot.root_char_bag;
2472            root_abs_path = snapshot.abs_path.clone();
2473            next_entry_id = snapshot.next_entry_id.clone();
2474        }
2475
2476        let root_canonical_path = if let Ok(path) = self.fs.canonicalize(&root_abs_path).await {
2477            path
2478        } else {
2479            return false;
2480        };
2481        let metadata = futures::future::join_all(
2482            events
2483                .iter()
2484                .map(|event| self.fs.metadata(&event.path))
2485                .collect::<Vec<_>>(),
2486        )
2487        .await;
2488
2489        // Hold the snapshot lock while clearing and re-inserting the root entries
2490        // for each event. This way, the snapshot is not observable to the foreground
2491        // thread while this operation is in-progress.
2492        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2493        {
2494            let mut snapshot = self.snapshot.lock();
2495            snapshot.scan_id += 1;
2496            for event in &events {
2497                if let Ok(path) = event.path.strip_prefix(&root_canonical_path) {
2498                    snapshot.remove_path(path);
2499                }
2500            }
2501
2502            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2503                let path: Arc<Path> = match event.path.strip_prefix(&root_canonical_path) {
2504                    Ok(path) => Arc::from(path.to_path_buf()),
2505                    Err(_) => {
2506                        log::error!(
2507                            "unexpected event {:?} for root path {:?}",
2508                            event.path,
2509                            root_canonical_path
2510                        );
2511                        continue;
2512                    }
2513                };
2514                let abs_path = root_abs_path.join(&path);
2515
2516                match metadata {
2517                    Ok(Some(metadata)) => {
2518                        let ignore_stack =
2519                            snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2520                        let mut fs_entry = Entry::new(
2521                            path.clone(),
2522                            &metadata,
2523                            snapshot.next_entry_id.as_ref(),
2524                            snapshot.root_char_bag,
2525                        );
2526                        fs_entry.is_ignored = ignore_stack.is_all();
2527                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2528
2529                        let scan_id = snapshot.scan_id;
2530                        if let Some(repo) = snapshot.in_dot_git(&path) {
2531                            repo.repo.lock().reload_index();
2532                            repo.scan_id = scan_id;
2533                        }
2534
2535                        let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2536                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2537                            ancestor_inodes.insert(metadata.inode);
2538                            self.executor
2539                                .block(scan_queue_tx.send(ScanJob {
2540                                    abs_path,
2541                                    path,
2542                                    ignore_stack,
2543                                    ancestor_inodes,
2544                                    scan_queue: scan_queue_tx.clone(),
2545                                }))
2546                                .unwrap();
2547                        }
2548                    }
2549                    Ok(None) => {}
2550                    Err(err) => {
2551                        // TODO - create a special 'error' entry in the entries tree to mark this
2552                        log::error!("error reading file on event {:?}", err);
2553                    }
2554                }
2555            }
2556            drop(scan_queue_tx);
2557        }
2558
2559        // Scan any directories that were created as part of this event batch.
2560        self.executor
2561            .scoped(|scope| {
2562                for _ in 0..self.executor.num_cpus() {
2563                    scope.spawn(async {
2564                        while let Ok(job) = scan_queue_rx.recv().await {
2565                            if let Err(err) = self
2566                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2567                                .await
2568                            {
2569                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2570                            }
2571                        }
2572                    });
2573                }
2574            })
2575            .await;
2576
2577        // Attempt to detect renames only over a single batch of file-system events.
2578        self.snapshot.lock().removed_entry_ids.clear();
2579
2580        self.update_ignore_statuses().await;
2581        self.update_git_repositories();
2582        true
2583    }
2584
2585    async fn update_ignore_statuses(&self) {
2586        let mut snapshot = self.snapshot();
2587
2588        let mut ignores_to_update = Vec::new();
2589        let mut ignores_to_delete = Vec::new();
2590        for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2591            if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2592                if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2593                    ignores_to_update.push(parent_abs_path.clone());
2594                }
2595
2596                let ignore_path = parent_path.join(&*GITIGNORE);
2597                if snapshot.entry_for_path(ignore_path).is_none() {
2598                    ignores_to_delete.push(parent_abs_path.clone());
2599                }
2600            }
2601        }
2602
2603        for parent_abs_path in ignores_to_delete {
2604            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2605            self.snapshot
2606                .lock()
2607                .ignores_by_parent_abs_path
2608                .remove(&parent_abs_path);
2609        }
2610
2611        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2612        ignores_to_update.sort_unstable();
2613        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2614        while let Some(parent_abs_path) = ignores_to_update.next() {
2615            while ignores_to_update
2616                .peek()
2617                .map_or(false, |p| p.starts_with(&parent_abs_path))
2618            {
2619                ignores_to_update.next().unwrap();
2620            }
2621
2622            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2623            ignore_queue_tx
2624                .send(UpdateIgnoreStatusJob {
2625                    abs_path: parent_abs_path,
2626                    ignore_stack,
2627                    ignore_queue: ignore_queue_tx.clone(),
2628                })
2629                .await
2630                .unwrap();
2631        }
2632        drop(ignore_queue_tx);
2633
2634        self.executor
2635            .scoped(|scope| {
2636                for _ in 0..self.executor.num_cpus() {
2637                    scope.spawn(async {
2638                        while let Ok(job) = ignore_queue_rx.recv().await {
2639                            self.update_ignore_status(job, &snapshot).await;
2640                        }
2641                    });
2642                }
2643            })
2644            .await;
2645    }
2646
2647    fn update_git_repositories(&self) {
2648        let mut snapshot = self.snapshot.lock();
2649        let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2650        git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2651        snapshot.git_repositories = git_repositories;
2652    }
2653
2654    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2655        let mut ignore_stack = job.ignore_stack;
2656        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2657            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2658        }
2659
2660        let mut entries_by_id_edits = Vec::new();
2661        let mut entries_by_path_edits = Vec::new();
2662        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2663        for mut entry in snapshot.child_entries(path).cloned() {
2664            let was_ignored = entry.is_ignored;
2665            let abs_path = self.abs_path().join(&entry.path);
2666            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2667            if entry.is_dir() {
2668                let child_ignore_stack = if entry.is_ignored {
2669                    IgnoreStack::all()
2670                } else {
2671                    ignore_stack.clone()
2672                };
2673                job.ignore_queue
2674                    .send(UpdateIgnoreStatusJob {
2675                        abs_path: abs_path.into(),
2676                        ignore_stack: child_ignore_stack,
2677                        ignore_queue: job.ignore_queue.clone(),
2678                    })
2679                    .await
2680                    .unwrap();
2681            }
2682
2683            if entry.is_ignored != was_ignored {
2684                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2685                path_entry.scan_id = snapshot.scan_id;
2686                path_entry.is_ignored = entry.is_ignored;
2687                entries_by_id_edits.push(Edit::Insert(path_entry));
2688                entries_by_path_edits.push(Edit::Insert(entry));
2689            }
2690        }
2691
2692        let mut snapshot = self.snapshot.lock();
2693        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2694        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2695    }
2696}
2697
2698fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2699    let mut result = root_char_bag;
2700    result.extend(
2701        path.to_string_lossy()
2702            .chars()
2703            .map(|c| c.to_ascii_lowercase()),
2704    );
2705    result
2706}
2707
2708struct ScanJob {
2709    abs_path: PathBuf,
2710    path: Arc<Path>,
2711    ignore_stack: Arc<IgnoreStack>,
2712    scan_queue: Sender<ScanJob>,
2713    ancestor_inodes: TreeSet<u64>,
2714}
2715
2716struct UpdateIgnoreStatusJob {
2717    abs_path: Arc<Path>,
2718    ignore_stack: Arc<IgnoreStack>,
2719    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2720}
2721
2722pub trait WorktreeHandle {
2723    #[cfg(any(test, feature = "test-support"))]
2724    fn flush_fs_events<'a>(
2725        &self,
2726        cx: &'a gpui::TestAppContext,
2727    ) -> futures::future::LocalBoxFuture<'a, ()>;
2728}
2729
2730impl WorktreeHandle for ModelHandle<Worktree> {
2731    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2732    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2733    // extra directory scans, and emit extra scan-state notifications.
2734    //
2735    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2736    // to ensure that all redundant FS events have already been processed.
2737    #[cfg(any(test, feature = "test-support"))]
2738    fn flush_fs_events<'a>(
2739        &self,
2740        cx: &'a gpui::TestAppContext,
2741    ) -> futures::future::LocalBoxFuture<'a, ()> {
2742        use smol::future::FutureExt;
2743
2744        let filename = "fs-event-sentinel";
2745        let tree = self.clone();
2746        let (fs, root_path) = self.read_with(cx, |tree, _| {
2747            let tree = tree.as_local().unwrap();
2748            (tree.fs.clone(), tree.abs_path().clone())
2749        });
2750
2751        async move {
2752            fs.create_file(&root_path.join(filename), Default::default())
2753                .await
2754                .unwrap();
2755            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2756                .await;
2757
2758            fs.remove_file(&root_path.join(filename), Default::default())
2759                .await
2760                .unwrap();
2761            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2762                .await;
2763
2764            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2765                .await;
2766        }
2767        .boxed_local()
2768    }
2769}
2770
2771#[derive(Clone, Debug)]
2772struct TraversalProgress<'a> {
2773    max_path: &'a Path,
2774    count: usize,
2775    visible_count: usize,
2776    file_count: usize,
2777    visible_file_count: usize,
2778}
2779
2780impl<'a> TraversalProgress<'a> {
2781    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2782        match (include_ignored, include_dirs) {
2783            (true, true) => self.count,
2784            (true, false) => self.file_count,
2785            (false, true) => self.visible_count,
2786            (false, false) => self.visible_file_count,
2787        }
2788    }
2789}
2790
2791impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2792    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2793        self.max_path = summary.max_path.as_ref();
2794        self.count += summary.count;
2795        self.visible_count += summary.visible_count;
2796        self.file_count += summary.file_count;
2797        self.visible_file_count += summary.visible_file_count;
2798    }
2799}
2800
2801impl<'a> Default for TraversalProgress<'a> {
2802    fn default() -> Self {
2803        Self {
2804            max_path: Path::new(""),
2805            count: 0,
2806            visible_count: 0,
2807            file_count: 0,
2808            visible_file_count: 0,
2809        }
2810    }
2811}
2812
2813pub struct Traversal<'a> {
2814    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2815    include_ignored: bool,
2816    include_dirs: bool,
2817}
2818
2819impl<'a> Traversal<'a> {
2820    pub fn advance(&mut self) -> bool {
2821        self.advance_to_offset(self.offset() + 1)
2822    }
2823
2824    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2825        self.cursor.seek_forward(
2826            &TraversalTarget::Count {
2827                count: offset,
2828                include_dirs: self.include_dirs,
2829                include_ignored: self.include_ignored,
2830            },
2831            Bias::Right,
2832            &(),
2833        )
2834    }
2835
2836    pub fn advance_to_sibling(&mut self) -> bool {
2837        while let Some(entry) = self.cursor.item() {
2838            self.cursor.seek_forward(
2839                &TraversalTarget::PathSuccessor(&entry.path),
2840                Bias::Left,
2841                &(),
2842            );
2843            if let Some(entry) = self.cursor.item() {
2844                if (self.include_dirs || !entry.is_dir())
2845                    && (self.include_ignored || !entry.is_ignored)
2846                {
2847                    return true;
2848                }
2849            }
2850        }
2851        false
2852    }
2853
2854    pub fn entry(&self) -> Option<&'a Entry> {
2855        self.cursor.item()
2856    }
2857
2858    pub fn offset(&self) -> usize {
2859        self.cursor
2860            .start()
2861            .count(self.include_dirs, self.include_ignored)
2862    }
2863}
2864
2865impl<'a> Iterator for Traversal<'a> {
2866    type Item = &'a Entry;
2867
2868    fn next(&mut self) -> Option<Self::Item> {
2869        if let Some(item) = self.entry() {
2870            self.advance();
2871            Some(item)
2872        } else {
2873            None
2874        }
2875    }
2876}
2877
2878#[derive(Debug)]
2879enum TraversalTarget<'a> {
2880    Path(&'a Path),
2881    PathSuccessor(&'a Path),
2882    Count {
2883        count: usize,
2884        include_ignored: bool,
2885        include_dirs: bool,
2886    },
2887}
2888
2889impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2890    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2891        match self {
2892            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2893            TraversalTarget::PathSuccessor(path) => {
2894                if !cursor_location.max_path.starts_with(path) {
2895                    Ordering::Equal
2896                } else {
2897                    Ordering::Greater
2898                }
2899            }
2900            TraversalTarget::Count {
2901                count,
2902                include_dirs,
2903                include_ignored,
2904            } => Ord::cmp(
2905                count,
2906                &cursor_location.count(*include_dirs, *include_ignored),
2907            ),
2908        }
2909    }
2910}
2911
2912struct ChildEntriesIter<'a> {
2913    parent_path: &'a Path,
2914    traversal: Traversal<'a>,
2915}
2916
2917impl<'a> Iterator for ChildEntriesIter<'a> {
2918    type Item = &'a Entry;
2919
2920    fn next(&mut self) -> Option<Self::Item> {
2921        if let Some(item) = self.traversal.entry() {
2922            if item.path.starts_with(&self.parent_path) {
2923                self.traversal.advance_to_sibling();
2924                return Some(item);
2925            }
2926        }
2927        None
2928    }
2929}
2930
2931impl<'a> From<&'a Entry> for proto::Entry {
2932    fn from(entry: &'a Entry) -> Self {
2933        Self {
2934            id: entry.id.to_proto(),
2935            is_dir: entry.is_dir(),
2936            path: entry.path.as_os_str().as_bytes().to_vec(),
2937            inode: entry.inode,
2938            mtime: Some(entry.mtime.into()),
2939            is_symlink: entry.is_symlink,
2940            is_ignored: entry.is_ignored,
2941        }
2942    }
2943}
2944
2945impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2946    type Error = anyhow::Error;
2947
2948    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2949        if let Some(mtime) = entry.mtime {
2950            let kind = if entry.is_dir {
2951                EntryKind::Dir
2952            } else {
2953                let mut char_bag = *root_char_bag;
2954                char_bag.extend(
2955                    String::from_utf8_lossy(&entry.path)
2956                        .chars()
2957                        .map(|c| c.to_ascii_lowercase()),
2958                );
2959                EntryKind::File(char_bag)
2960            };
2961            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2962            Ok(Entry {
2963                id: ProjectEntryId::from_proto(entry.id),
2964                kind,
2965                path,
2966                inode: entry.inode,
2967                mtime: mtime.into(),
2968                is_symlink: entry.is_symlink,
2969                is_ignored: entry.is_ignored,
2970            })
2971        } else {
2972            Err(anyhow!(
2973                "missing mtime in remote worktree entry {:?}",
2974                entry.path
2975            ))
2976        }
2977    }
2978}
2979
2980async fn send_worktree_update(client: &Arc<Client>, update: proto::UpdateWorktree) -> Result<()> {
2981    #[cfg(any(test, feature = "test-support"))]
2982    const MAX_CHUNK_SIZE: usize = 2;
2983    #[cfg(not(any(test, feature = "test-support")))]
2984    const MAX_CHUNK_SIZE: usize = 256;
2985
2986    for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
2987        client.request(update).await?;
2988    }
2989
2990    Ok(())
2991}
2992
2993#[cfg(test)]
2994mod tests {
2995    use super::*;
2996    use anyhow::Result;
2997    use client::test::FakeHttpClient;
2998    use fs::repository::FakeGitRepository;
2999    use fs::{FakeFs, RealFs};
3000    use gpui::{executor::Deterministic, TestAppContext};
3001    use rand::prelude::*;
3002    use serde_json::json;
3003    use std::{
3004        env,
3005        fmt::Write,
3006        time::{SystemTime, UNIX_EPOCH},
3007    };
3008
3009    use util::test::temp_tree;
3010
3011    #[gpui::test]
3012    async fn test_traversal(cx: &mut TestAppContext) {
3013        let fs = FakeFs::new(cx.background());
3014        fs.insert_tree(
3015            "/root",
3016            json!({
3017               ".gitignore": "a/b\n",
3018               "a": {
3019                   "b": "",
3020                   "c": "",
3021               }
3022            }),
3023        )
3024        .await;
3025
3026        let http_client = FakeHttpClient::with_404_response();
3027        let client = cx.read(|cx| Client::new(http_client, cx));
3028
3029        let tree = Worktree::local(
3030            client,
3031            Arc::from(Path::new("/root")),
3032            true,
3033            fs,
3034            Default::default(),
3035            &mut cx.to_async(),
3036        )
3037        .await
3038        .unwrap();
3039        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3040            .await;
3041
3042        tree.read_with(cx, |tree, _| {
3043            assert_eq!(
3044                tree.entries(false)
3045                    .map(|entry| entry.path.as_ref())
3046                    .collect::<Vec<_>>(),
3047                vec![
3048                    Path::new(""),
3049                    Path::new(".gitignore"),
3050                    Path::new("a"),
3051                    Path::new("a/c"),
3052                ]
3053            );
3054            assert_eq!(
3055                tree.entries(true)
3056                    .map(|entry| entry.path.as_ref())
3057                    .collect::<Vec<_>>(),
3058                vec![
3059                    Path::new(""),
3060                    Path::new(".gitignore"),
3061                    Path::new("a"),
3062                    Path::new("a/b"),
3063                    Path::new("a/c"),
3064                ]
3065            );
3066        })
3067    }
3068
3069    #[gpui::test(iterations = 10)]
3070    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3071        let fs = FakeFs::new(cx.background());
3072        fs.insert_tree(
3073            "/root",
3074            json!({
3075                "lib": {
3076                    "a": {
3077                        "a.txt": ""
3078                    },
3079                    "b": {
3080                        "b.txt": ""
3081                    }
3082                }
3083            }),
3084        )
3085        .await;
3086        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3087        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3088
3089        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3090        let tree = Worktree::local(
3091            client,
3092            Arc::from(Path::new("/root")),
3093            true,
3094            fs.clone(),
3095            Default::default(),
3096            &mut cx.to_async(),
3097        )
3098        .await
3099        .unwrap();
3100
3101        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3102            .await;
3103
3104        tree.read_with(cx, |tree, _| {
3105            assert_eq!(
3106                tree.entries(false)
3107                    .map(|entry| entry.path.as_ref())
3108                    .collect::<Vec<_>>(),
3109                vec![
3110                    Path::new(""),
3111                    Path::new("lib"),
3112                    Path::new("lib/a"),
3113                    Path::new("lib/a/a.txt"),
3114                    Path::new("lib/a/lib"),
3115                    Path::new("lib/b"),
3116                    Path::new("lib/b/b.txt"),
3117                    Path::new("lib/b/lib"),
3118                ]
3119            );
3120        });
3121
3122        fs.rename(
3123            Path::new("/root/lib/a/lib"),
3124            Path::new("/root/lib/a/lib-2"),
3125            Default::default(),
3126        )
3127        .await
3128        .unwrap();
3129        executor.run_until_parked();
3130        tree.read_with(cx, |tree, _| {
3131            assert_eq!(
3132                tree.entries(false)
3133                    .map(|entry| entry.path.as_ref())
3134                    .collect::<Vec<_>>(),
3135                vec![
3136                    Path::new(""),
3137                    Path::new("lib"),
3138                    Path::new("lib/a"),
3139                    Path::new("lib/a/a.txt"),
3140                    Path::new("lib/a/lib-2"),
3141                    Path::new("lib/b"),
3142                    Path::new("lib/b/b.txt"),
3143                    Path::new("lib/b/lib"),
3144                ]
3145            );
3146        });
3147    }
3148
3149    #[gpui::test]
3150    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3151        let parent_dir = temp_tree(json!({
3152            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3153            "tree": {
3154                ".git": {},
3155                ".gitignore": "ignored-dir\n",
3156                "tracked-dir": {
3157                    "tracked-file1": "",
3158                    "ancestor-ignored-file1": "",
3159                },
3160                "ignored-dir": {
3161                    "ignored-file1": ""
3162                }
3163            }
3164        }));
3165        let dir = parent_dir.path().join("tree");
3166
3167        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3168
3169        let tree = Worktree::local(
3170            client,
3171            dir.as_path(),
3172            true,
3173            Arc::new(RealFs),
3174            Default::default(),
3175            &mut cx.to_async(),
3176        )
3177        .await
3178        .unwrap();
3179        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3180            .await;
3181        tree.flush_fs_events(cx).await;
3182        cx.read(|cx| {
3183            let tree = tree.read(cx);
3184            assert!(
3185                !tree
3186                    .entry_for_path("tracked-dir/tracked-file1")
3187                    .unwrap()
3188                    .is_ignored
3189            );
3190            assert!(
3191                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3192                    .unwrap()
3193                    .is_ignored
3194            );
3195            assert!(
3196                tree.entry_for_path("ignored-dir/ignored-file1")
3197                    .unwrap()
3198                    .is_ignored
3199            );
3200        });
3201
3202        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3203        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3204        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3205        tree.flush_fs_events(cx).await;
3206        cx.read(|cx| {
3207            let tree = tree.read(cx);
3208            assert!(
3209                !tree
3210                    .entry_for_path("tracked-dir/tracked-file2")
3211                    .unwrap()
3212                    .is_ignored
3213            );
3214            assert!(
3215                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3216                    .unwrap()
3217                    .is_ignored
3218            );
3219            assert!(
3220                tree.entry_for_path("ignored-dir/ignored-file2")
3221                    .unwrap()
3222                    .is_ignored
3223            );
3224            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3225        });
3226    }
3227
3228    #[gpui::test]
3229    async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3230        let root = temp_tree(json!({
3231            "dir1": {
3232                ".git": {},
3233                "deps": {
3234                    "dep1": {
3235                        ".git": {},
3236                        "src": {
3237                            "a.txt": ""
3238                        }
3239                    }
3240                },
3241                "src": {
3242                    "b.txt": ""
3243                }
3244            },
3245            "c.txt": "",
3246
3247        }));
3248
3249        let http_client = FakeHttpClient::with_404_response();
3250        let client = cx.read(|cx| Client::new(http_client, cx));
3251        let tree = Worktree::local(
3252            client,
3253            root.path(),
3254            true,
3255            Arc::new(RealFs),
3256            Default::default(),
3257            &mut cx.to_async(),
3258        )
3259        .await
3260        .unwrap();
3261
3262        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3263            .await;
3264        tree.flush_fs_events(cx).await;
3265
3266        tree.read_with(cx, |tree, _cx| {
3267            let tree = tree.as_local().unwrap();
3268
3269            assert!(tree.repo_for("c.txt".as_ref()).is_none());
3270
3271            let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3272            assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3273            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3274
3275            let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3276            assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3277            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3278        });
3279
3280        let original_scan_id = tree.read_with(cx, |tree, _cx| {
3281            let tree = tree.as_local().unwrap();
3282            tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3283        });
3284
3285        std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3286        tree.flush_fs_events(cx).await;
3287
3288        tree.read_with(cx, |tree, _cx| {
3289            let tree = tree.as_local().unwrap();
3290            let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3291            assert_ne!(
3292                original_scan_id, new_scan_id,
3293                "original {original_scan_id}, new {new_scan_id}"
3294            );
3295        });
3296
3297        std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3298        tree.flush_fs_events(cx).await;
3299
3300        tree.read_with(cx, |tree, _cx| {
3301            let tree = tree.as_local().unwrap();
3302
3303            assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3304        });
3305    }
3306
3307    #[test]
3308    fn test_changed_repos() {
3309        fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3310            GitRepositoryEntry {
3311                repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3312                scan_id,
3313                content_path: git_dir_path.as_ref().parent().unwrap().into(),
3314                git_dir_path: git_dir_path.as_ref().into(),
3315            }
3316        }
3317
3318        let prev_repos: Vec<GitRepositoryEntry> = vec![
3319            fake_entry("/.git", 0),
3320            fake_entry("/a/.git", 0),
3321            fake_entry("/a/b/.git", 0),
3322        ];
3323
3324        let new_repos: Vec<GitRepositoryEntry> = vec![
3325            fake_entry("/a/.git", 1),
3326            fake_entry("/a/b/.git", 0),
3327            fake_entry("/a/c/.git", 0),
3328        ];
3329
3330        let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3331
3332        // Deletion retained
3333        assert!(res
3334            .iter()
3335            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3336            .is_some());
3337
3338        // Update retained
3339        assert!(res
3340            .iter()
3341            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3342            .is_some());
3343
3344        // Addition retained
3345        assert!(res
3346            .iter()
3347            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3348            .is_some());
3349
3350        // Nochange, not retained
3351        assert!(res
3352            .iter()
3353            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3354            .is_none());
3355    }
3356
3357    #[gpui::test]
3358    async fn test_write_file(cx: &mut TestAppContext) {
3359        let dir = temp_tree(json!({
3360            ".git": {},
3361            ".gitignore": "ignored-dir\n",
3362            "tracked-dir": {},
3363            "ignored-dir": {}
3364        }));
3365
3366        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3367
3368        let tree = Worktree::local(
3369            client,
3370            dir.path(),
3371            true,
3372            Arc::new(RealFs),
3373            Default::default(),
3374            &mut cx.to_async(),
3375        )
3376        .await
3377        .unwrap();
3378        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3379            .await;
3380        tree.flush_fs_events(cx).await;
3381
3382        tree.update(cx, |tree, cx| {
3383            tree.as_local().unwrap().write_file(
3384                Path::new("tracked-dir/file.txt"),
3385                "hello".into(),
3386                Default::default(),
3387                cx,
3388            )
3389        })
3390        .await
3391        .unwrap();
3392        tree.update(cx, |tree, cx| {
3393            tree.as_local().unwrap().write_file(
3394                Path::new("ignored-dir/file.txt"),
3395                "world".into(),
3396                Default::default(),
3397                cx,
3398            )
3399        })
3400        .await
3401        .unwrap();
3402
3403        tree.read_with(cx, |tree, _| {
3404            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3405            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3406            assert!(!tracked.is_ignored);
3407            assert!(ignored.is_ignored);
3408        });
3409    }
3410
3411    #[gpui::test(iterations = 30)]
3412    async fn test_create_directory(cx: &mut TestAppContext) {
3413        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3414
3415        let fs = FakeFs::new(cx.background());
3416        fs.insert_tree(
3417            "/a",
3418            json!({
3419                "b": {},
3420                "c": {},
3421                "d": {},
3422            }),
3423        )
3424        .await;
3425
3426        let tree = Worktree::local(
3427            client,
3428            "/a".as_ref(),
3429            true,
3430            fs,
3431            Default::default(),
3432            &mut cx.to_async(),
3433        )
3434        .await
3435        .unwrap();
3436
3437        let entry = tree
3438            .update(cx, |tree, cx| {
3439                tree.as_local_mut()
3440                    .unwrap()
3441                    .create_entry("a/e".as_ref(), true, cx)
3442            })
3443            .await
3444            .unwrap();
3445        assert!(entry.is_dir());
3446
3447        cx.foreground().run_until_parked();
3448        tree.read_with(cx, |tree, _| {
3449            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3450        });
3451    }
3452
3453    #[gpui::test(iterations = 100)]
3454    fn test_random(mut rng: StdRng) {
3455        let operations = env::var("OPERATIONS")
3456            .map(|o| o.parse().unwrap())
3457            .unwrap_or(40);
3458        let initial_entries = env::var("INITIAL_ENTRIES")
3459            .map(|o| o.parse().unwrap())
3460            .unwrap_or(20);
3461
3462        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
3463        for _ in 0..initial_entries {
3464            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
3465        }
3466        log::info!("Generated initial tree");
3467
3468        let (notify_tx, _notify_rx) = mpsc::unbounded();
3469        let fs = Arc::new(RealFs);
3470        let next_entry_id = Arc::new(AtomicUsize::new(0));
3471        let mut initial_snapshot = LocalSnapshot {
3472            abs_path: root_dir.path().into(),
3473            removed_entry_ids: Default::default(),
3474            ignores_by_parent_abs_path: Default::default(),
3475            git_repositories: Default::default(),
3476            next_entry_id: next_entry_id.clone(),
3477            snapshot: Snapshot {
3478                id: WorktreeId::from_usize(0),
3479                entries_by_path: Default::default(),
3480                entries_by_id: Default::default(),
3481                root_name: Default::default(),
3482                root_char_bag: Default::default(),
3483                scan_id: 0,
3484                is_complete: true,
3485            },
3486            extension_counts: Default::default(),
3487        };
3488        initial_snapshot.insert_entry(
3489            Entry::new(
3490                Path::new("").into(),
3491                &smol::block_on(fs.metadata(root_dir.path()))
3492                    .unwrap()
3493                    .unwrap(),
3494                &next_entry_id,
3495                Default::default(),
3496            ),
3497            fs.as_ref(),
3498        );
3499        let mut scanner = BackgroundScanner::new(
3500            Arc::new(Mutex::new(initial_snapshot.clone())),
3501            notify_tx,
3502            fs.clone(),
3503            Arc::new(gpui::executor::Background::new()),
3504        );
3505        smol::block_on(scanner.scan_dirs()).unwrap();
3506        scanner.snapshot().check_invariants();
3507
3508        let mut events = Vec::new();
3509        let mut snapshots = Vec::new();
3510        let mut mutations_len = operations;
3511        while mutations_len > 1 {
3512            if !events.is_empty() && rng.gen_bool(0.4) {
3513                let len = rng.gen_range(0..=events.len());
3514                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3515                log::info!("Delivering events: {:#?}", to_deliver);
3516                smol::block_on(scanner.process_events(to_deliver));
3517                scanner.snapshot().check_invariants();
3518            } else {
3519                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3520                mutations_len -= 1;
3521            }
3522
3523            if rng.gen_bool(0.2) {
3524                snapshots.push(scanner.snapshot());
3525            }
3526        }
3527        log::info!("Quiescing: {:#?}", events);
3528        smol::block_on(scanner.process_events(events));
3529        scanner.snapshot().check_invariants();
3530
3531        let (notify_tx, _notify_rx) = mpsc::unbounded();
3532        let mut new_scanner = BackgroundScanner::new(
3533            Arc::new(Mutex::new(initial_snapshot)),
3534            notify_tx,
3535            scanner.fs.clone(),
3536            scanner.executor.clone(),
3537        );
3538        smol::block_on(new_scanner.scan_dirs()).unwrap();
3539        assert_eq!(
3540            scanner.snapshot().to_vec(true),
3541            new_scanner.snapshot().to_vec(true)
3542        );
3543
3544        for mut prev_snapshot in snapshots {
3545            let include_ignored = rng.gen::<bool>();
3546            if !include_ignored {
3547                let mut entries_by_path_edits = Vec::new();
3548                let mut entries_by_id_edits = Vec::new();
3549                for entry in prev_snapshot
3550                    .entries_by_id
3551                    .cursor::<()>()
3552                    .filter(|e| e.is_ignored)
3553                {
3554                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3555                    entries_by_id_edits.push(Edit::Remove(entry.id));
3556                }
3557
3558                prev_snapshot
3559                    .entries_by_path
3560                    .edit(entries_by_path_edits, &());
3561                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3562            }
3563
3564            let update = scanner
3565                .snapshot()
3566                .build_update(&prev_snapshot, 0, 0, include_ignored);
3567            prev_snapshot.apply_remote_update(update).unwrap();
3568            assert_eq!(
3569                prev_snapshot.to_vec(true),
3570                scanner.snapshot().to_vec(include_ignored)
3571            );
3572        }
3573    }
3574
3575    fn randomly_mutate_tree(
3576        root_path: &Path,
3577        insertion_probability: f64,
3578        rng: &mut impl Rng,
3579    ) -> Result<Vec<fsevent::Event>> {
3580        let root_path = root_path.canonicalize().unwrap();
3581        let (dirs, files) = read_dir_recursive(root_path.clone());
3582
3583        let mut events = Vec::new();
3584        let mut record_event = |path: PathBuf| {
3585            events.push(fsevent::Event {
3586                event_id: SystemTime::now()
3587                    .duration_since(UNIX_EPOCH)
3588                    .unwrap()
3589                    .as_secs(),
3590                flags: fsevent::StreamFlags::empty(),
3591                path,
3592            });
3593        };
3594
3595        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3596            let path = dirs.choose(rng).unwrap();
3597            let new_path = path.join(gen_name(rng));
3598
3599            if rng.gen() {
3600                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3601                std::fs::create_dir(&new_path)?;
3602            } else {
3603                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3604                std::fs::write(&new_path, "")?;
3605            }
3606            record_event(new_path);
3607        } else if rng.gen_bool(0.05) {
3608            let ignore_dir_path = dirs.choose(rng).unwrap();
3609            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3610
3611            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3612            let files_to_ignore = {
3613                let len = rng.gen_range(0..=subfiles.len());
3614                subfiles.choose_multiple(rng, len)
3615            };
3616            let dirs_to_ignore = {
3617                let len = rng.gen_range(0..subdirs.len());
3618                subdirs.choose_multiple(rng, len)
3619            };
3620
3621            let mut ignore_contents = String::new();
3622            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3623                writeln!(
3624                    ignore_contents,
3625                    "{}",
3626                    path_to_ignore
3627                        .strip_prefix(&ignore_dir_path)?
3628                        .to_str()
3629                        .unwrap()
3630                )
3631                .unwrap();
3632            }
3633            log::info!(
3634                "Creating {:?} with contents:\n{}",
3635                ignore_path.strip_prefix(&root_path)?,
3636                ignore_contents
3637            );
3638            std::fs::write(&ignore_path, ignore_contents).unwrap();
3639            record_event(ignore_path);
3640        } else {
3641            let old_path = {
3642                let file_path = files.choose(rng);
3643                let dir_path = dirs[1..].choose(rng);
3644                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3645            };
3646
3647            let is_rename = rng.gen();
3648            if is_rename {
3649                let new_path_parent = dirs
3650                    .iter()
3651                    .filter(|d| !d.starts_with(old_path))
3652                    .choose(rng)
3653                    .unwrap();
3654
3655                let overwrite_existing_dir =
3656                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3657                let new_path = if overwrite_existing_dir {
3658                    std::fs::remove_dir_all(&new_path_parent).ok();
3659                    new_path_parent.to_path_buf()
3660                } else {
3661                    new_path_parent.join(gen_name(rng))
3662                };
3663
3664                log::info!(
3665                    "Renaming {:?} to {}{:?}",
3666                    old_path.strip_prefix(&root_path)?,
3667                    if overwrite_existing_dir {
3668                        "overwrite "
3669                    } else {
3670                        ""
3671                    },
3672                    new_path.strip_prefix(&root_path)?
3673                );
3674                std::fs::rename(&old_path, &new_path)?;
3675                record_event(old_path.clone());
3676                record_event(new_path);
3677            } else if old_path.is_dir() {
3678                let (dirs, files) = read_dir_recursive(old_path.clone());
3679
3680                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3681                std::fs::remove_dir_all(&old_path).unwrap();
3682                for file in files {
3683                    record_event(file);
3684                }
3685                for dir in dirs {
3686                    record_event(dir);
3687                }
3688            } else {
3689                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3690                std::fs::remove_file(old_path).unwrap();
3691                record_event(old_path.clone());
3692            }
3693        }
3694
3695        Ok(events)
3696    }
3697
3698    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3699        let child_entries = std::fs::read_dir(&path).unwrap();
3700        let mut dirs = vec![path];
3701        let mut files = Vec::new();
3702        for child_entry in child_entries {
3703            let child_path = child_entry.unwrap().path();
3704            if child_path.is_dir() {
3705                let (child_dirs, child_files) = read_dir_recursive(child_path);
3706                dirs.extend(child_dirs);
3707                files.extend(child_files);
3708            } else {
3709                files.push(child_path);
3710            }
3711        }
3712        (dirs, files)
3713    }
3714
3715    fn gen_name(rng: &mut impl Rng) -> String {
3716        (0..6)
3717            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3718            .map(char::from)
3719            .collect()
3720    }
3721
3722    impl LocalSnapshot {
3723        fn check_invariants(&self) {
3724            let mut files = self.files(true, 0);
3725            let mut visible_files = self.files(false, 0);
3726            for entry in self.entries_by_path.cursor::<()>() {
3727                if entry.is_file() {
3728                    assert_eq!(files.next().unwrap().inode, entry.inode);
3729                    if !entry.is_ignored {
3730                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3731                    }
3732                }
3733            }
3734            assert!(files.next().is_none());
3735            assert!(visible_files.next().is_none());
3736
3737            let mut bfs_paths = Vec::new();
3738            let mut stack = vec![Path::new("")];
3739            while let Some(path) = stack.pop() {
3740                bfs_paths.push(path);
3741                let ix = stack.len();
3742                for child_entry in self.child_entries(path) {
3743                    stack.insert(ix, &child_entry.path);
3744                }
3745            }
3746
3747            let dfs_paths_via_iter = self
3748                .entries_by_path
3749                .cursor::<()>()
3750                .map(|e| e.path.as_ref())
3751                .collect::<Vec<_>>();
3752            assert_eq!(bfs_paths, dfs_paths_via_iter);
3753
3754            let dfs_paths_via_traversal = self
3755                .entries(true)
3756                .map(|e| e.path.as_ref())
3757                .collect::<Vec<_>>();
3758            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3759
3760            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3761                let ignore_parent_path =
3762                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3763                assert!(self.entry_for_path(&ignore_parent_path).is_some());
3764                assert!(self
3765                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3766                    .is_some());
3767            }
3768
3769            // Ensure extension counts are correct.
3770            let mut expected_extension_counts = HashMap::default();
3771            for extension in self.entries(false).filter_map(|e| e.path.extension()) {
3772                *expected_extension_counts
3773                    .entry(extension.into())
3774                    .or_insert(0) += 1;
3775            }
3776            assert_eq!(self.extension_counts, expected_extension_counts);
3777        }
3778
3779        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3780            let mut paths = Vec::new();
3781            for entry in self.entries_by_path.cursor::<()>() {
3782                if include_ignored || !entry.is_ignored {
3783                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3784                }
3785            }
3786            paths.sort_by(|a, b| a.0.cmp(b.0));
3787            paths
3788        }
3789    }
3790}