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