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