worktree.rs

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