worktree.rs

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