worktree.rs

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