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