worktree.rs

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