worktree.rs

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