worktree.rs

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