worktree.rs

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