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