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