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(path.to_path_buf()) {
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                return false;
2294            }
2295        }
2296    }
2297}
2298
2299impl BackgroundScannerState {
2300    fn should_scan_directory(&self, entry: &Entry) -> bool {
2301        (!entry.is_external && !entry.is_ignored)
2302            || entry.path.file_name() == Some(&*DOT_GIT)
2303            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2304            || self
2305                .paths_to_scan
2306                .iter()
2307                .any(|p| p.starts_with(&entry.path))
2308            || self
2309                .path_prefixes_to_scan
2310                .iter()
2311                .any(|p| entry.path.starts_with(p))
2312    }
2313
2314    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2315        let path = entry.path.clone();
2316        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2317        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2318        let mut containing_repository = None;
2319        if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2320            if let Some((workdir_path, repo)) = self.snapshot.local_repo_for_path(&path) {
2321                if let Ok(repo_path) = path.strip_prefix(&workdir_path.0) {
2322                    containing_repository = Some((
2323                        workdir_path,
2324                        repo.repo_ptr.clone(),
2325                        repo.repo_ptr.lock().staged_statuses(repo_path),
2326                    ));
2327                }
2328            }
2329        }
2330        if !ancestor_inodes.contains(&entry.inode) {
2331            ancestor_inodes.insert(entry.inode);
2332            scan_job_tx
2333                .try_send(ScanJob {
2334                    abs_path,
2335                    path,
2336                    ignore_stack,
2337                    scan_queue: scan_job_tx.clone(),
2338                    ancestor_inodes,
2339                    is_external: entry.is_external,
2340                    containing_repository,
2341                })
2342                .unwrap();
2343        }
2344    }
2345
2346    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2347        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2348            entry.id = removed_entry_id;
2349        } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2350            entry.id = existing_entry.id;
2351        }
2352    }
2353
2354    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2355        self.reuse_entry_id(&mut entry);
2356        let entry = self.snapshot.insert_entry(entry, fs);
2357        if entry.path.file_name() == Some(&DOT_GIT) {
2358            self.build_git_repository(entry.path.clone(), fs);
2359        }
2360
2361        #[cfg(test)]
2362        self.snapshot.check_invariants(false);
2363
2364        entry
2365    }
2366
2367    fn populate_dir(
2368        &mut self,
2369        parent_path: &Arc<Path>,
2370        entries: impl IntoIterator<Item = Entry>,
2371        ignore: Option<Arc<Gitignore>>,
2372    ) {
2373        let mut parent_entry = if let Some(parent_entry) = self
2374            .snapshot
2375            .entries_by_path
2376            .get(&PathKey(parent_path.clone()), &())
2377        {
2378            parent_entry.clone()
2379        } else {
2380            log::warn!(
2381                "populating a directory {:?} that has been removed",
2382                parent_path
2383            );
2384            return;
2385        };
2386
2387        match parent_entry.kind {
2388            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2389            EntryKind::Dir => {}
2390            _ => return,
2391        }
2392
2393        if let Some(ignore) = ignore {
2394            let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2395            self.snapshot
2396                .ignores_by_parent_abs_path
2397                .insert(abs_parent_path, (ignore, false));
2398        }
2399
2400        let parent_entry_id = parent_entry.id;
2401        self.scanned_dirs.insert(parent_entry_id);
2402        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2403        let mut entries_by_id_edits = Vec::new();
2404
2405        for entry in entries {
2406            entries_by_id_edits.push(Edit::Insert(PathEntry {
2407                id: entry.id,
2408                path: entry.path.clone(),
2409                is_ignored: entry.is_ignored,
2410                scan_id: self.snapshot.scan_id,
2411            }));
2412            entries_by_path_edits.push(Edit::Insert(entry));
2413        }
2414
2415        self.snapshot
2416            .entries_by_path
2417            .edit(entries_by_path_edits, &());
2418        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2419
2420        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2421            self.changed_paths.insert(ix, parent_path.clone());
2422        }
2423
2424        #[cfg(test)]
2425        self.snapshot.check_invariants(false);
2426    }
2427
2428    fn remove_path(&mut self, path: &Path) {
2429        let mut new_entries;
2430        let removed_entries;
2431        {
2432            let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2433            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2434            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2435            new_entries.append(cursor.suffix(&()), &());
2436        }
2437        self.snapshot.entries_by_path = new_entries;
2438
2439        let mut entries_by_id_edits = Vec::new();
2440        for entry in removed_entries.cursor::<()>() {
2441            let removed_entry_id = self
2442                .removed_entry_ids
2443                .entry(entry.inode)
2444                .or_insert(entry.id);
2445            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2446            entries_by_id_edits.push(Edit::Remove(entry.id));
2447        }
2448        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2449
2450        if path.file_name() == Some(&GITIGNORE) {
2451            let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2452            if let Some((_, needs_update)) = self
2453                .snapshot
2454                .ignores_by_parent_abs_path
2455                .get_mut(abs_parent_path.as_path())
2456            {
2457                *needs_update = true;
2458            }
2459        }
2460
2461        #[cfg(test)]
2462        self.snapshot.check_invariants(false);
2463    }
2464
2465    fn reload_repositories(&mut self, dot_git_dirs_to_reload: &HashSet<PathBuf>, fs: &dyn Fs) {
2466        let scan_id = self.snapshot.scan_id;
2467        for dot_git_dir in dot_git_dirs_to_reload {
2468            // If there is already a repository for this .git directory, reload
2469            // the status for all of its files.
2470            let repository = self
2471                .snapshot
2472                .git_repositories
2473                .iter()
2474                .find_map(|(entry_id, repo)| {
2475                    (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2476                });
2477            match repository {
2478                None => {
2479                    self.build_git_repository(Arc::from(dot_git_dir.as_path()), fs);
2480                }
2481                Some((entry_id, repository)) => {
2482                    if repository.git_dir_scan_id == scan_id {
2483                        continue;
2484                    }
2485                    let Some(work_dir) = self
2486                        .snapshot
2487                        .entry_for_id(entry_id)
2488                        .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2489                    else {
2490                        continue;
2491                    };
2492
2493                    log::info!("reload git repository {dot_git_dir:?}");
2494                    let repository = repository.repo_ptr.lock();
2495                    let branch = repository.branch_name();
2496                    repository.reload_index();
2497
2498                    self.snapshot
2499                        .git_repositories
2500                        .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2501                    self.snapshot
2502                        .snapshot
2503                        .repository_entries
2504                        .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2505
2506                    self.update_git_statuses(&work_dir, &*repository);
2507                }
2508            }
2509        }
2510
2511        // Remove any git repositories whose .git entry no longer exists.
2512        let snapshot = &mut self.snapshot;
2513        let mut ids_to_preserve = HashSet::default();
2514        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
2515            let exists_in_snapshot = snapshot
2516                .entry_for_id(work_directory_id)
2517                .map_or(false, |entry| {
2518                    snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2519                });
2520            if exists_in_snapshot {
2521                ids_to_preserve.insert(work_directory_id);
2522            } else {
2523                let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
2524                let git_dir_excluded = snapshot.is_path_excluded(entry.git_dir_path.to_path_buf());
2525                if git_dir_excluded
2526                    && !matches!(smol::block_on(fs.metadata(&git_dir_abs_path)), Ok(None))
2527                {
2528                    ids_to_preserve.insert(work_directory_id);
2529                }
2530            }
2531        }
2532        snapshot
2533            .git_repositories
2534            .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
2535        snapshot
2536            .repository_entries
2537            .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
2538    }
2539
2540    fn build_git_repository(
2541        &mut self,
2542        dot_git_path: Arc<Path>,
2543        fs: &dyn Fs,
2544    ) -> Option<(
2545        RepositoryWorkDirectory,
2546        Arc<Mutex<dyn GitRepository>>,
2547        TreeMap<RepoPath, GitFileStatus>,
2548    )> {
2549        log::info!("build git repository {:?}", dot_git_path);
2550
2551        let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2552
2553        // Guard against repositories inside the repository metadata
2554        if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2555            return None;
2556        };
2557
2558        let work_dir_id = self
2559            .snapshot
2560            .entry_for_path(work_dir_path.clone())
2561            .map(|entry| entry.id)?;
2562
2563        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2564            return None;
2565        }
2566
2567        let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2568        let repository = fs.open_repo(abs_path.as_path())?;
2569        let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2570
2571        let repo_lock = repository.lock();
2572        self.snapshot.repository_entries.insert(
2573            work_directory.clone(),
2574            RepositoryEntry {
2575                work_directory: work_dir_id.into(),
2576                branch: repo_lock.branch_name().map(Into::into),
2577            },
2578        );
2579
2580        let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2581        drop(repo_lock);
2582
2583        self.snapshot.git_repositories.insert(
2584            work_dir_id,
2585            LocalRepositoryEntry {
2586                git_dir_scan_id: 0,
2587                repo_ptr: repository.clone(),
2588                git_dir_path: dot_git_path.clone(),
2589            },
2590        );
2591
2592        Some((work_directory, repository, staged_statuses))
2593    }
2594
2595    fn update_git_statuses(
2596        &mut self,
2597        work_directory: &RepositoryWorkDirectory,
2598        repo: &dyn GitRepository,
2599    ) -> TreeMap<RepoPath, GitFileStatus> {
2600        let staged_statuses = repo.staged_statuses(Path::new(""));
2601
2602        let mut changes = vec![];
2603        let mut edits = vec![];
2604
2605        for mut entry in self
2606            .snapshot
2607            .descendent_entries(false, false, &work_directory.0)
2608            .cloned()
2609        {
2610            let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2611                continue;
2612            };
2613            let repo_path = RepoPath(repo_path.to_path_buf());
2614            let git_file_status = combine_git_statuses(
2615                staged_statuses.get(&repo_path).copied(),
2616                repo.unstaged_status(&repo_path, entry.mtime),
2617            );
2618            if entry.git_status != git_file_status {
2619                entry.git_status = git_file_status;
2620                changes.push(entry.path.clone());
2621                edits.push(Edit::Insert(entry));
2622            }
2623        }
2624
2625        self.snapshot.entries_by_path.edit(edits, &());
2626        util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2627        staged_statuses
2628    }
2629}
2630
2631async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2632    let contents = fs.load(abs_path).await?;
2633    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2634    let mut builder = GitignoreBuilder::new(parent);
2635    for line in contents.lines() {
2636        builder.add_line(Some(abs_path.into()), line)?;
2637    }
2638    Ok(builder.build()?)
2639}
2640
2641impl WorktreeId {
2642    pub fn from_usize(handle_id: usize) -> Self {
2643        Self(handle_id)
2644    }
2645
2646    pub(crate) fn from_proto(id: u64) -> Self {
2647        Self(id as usize)
2648    }
2649
2650    pub fn to_proto(&self) -> u64 {
2651        self.0 as u64
2652    }
2653
2654    pub fn to_usize(&self) -> usize {
2655        self.0
2656    }
2657}
2658
2659impl fmt::Display for WorktreeId {
2660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2661        self.0.fmt(f)
2662    }
2663}
2664
2665impl Deref for Worktree {
2666    type Target = Snapshot;
2667
2668    fn deref(&self) -> &Self::Target {
2669        match self {
2670            Worktree::Local(worktree) => &worktree.snapshot,
2671            Worktree::Remote(worktree) => &worktree.snapshot,
2672        }
2673    }
2674}
2675
2676impl Deref for LocalWorktree {
2677    type Target = LocalSnapshot;
2678
2679    fn deref(&self) -> &Self::Target {
2680        &self.snapshot
2681    }
2682}
2683
2684impl Deref for RemoteWorktree {
2685    type Target = Snapshot;
2686
2687    fn deref(&self) -> &Self::Target {
2688        &self.snapshot
2689    }
2690}
2691
2692impl fmt::Debug for LocalWorktree {
2693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2694        self.snapshot.fmt(f)
2695    }
2696}
2697
2698impl fmt::Debug for Snapshot {
2699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2700        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2701        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2702
2703        impl<'a> fmt::Debug for EntriesByPath<'a> {
2704            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2705                f.debug_map()
2706                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2707                    .finish()
2708            }
2709        }
2710
2711        impl<'a> fmt::Debug for EntriesById<'a> {
2712            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2713                f.debug_list().entries(self.0.iter()).finish()
2714            }
2715        }
2716
2717        f.debug_struct("Snapshot")
2718            .field("id", &self.id)
2719            .field("root_name", &self.root_name)
2720            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2721            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2722            .finish()
2723    }
2724}
2725
2726#[derive(Clone, PartialEq)]
2727pub struct File {
2728    pub worktree: ModelHandle<Worktree>,
2729    pub path: Arc<Path>,
2730    pub mtime: SystemTime,
2731    pub(crate) entry_id: Option<ProjectEntryId>,
2732    pub(crate) is_local: bool,
2733    pub(crate) is_deleted: bool,
2734}
2735
2736impl language::File for File {
2737    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2738        if self.is_local {
2739            Some(self)
2740        } else {
2741            None
2742        }
2743    }
2744
2745    fn mtime(&self) -> SystemTime {
2746        self.mtime
2747    }
2748
2749    fn path(&self) -> &Arc<Path> {
2750        &self.path
2751    }
2752
2753    fn full_path(&self, cx: &AppContext) -> PathBuf {
2754        let mut full_path = PathBuf::new();
2755        let worktree = self.worktree.read(cx);
2756
2757        if worktree.is_visible() {
2758            full_path.push(worktree.root_name());
2759        } else {
2760            let path = worktree.abs_path();
2761
2762            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2763                full_path.push("~");
2764                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2765            } else {
2766                full_path.push(path)
2767            }
2768        }
2769
2770        if self.path.components().next().is_some() {
2771            full_path.push(&self.path);
2772        }
2773
2774        full_path
2775    }
2776
2777    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2778    /// of its worktree, then this method will return the name of the worktree itself.
2779    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2780        self.path
2781            .file_name()
2782            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2783    }
2784
2785    fn worktree_id(&self) -> usize {
2786        self.worktree.id()
2787    }
2788
2789    fn is_deleted(&self) -> bool {
2790        self.is_deleted
2791    }
2792
2793    fn as_any(&self) -> &dyn Any {
2794        self
2795    }
2796
2797    fn to_proto(&self) -> rpc::proto::File {
2798        rpc::proto::File {
2799            worktree_id: self.worktree.id() as u64,
2800            entry_id: self.entry_id.map(|id| id.to_proto()),
2801            path: self.path.to_string_lossy().into(),
2802            mtime: Some(self.mtime.into()),
2803            is_deleted: self.is_deleted,
2804        }
2805    }
2806}
2807
2808impl language::LocalFile for File {
2809    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2810        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2811        if self.path.as_ref() == Path::new("") {
2812            worktree_path.to_path_buf()
2813        } else {
2814            worktree_path.join(&self.path)
2815        }
2816    }
2817
2818    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2819        let worktree = self.worktree.read(cx).as_local().unwrap();
2820        let abs_path = worktree.absolutize(&self.path);
2821        let fs = worktree.fs.clone();
2822        cx.background()
2823            .spawn(async move { fs.load(&abs_path).await })
2824    }
2825
2826    fn buffer_reloaded(
2827        &self,
2828        buffer_id: u64,
2829        version: &clock::Global,
2830        fingerprint: RopeFingerprint,
2831        line_ending: LineEnding,
2832        mtime: SystemTime,
2833        cx: &mut AppContext,
2834    ) {
2835        let worktree = self.worktree.read(cx).as_local().unwrap();
2836        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2837            worktree
2838                .client
2839                .send(proto::BufferReloaded {
2840                    project_id,
2841                    buffer_id,
2842                    version: serialize_version(version),
2843                    mtime: Some(mtime.into()),
2844                    fingerprint: serialize_fingerprint(fingerprint),
2845                    line_ending: serialize_line_ending(line_ending) as i32,
2846                })
2847                .log_err();
2848        }
2849    }
2850}
2851
2852impl File {
2853    pub fn for_entry(entry: Entry, worktree: ModelHandle<Worktree>) -> Arc<Self> {
2854        Arc::new(Self {
2855            worktree,
2856            path: entry.path.clone(),
2857            mtime: entry.mtime,
2858            entry_id: Some(entry.id),
2859            is_local: true,
2860            is_deleted: false,
2861        })
2862    }
2863
2864    pub fn from_proto(
2865        proto: rpc::proto::File,
2866        worktree: ModelHandle<Worktree>,
2867        cx: &AppContext,
2868    ) -> Result<Self> {
2869        let worktree_id = worktree
2870            .read(cx)
2871            .as_remote()
2872            .ok_or_else(|| anyhow!("not remote"))?
2873            .id();
2874
2875        if worktree_id.to_proto() != proto.worktree_id {
2876            return Err(anyhow!("worktree id does not match file"));
2877        }
2878
2879        Ok(Self {
2880            worktree,
2881            path: Path::new(&proto.path).into(),
2882            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2883            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
2884            is_local: false,
2885            is_deleted: proto.is_deleted,
2886        })
2887    }
2888
2889    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2890        file.and_then(|f| f.as_any().downcast_ref())
2891    }
2892
2893    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2894        self.worktree.read(cx).id()
2895    }
2896
2897    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2898        if self.is_deleted {
2899            None
2900        } else {
2901            self.entry_id
2902        }
2903    }
2904}
2905
2906#[derive(Clone, Debug, PartialEq, Eq)]
2907pub struct Entry {
2908    pub id: ProjectEntryId,
2909    pub kind: EntryKind,
2910    pub path: Arc<Path>,
2911    pub inode: u64,
2912    pub mtime: SystemTime,
2913    pub is_symlink: bool,
2914
2915    /// Whether this entry is ignored by Git.
2916    ///
2917    /// We only scan ignored entries once the directory is expanded and
2918    /// exclude them from searches.
2919    pub is_ignored: bool,
2920
2921    /// Whether this entry's canonical path is outside of the worktree.
2922    /// This means the entry is only accessible from the worktree root via a
2923    /// symlink.
2924    ///
2925    /// We only scan entries outside of the worktree once the symlinked
2926    /// directory is expanded. External entries are treated like gitignored
2927    /// entries in that they are not included in searches.
2928    pub is_external: bool,
2929    pub git_status: Option<GitFileStatus>,
2930}
2931
2932#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2933pub enum EntryKind {
2934    UnloadedDir,
2935    PendingDir,
2936    Dir,
2937    File(CharBag),
2938}
2939
2940#[derive(Clone, Copy, Debug, PartialEq)]
2941pub enum PathChange {
2942    /// A filesystem entry was was created.
2943    Added,
2944    /// A filesystem entry was removed.
2945    Removed,
2946    /// A filesystem entry was updated.
2947    Updated,
2948    /// A filesystem entry was either updated or added. We don't know
2949    /// whether or not it already existed, because the path had not
2950    /// been loaded before the event.
2951    AddedOrUpdated,
2952    /// A filesystem entry was found during the initial scan of the worktree.
2953    Loaded,
2954}
2955
2956pub struct GitRepositoryChange {
2957    /// The previous state of the repository, if it already existed.
2958    pub old_repository: Option<RepositoryEntry>,
2959}
2960
2961pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2962pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2963
2964impl Entry {
2965    fn new(
2966        path: Arc<Path>,
2967        metadata: &fs::Metadata,
2968        next_entry_id: &AtomicUsize,
2969        root_char_bag: CharBag,
2970    ) -> Self {
2971        Self {
2972            id: ProjectEntryId::new(next_entry_id),
2973            kind: if metadata.is_dir {
2974                EntryKind::PendingDir
2975            } else {
2976                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2977            },
2978            path,
2979            inode: metadata.inode,
2980            mtime: metadata.mtime,
2981            is_symlink: metadata.is_symlink,
2982            is_ignored: false,
2983            is_external: false,
2984            git_status: None,
2985        }
2986    }
2987
2988    pub fn is_dir(&self) -> bool {
2989        self.kind.is_dir()
2990    }
2991
2992    pub fn is_file(&self) -> bool {
2993        self.kind.is_file()
2994    }
2995
2996    pub fn git_status(&self) -> Option<GitFileStatus> {
2997        self.git_status
2998    }
2999}
3000
3001impl EntryKind {
3002    pub fn is_dir(&self) -> bool {
3003        matches!(
3004            self,
3005            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3006        )
3007    }
3008
3009    pub fn is_unloaded(&self) -> bool {
3010        matches!(self, EntryKind::UnloadedDir)
3011    }
3012
3013    pub fn is_file(&self) -> bool {
3014        matches!(self, EntryKind::File(_))
3015    }
3016}
3017
3018impl sum_tree::Item for Entry {
3019    type Summary = EntrySummary;
3020
3021    fn summary(&self) -> Self::Summary {
3022        let non_ignored_count = if self.is_ignored || self.is_external {
3023            0
3024        } else {
3025            1
3026        };
3027        let file_count;
3028        let non_ignored_file_count;
3029        if self.is_file() {
3030            file_count = 1;
3031            non_ignored_file_count = non_ignored_count;
3032        } else {
3033            file_count = 0;
3034            non_ignored_file_count = 0;
3035        }
3036
3037        let mut statuses = GitStatuses::default();
3038        match self.git_status {
3039            Some(status) => match status {
3040                GitFileStatus::Added => statuses.added = 1,
3041                GitFileStatus::Modified => statuses.modified = 1,
3042                GitFileStatus::Conflict => statuses.conflict = 1,
3043            },
3044            None => {}
3045        }
3046
3047        EntrySummary {
3048            max_path: self.path.clone(),
3049            count: 1,
3050            non_ignored_count,
3051            file_count,
3052            non_ignored_file_count,
3053            statuses,
3054        }
3055    }
3056}
3057
3058impl sum_tree::KeyedItem for Entry {
3059    type Key = PathKey;
3060
3061    fn key(&self) -> Self::Key {
3062        PathKey(self.path.clone())
3063    }
3064}
3065
3066#[derive(Clone, Debug)]
3067pub struct EntrySummary {
3068    max_path: Arc<Path>,
3069    count: usize,
3070    non_ignored_count: usize,
3071    file_count: usize,
3072    non_ignored_file_count: usize,
3073    statuses: GitStatuses,
3074}
3075
3076impl Default for EntrySummary {
3077    fn default() -> Self {
3078        Self {
3079            max_path: Arc::from(Path::new("")),
3080            count: 0,
3081            non_ignored_count: 0,
3082            file_count: 0,
3083            non_ignored_file_count: 0,
3084            statuses: Default::default(),
3085        }
3086    }
3087}
3088
3089impl sum_tree::Summary for EntrySummary {
3090    type Context = ();
3091
3092    fn add_summary(&mut self, rhs: &Self, _: &()) {
3093        self.max_path = rhs.max_path.clone();
3094        self.count += rhs.count;
3095        self.non_ignored_count += rhs.non_ignored_count;
3096        self.file_count += rhs.file_count;
3097        self.non_ignored_file_count += rhs.non_ignored_file_count;
3098        self.statuses += rhs.statuses;
3099    }
3100}
3101
3102#[derive(Clone, Debug)]
3103struct PathEntry {
3104    id: ProjectEntryId,
3105    path: Arc<Path>,
3106    is_ignored: bool,
3107    scan_id: usize,
3108}
3109
3110impl sum_tree::Item for PathEntry {
3111    type Summary = PathEntrySummary;
3112
3113    fn summary(&self) -> Self::Summary {
3114        PathEntrySummary { max_id: self.id }
3115    }
3116}
3117
3118impl sum_tree::KeyedItem for PathEntry {
3119    type Key = ProjectEntryId;
3120
3121    fn key(&self) -> Self::Key {
3122        self.id
3123    }
3124}
3125
3126#[derive(Clone, Debug, Default)]
3127struct PathEntrySummary {
3128    max_id: ProjectEntryId,
3129}
3130
3131impl sum_tree::Summary for PathEntrySummary {
3132    type Context = ();
3133
3134    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3135        self.max_id = summary.max_id;
3136    }
3137}
3138
3139impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3140    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3141        *self = summary.max_id;
3142    }
3143}
3144
3145#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3146pub struct PathKey(Arc<Path>);
3147
3148impl Default for PathKey {
3149    fn default() -> Self {
3150        Self(Path::new("").into())
3151    }
3152}
3153
3154impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3155    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3156        self.0 = summary.max_path.clone();
3157    }
3158}
3159
3160struct BackgroundScanner {
3161    state: Mutex<BackgroundScannerState>,
3162    fs: Arc<dyn Fs>,
3163    status_updates_tx: UnboundedSender<ScanState>,
3164    executor: Arc<executor::Background>,
3165    scan_requests_rx: channel::Receiver<ScanRequest>,
3166    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3167    next_entry_id: Arc<AtomicUsize>,
3168    phase: BackgroundScannerPhase,
3169}
3170
3171#[derive(PartialEq)]
3172enum BackgroundScannerPhase {
3173    InitialScan,
3174    EventsReceivedDuringInitialScan,
3175    Events,
3176}
3177
3178impl BackgroundScanner {
3179    fn new(
3180        snapshot: LocalSnapshot,
3181        next_entry_id: Arc<AtomicUsize>,
3182        fs: Arc<dyn Fs>,
3183        status_updates_tx: UnboundedSender<ScanState>,
3184        executor: Arc<executor::Background>,
3185        scan_requests_rx: channel::Receiver<ScanRequest>,
3186        path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3187    ) -> Self {
3188        Self {
3189            fs,
3190            status_updates_tx,
3191            executor,
3192            scan_requests_rx,
3193            path_prefixes_to_scan_rx,
3194            next_entry_id,
3195            state: Mutex::new(BackgroundScannerState {
3196                prev_snapshot: snapshot.snapshot.clone(),
3197                snapshot,
3198                scanned_dirs: Default::default(),
3199                path_prefixes_to_scan: Default::default(),
3200                paths_to_scan: Default::default(),
3201                removed_entry_ids: Default::default(),
3202                changed_paths: Default::default(),
3203            }),
3204            phase: BackgroundScannerPhase::InitialScan,
3205        }
3206    }
3207
3208    async fn run(
3209        &mut self,
3210        mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
3211    ) {
3212        use futures::FutureExt as _;
3213
3214        // Populate ignores above the root.
3215        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3216        for (index, ancestor) in root_abs_path.ancestors().enumerate() {
3217            if index != 0 {
3218                if let Ok(ignore) =
3219                    build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3220                {
3221                    self.state
3222                        .lock()
3223                        .snapshot
3224                        .ignores_by_parent_abs_path
3225                        .insert(ancestor.into(), (ignore.into(), false));
3226                }
3227            }
3228            if ancestor.join(&*DOT_GIT).is_dir() {
3229                // Reached root of git repository.
3230                break;
3231            }
3232        }
3233
3234        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3235        {
3236            let mut state = self.state.lock();
3237            state.snapshot.scan_id += 1;
3238            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3239                let ignore_stack = state
3240                    .snapshot
3241                    .ignore_stack_for_abs_path(&root_abs_path, true);
3242                if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3243                    root_entry.is_ignored = true;
3244                    state.insert_entry(root_entry.clone(), self.fs.as_ref());
3245                }
3246                state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3247            }
3248        };
3249
3250        // Perform an initial scan of the directory.
3251        drop(scan_job_tx);
3252        self.scan_dirs(true, scan_job_rx).await;
3253        {
3254            let mut state = self.state.lock();
3255            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3256        }
3257
3258        self.send_status_update(false, None);
3259
3260        // Process any any FS events that occurred while performing the initial scan.
3261        // For these events, update events cannot be as precise, because we didn't
3262        // have the previous state loaded yet.
3263        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3264        if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3265            let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3266            while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3267                paths.extend(more_events.into_iter().map(|e| e.path));
3268            }
3269            self.process_events(paths).await;
3270        }
3271
3272        // Continue processing events until the worktree is dropped.
3273        self.phase = BackgroundScannerPhase::Events;
3274        loop {
3275            select_biased! {
3276                // Process any path refresh requests from the worktree. Prioritize
3277                // these before handling changes reported by the filesystem.
3278                request = self.scan_requests_rx.recv().fuse() => {
3279                    let Ok(request) = request else { break };
3280                    if !self.process_scan_request(request, false).await {
3281                        return;
3282                    }
3283                }
3284
3285                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3286                    let Ok(path_prefix) = path_prefix else { break };
3287                    log::trace!("adding path prefix {:?}", path_prefix);
3288
3289                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3290                    if did_scan {
3291                        let abs_path =
3292                        {
3293                            let mut state = self.state.lock();
3294                            state.path_prefixes_to_scan.insert(path_prefix.clone());
3295                            state.snapshot.abs_path.join(&path_prefix)
3296                        };
3297
3298                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3299                            self.process_events(vec![abs_path]).await;
3300                        }
3301                    }
3302                }
3303
3304                events = fs_events_rx.next().fuse() => {
3305                    let Some(events) = events else { break };
3306                    let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3307                    while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3308                        paths.extend(more_events.into_iter().map(|e| e.path));
3309                    }
3310                    self.process_events(paths.clone()).await;
3311                }
3312            }
3313        }
3314    }
3315
3316    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3317        log::debug!("rescanning paths {:?}", request.relative_paths);
3318
3319        request.relative_paths.sort_unstable();
3320        self.forcibly_load_paths(&request.relative_paths).await;
3321
3322        let root_path = self.state.lock().snapshot.abs_path.clone();
3323        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3324            Ok(path) => path,
3325            Err(err) => {
3326                log::error!("failed to canonicalize root path: {}", err);
3327                return false;
3328            }
3329        };
3330        let abs_paths = request
3331            .relative_paths
3332            .iter()
3333            .map(|path| {
3334                if path.file_name().is_some() {
3335                    root_canonical_path.join(path)
3336                } else {
3337                    root_canonical_path.clone()
3338                }
3339            })
3340            .collect::<Vec<_>>();
3341
3342        self.reload_entries_for_paths(
3343            root_path,
3344            root_canonical_path,
3345            &request.relative_paths,
3346            abs_paths,
3347            None,
3348        )
3349        .await;
3350        self.send_status_update(scanning, Some(request.done))
3351    }
3352
3353    async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3354        let root_path = self.state.lock().snapshot.abs_path.clone();
3355        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3356            Ok(path) => path,
3357            Err(err) => {
3358                log::error!("failed to canonicalize root path: {}", err);
3359                return;
3360            }
3361        };
3362
3363        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3364        let mut dot_git_paths_to_reload = HashSet::default();
3365        abs_paths.sort_unstable();
3366        abs_paths.dedup_by(|a, b| a.starts_with(&b));
3367        abs_paths.retain(|abs_path| {
3368            let snapshot = &self.state.lock().snapshot;
3369            {
3370                let mut is_git_related = false;
3371                if let Some(dot_git_dir) = abs_path
3372                    .ancestors()
3373                    .find(|ancestor| ancestor.file_name() == Some(&*DOT_GIT))
3374                {
3375                    let dot_git_path = dot_git_dir
3376                        .strip_prefix(&root_canonical_path)
3377                        .ok()
3378                        .map(|path| path.to_path_buf())
3379                        .unwrap_or_else(|| dot_git_dir.to_path_buf());
3380                    dot_git_paths_to_reload.insert(dot_git_path.to_path_buf());
3381                    is_git_related = true;
3382                }
3383
3384                let relative_path: Arc<Path> =
3385                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3386                        path.into()
3387                    } else {
3388                        log::error!(
3389                        "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3390                    );
3391                        return false;
3392                    };
3393                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3394                    snapshot
3395                        .entry_for_path(parent)
3396                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
3397                });
3398                if !parent_dir_is_loaded {
3399                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3400                    return false;
3401                }
3402
3403                if snapshot.is_path_excluded(relative_path.to_path_buf()) {
3404                    if !is_git_related {
3405                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
3406                    }
3407                    return false;
3408                }
3409
3410                relative_paths.push(relative_path);
3411                true
3412            }
3413        });
3414
3415        if dot_git_paths_to_reload.is_empty() && relative_paths.is_empty() {
3416            return;
3417        }
3418
3419        if !relative_paths.is_empty() {
3420            log::debug!("received fs events {:?}", relative_paths);
3421
3422            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3423            self.reload_entries_for_paths(
3424                root_path,
3425                root_canonical_path,
3426                &relative_paths,
3427                abs_paths,
3428                Some(scan_job_tx.clone()),
3429            )
3430            .await;
3431            drop(scan_job_tx);
3432            self.scan_dirs(false, scan_job_rx).await;
3433
3434            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3435            self.update_ignore_statuses(scan_job_tx).await;
3436            self.scan_dirs(false, scan_job_rx).await;
3437        }
3438
3439        {
3440            let mut state = self.state.lock();
3441            if !dot_git_paths_to_reload.is_empty() {
3442                if relative_paths.is_empty() {
3443                    state.snapshot.scan_id += 1;
3444                }
3445                log::debug!("reloading repositories: {dot_git_paths_to_reload:?}");
3446                state.reload_repositories(&dot_git_paths_to_reload, self.fs.as_ref());
3447            }
3448            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3449            for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3450                state.scanned_dirs.remove(&entry_id);
3451            }
3452        }
3453
3454        self.send_status_update(false, None);
3455    }
3456
3457    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3458        let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3459        {
3460            let mut state = self.state.lock();
3461            let root_path = state.snapshot.abs_path.clone();
3462            for path in paths {
3463                for ancestor in path.ancestors() {
3464                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3465                        if entry.kind == EntryKind::UnloadedDir {
3466                            let abs_path = root_path.join(ancestor);
3467                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3468                            state.paths_to_scan.insert(path.clone());
3469                            break;
3470                        }
3471                    }
3472                }
3473            }
3474            drop(scan_job_tx);
3475        }
3476        while let Some(job) = scan_job_rx.next().await {
3477            self.scan_dir(&job).await.log_err();
3478        }
3479
3480        mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3481    }
3482
3483    async fn scan_dirs(
3484        &self,
3485        enable_progress_updates: bool,
3486        scan_jobs_rx: channel::Receiver<ScanJob>,
3487    ) {
3488        use futures::FutureExt as _;
3489
3490        if self
3491            .status_updates_tx
3492            .unbounded_send(ScanState::Started)
3493            .is_err()
3494        {
3495            return;
3496        }
3497
3498        let progress_update_count = AtomicUsize::new(0);
3499        self.executor
3500            .scoped(|scope| {
3501                for _ in 0..self.executor.num_cpus() {
3502                    scope.spawn(async {
3503                        let mut last_progress_update_count = 0;
3504                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3505                        futures::pin_mut!(progress_update_timer);
3506
3507                        loop {
3508                            select_biased! {
3509                                // Process any path refresh requests before moving on to process
3510                                // the scan queue, so that user operations are prioritized.
3511                                request = self.scan_requests_rx.recv().fuse() => {
3512                                    let Ok(request) = request else { break };
3513                                    if !self.process_scan_request(request, true).await {
3514                                        return;
3515                                    }
3516                                }
3517
3518                                // Send periodic progress updates to the worktree. Use an atomic counter
3519                                // to ensure that only one of the workers sends a progress update after
3520                                // the update interval elapses.
3521                                _ = progress_update_timer => {
3522                                    match progress_update_count.compare_exchange(
3523                                        last_progress_update_count,
3524                                        last_progress_update_count + 1,
3525                                        SeqCst,
3526                                        SeqCst
3527                                    ) {
3528                                        Ok(_) => {
3529                                            last_progress_update_count += 1;
3530                                            self.send_status_update(true, None);
3531                                        }
3532                                        Err(count) => {
3533                                            last_progress_update_count = count;
3534                                        }
3535                                    }
3536                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3537                                }
3538
3539                                // Recursively load directories from the file system.
3540                                job = scan_jobs_rx.recv().fuse() => {
3541                                    let Ok(job) = job else { break };
3542                                    if let Err(err) = self.scan_dir(&job).await {
3543                                        if job.path.as_ref() != Path::new("") {
3544                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3545                                        }
3546                                    }
3547                                }
3548                            }
3549                        }
3550                    })
3551                }
3552            })
3553            .await;
3554    }
3555
3556    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3557        let mut state = self.state.lock();
3558        if state.changed_paths.is_empty() && scanning {
3559            return true;
3560        }
3561
3562        let new_snapshot = state.snapshot.clone();
3563        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3564        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3565        state.changed_paths.clear();
3566
3567        self.status_updates_tx
3568            .unbounded_send(ScanState::Updated {
3569                snapshot: new_snapshot,
3570                changes,
3571                scanning,
3572                barrier,
3573            })
3574            .is_ok()
3575    }
3576
3577    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3578        let root_abs_path;
3579        let mut ignore_stack;
3580        let mut new_ignore;
3581        let root_char_bag;
3582        let next_entry_id;
3583        {
3584            let state = self.state.lock();
3585            let snapshot = &state.snapshot;
3586            root_abs_path = snapshot.abs_path().clone();
3587            if snapshot.is_path_excluded(job.path.to_path_buf()) {
3588                log::error!("skipping excluded directory {:?}", job.path);
3589                return Ok(());
3590            }
3591            log::debug!("scanning directory {:?}", job.path);
3592            ignore_stack = job.ignore_stack.clone();
3593            new_ignore = None;
3594            root_char_bag = snapshot.root_char_bag;
3595            next_entry_id = self.next_entry_id.clone();
3596            drop(state);
3597        }
3598
3599        let mut dotgit_path = None;
3600        let mut root_canonical_path = None;
3601        let mut new_entries: Vec<Entry> = Vec::new();
3602        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3603        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3604        while let Some(child_abs_path) = child_paths.next().await {
3605            let child_abs_path: Arc<Path> = match child_abs_path {
3606                Ok(child_abs_path) => child_abs_path.into(),
3607                Err(error) => {
3608                    log::error!("error processing entry {:?}", error);
3609                    continue;
3610                }
3611            };
3612            let child_name = child_abs_path.file_name().unwrap();
3613            let child_path: Arc<Path> = job.path.join(child_name).into();
3614            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3615            if child_name == *GITIGNORE {
3616                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3617                    Ok(ignore) => {
3618                        let ignore = Arc::new(ignore);
3619                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3620                        new_ignore = Some(ignore);
3621                    }
3622                    Err(error) => {
3623                        log::error!(
3624                            "error loading .gitignore file {:?} - {:?}",
3625                            child_name,
3626                            error
3627                        );
3628                    }
3629                }
3630
3631                // Update ignore status of any child entries we've already processed to reflect the
3632                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3633                // there should rarely be too numerous. Update the ignore stack associated with any
3634                // new jobs as well.
3635                let mut new_jobs = new_jobs.iter_mut();
3636                for entry in &mut new_entries {
3637                    let entry_abs_path = root_abs_path.join(&entry.path);
3638                    entry.is_ignored =
3639                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3640
3641                    if entry.is_dir() {
3642                        if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3643                            job.ignore_stack = if entry.is_ignored {
3644                                IgnoreStack::all()
3645                            } else {
3646                                ignore_stack.clone()
3647                            };
3648                        }
3649                    }
3650                }
3651            }
3652            // If we find a .git, we'll need to load the repository.
3653            else if child_name == *DOT_GIT {
3654                dotgit_path = Some(child_path.clone());
3655            }
3656
3657            {
3658                let mut state = self.state.lock();
3659                let relative_path = job.path.join(child_name);
3660                if state.snapshot.is_path_excluded(relative_path.clone()) {
3661                    log::debug!("skipping excluded child entry {relative_path:?}");
3662                    state.remove_path(&relative_path);
3663                    continue;
3664                }
3665                drop(state);
3666            }
3667
3668            let child_metadata = match self.fs.metadata(&child_abs_path).await {
3669                Ok(Some(metadata)) => metadata,
3670                Ok(None) => continue,
3671                Err(err) => {
3672                    log::error!("error processing {child_abs_path:?}: {err:?}");
3673                    continue;
3674                }
3675            };
3676
3677            let mut child_entry = Entry::new(
3678                child_path.clone(),
3679                &child_metadata,
3680                &next_entry_id,
3681                root_char_bag,
3682            );
3683
3684            if job.is_external {
3685                child_entry.is_external = true;
3686            } else if child_metadata.is_symlink {
3687                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3688                    Ok(path) => path,
3689                    Err(err) => {
3690                        log::error!(
3691                            "error reading target of symlink {:?}: {:?}",
3692                            child_abs_path,
3693                            err
3694                        );
3695                        continue;
3696                    }
3697                };
3698
3699                // lazily canonicalize the root path in order to determine if
3700                // symlinks point outside of the worktree.
3701                let root_canonical_path = match &root_canonical_path {
3702                    Some(path) => path,
3703                    None => match self.fs.canonicalize(&root_abs_path).await {
3704                        Ok(path) => root_canonical_path.insert(path),
3705                        Err(err) => {
3706                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3707                            continue;
3708                        }
3709                    },
3710                };
3711
3712                if !canonical_path.starts_with(root_canonical_path) {
3713                    child_entry.is_external = true;
3714                }
3715            }
3716
3717            if child_entry.is_dir() {
3718                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3719
3720                // Avoid recursing until crash in the case of a recursive symlink
3721                if !job.ancestor_inodes.contains(&child_entry.inode) {
3722                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3723                    ancestor_inodes.insert(child_entry.inode);
3724
3725                    new_jobs.push(Some(ScanJob {
3726                        abs_path: child_abs_path,
3727                        path: child_path,
3728                        is_external: child_entry.is_external,
3729                        ignore_stack: if child_entry.is_ignored {
3730                            IgnoreStack::all()
3731                        } else {
3732                            ignore_stack.clone()
3733                        },
3734                        ancestor_inodes,
3735                        scan_queue: job.scan_queue.clone(),
3736                        containing_repository: job.containing_repository.clone(),
3737                    }));
3738                } else {
3739                    new_jobs.push(None);
3740                }
3741            } else {
3742                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3743                if !child_entry.is_ignored {
3744                    if let Some((repository_dir, repository, staged_statuses)) =
3745                        &job.containing_repository
3746                    {
3747                        if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3748                            let repo_path = RepoPath(repo_path.into());
3749                            child_entry.git_status = combine_git_statuses(
3750                                staged_statuses.get(&repo_path).copied(),
3751                                repository
3752                                    .lock()
3753                                    .unstaged_status(&repo_path, child_entry.mtime),
3754                            );
3755                        }
3756                    }
3757                }
3758            }
3759
3760            new_entries.push(child_entry);
3761        }
3762
3763        let mut state = self.state.lock();
3764
3765        // Identify any subdirectories that should not be scanned.
3766        let mut job_ix = 0;
3767        for entry in &mut new_entries {
3768            state.reuse_entry_id(entry);
3769            if entry.is_dir() {
3770                if state.should_scan_directory(&entry) {
3771                    job_ix += 1;
3772                } else {
3773                    log::debug!("defer scanning directory {:?}", entry.path);
3774                    entry.kind = EntryKind::UnloadedDir;
3775                    new_jobs.remove(job_ix);
3776                }
3777            }
3778        }
3779
3780        state.populate_dir(&job.path, new_entries, new_ignore);
3781
3782        let repository =
3783            dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3784
3785        for new_job in new_jobs {
3786            if let Some(mut new_job) = new_job {
3787                if let Some(containing_repository) = &repository {
3788                    new_job.containing_repository = Some(containing_repository.clone());
3789                }
3790
3791                job.scan_queue
3792                    .try_send(new_job)
3793                    .expect("channel is unbounded");
3794            }
3795        }
3796
3797        Ok(())
3798    }
3799
3800    async fn reload_entries_for_paths(
3801        &self,
3802        root_abs_path: Arc<Path>,
3803        root_canonical_path: PathBuf,
3804        relative_paths: &[Arc<Path>],
3805        abs_paths: Vec<PathBuf>,
3806        scan_queue_tx: Option<Sender<ScanJob>>,
3807    ) {
3808        let metadata = futures::future::join_all(
3809            abs_paths
3810                .iter()
3811                .map(|abs_path| async move {
3812                    let metadata = self.fs.metadata(&abs_path).await?;
3813                    if let Some(metadata) = metadata {
3814                        let canonical_path = self.fs.canonicalize(&abs_path).await?;
3815                        anyhow::Ok(Some((metadata, canonical_path)))
3816                    } else {
3817                        Ok(None)
3818                    }
3819                })
3820                .collect::<Vec<_>>(),
3821        )
3822        .await;
3823
3824        let mut state = self.state.lock();
3825        let snapshot = &mut state.snapshot;
3826        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3827        let doing_recursive_update = scan_queue_tx.is_some();
3828        snapshot.scan_id += 1;
3829        if is_idle && !doing_recursive_update {
3830            snapshot.completed_scan_id = snapshot.scan_id;
3831        }
3832
3833        // Remove any entries for paths that no longer exist or are being recursively
3834        // refreshed. Do this before adding any new entries, so that renames can be
3835        // detected regardless of the order of the paths.
3836        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3837            if matches!(metadata, Ok(None)) || doing_recursive_update {
3838                log::trace!("remove path {:?}", path);
3839                state.remove_path(path);
3840            }
3841        }
3842
3843        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3844            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3845            match metadata {
3846                Ok(Some((metadata, canonical_path))) => {
3847                    let ignore_stack = state
3848                        .snapshot
3849                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3850
3851                    let mut fs_entry = Entry::new(
3852                        path.clone(),
3853                        metadata,
3854                        self.next_entry_id.as_ref(),
3855                        state.snapshot.root_char_bag,
3856                    );
3857                    let is_dir = fs_entry.is_dir();
3858                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3859                    fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3860
3861                    if !is_dir && !fs_entry.is_ignored {
3862                        if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(&path) {
3863                            if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
3864                                let repo_path = RepoPath(repo_path.into());
3865                                let repo = repo.repo_ptr.lock();
3866                                fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
3867                            }
3868                        }
3869                    }
3870
3871                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3872                        if state.should_scan_directory(&fs_entry) {
3873                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3874                        } else {
3875                            fs_entry.kind = EntryKind::UnloadedDir;
3876                        }
3877                    }
3878
3879                    state.insert_entry(fs_entry, self.fs.as_ref());
3880                }
3881                Ok(None) => {
3882                    self.remove_repo_path(&path, &mut state.snapshot);
3883                }
3884                Err(err) => {
3885                    // TODO - create a special 'error' entry in the entries tree to mark this
3886                    log::error!("error reading file {abs_path:?} on event: {err:#}");
3887                }
3888            }
3889        }
3890
3891        util::extend_sorted(
3892            &mut state.changed_paths,
3893            relative_paths.iter().cloned(),
3894            usize::MAX,
3895            Ord::cmp,
3896        );
3897    }
3898
3899    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3900        if !path
3901            .components()
3902            .any(|component| component.as_os_str() == *DOT_GIT)
3903        {
3904            if let Some(repository) = snapshot.repository_for_work_directory(path) {
3905                let entry = repository.work_directory.0;
3906                snapshot.git_repositories.remove(&entry);
3907                snapshot
3908                    .snapshot
3909                    .repository_entries
3910                    .remove(&RepositoryWorkDirectory(path.into()));
3911                return Some(());
3912            }
3913        }
3914
3915        // TODO statuses
3916        // Track when a .git is removed and iterate over the file system there
3917
3918        Some(())
3919    }
3920
3921    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3922        use futures::FutureExt as _;
3923
3924        let mut snapshot = self.state.lock().snapshot.clone();
3925        let mut ignores_to_update = Vec::new();
3926        let mut ignores_to_delete = Vec::new();
3927        let abs_path = snapshot.abs_path.clone();
3928        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3929            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3930                if *needs_update {
3931                    *needs_update = false;
3932                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3933                        ignores_to_update.push(parent_abs_path.clone());
3934                    }
3935                }
3936
3937                let ignore_path = parent_path.join(&*GITIGNORE);
3938                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3939                    ignores_to_delete.push(parent_abs_path.clone());
3940                }
3941            }
3942        }
3943
3944        for parent_abs_path in ignores_to_delete {
3945            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3946            self.state
3947                .lock()
3948                .snapshot
3949                .ignores_by_parent_abs_path
3950                .remove(&parent_abs_path);
3951        }
3952
3953        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3954        ignores_to_update.sort_unstable();
3955        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3956        while let Some(parent_abs_path) = ignores_to_update.next() {
3957            while ignores_to_update
3958                .peek()
3959                .map_or(false, |p| p.starts_with(&parent_abs_path))
3960            {
3961                ignores_to_update.next().unwrap();
3962            }
3963
3964            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3965            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3966                abs_path: parent_abs_path,
3967                ignore_stack,
3968                ignore_queue: ignore_queue_tx.clone(),
3969                scan_queue: scan_job_tx.clone(),
3970            }))
3971            .unwrap();
3972        }
3973        drop(ignore_queue_tx);
3974
3975        self.executor
3976            .scoped(|scope| {
3977                for _ in 0..self.executor.num_cpus() {
3978                    scope.spawn(async {
3979                        loop {
3980                            select_biased! {
3981                                // Process any path refresh requests before moving on to process
3982                                // the queue of ignore statuses.
3983                                request = self.scan_requests_rx.recv().fuse() => {
3984                                    let Ok(request) = request else { break };
3985                                    if !self.process_scan_request(request, true).await {
3986                                        return;
3987                                    }
3988                                }
3989
3990                                // Recursively process directories whose ignores have changed.
3991                                job = ignore_queue_rx.recv().fuse() => {
3992                                    let Ok(job) = job else { break };
3993                                    self.update_ignore_status(job, &snapshot).await;
3994                                }
3995                            }
3996                        }
3997                    });
3998                }
3999            })
4000            .await;
4001    }
4002
4003    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4004        log::trace!("update ignore status {:?}", job.abs_path);
4005
4006        let mut ignore_stack = job.ignore_stack;
4007        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4008            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4009        }
4010
4011        let mut entries_by_id_edits = Vec::new();
4012        let mut entries_by_path_edits = Vec::new();
4013        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
4014        for mut entry in snapshot.child_entries(path).cloned() {
4015            let was_ignored = entry.is_ignored;
4016            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4017            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4018            if entry.is_dir() {
4019                let child_ignore_stack = if entry.is_ignored {
4020                    IgnoreStack::all()
4021                } else {
4022                    ignore_stack.clone()
4023                };
4024
4025                // Scan any directories that were previously ignored and weren't previously scanned.
4026                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4027                    let state = self.state.lock();
4028                    if state.should_scan_directory(&entry) {
4029                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4030                    }
4031                }
4032
4033                job.ignore_queue
4034                    .send(UpdateIgnoreStatusJob {
4035                        abs_path: abs_path.clone(),
4036                        ignore_stack: child_ignore_stack,
4037                        ignore_queue: job.ignore_queue.clone(),
4038                        scan_queue: job.scan_queue.clone(),
4039                    })
4040                    .await
4041                    .unwrap();
4042            }
4043
4044            if entry.is_ignored != was_ignored {
4045                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4046                path_entry.scan_id = snapshot.scan_id;
4047                path_entry.is_ignored = entry.is_ignored;
4048                entries_by_id_edits.push(Edit::Insert(path_entry));
4049                entries_by_path_edits.push(Edit::Insert(entry));
4050            }
4051        }
4052
4053        let state = &mut self.state.lock();
4054        for edit in &entries_by_path_edits {
4055            if let Edit::Insert(entry) = edit {
4056                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4057                    state.changed_paths.insert(ix, entry.path.clone());
4058                }
4059            }
4060        }
4061
4062        state
4063            .snapshot
4064            .entries_by_path
4065            .edit(entries_by_path_edits, &());
4066        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4067    }
4068
4069    fn build_change_set(
4070        &self,
4071        old_snapshot: &Snapshot,
4072        new_snapshot: &Snapshot,
4073        event_paths: &[Arc<Path>],
4074    ) -> UpdatedEntriesSet {
4075        use BackgroundScannerPhase::*;
4076        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4077
4078        // Identify which paths have changed. Use the known set of changed
4079        // parent paths to optimize the search.
4080        let mut changes = Vec::new();
4081        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4082        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4083        let mut last_newly_loaded_dir_path = None;
4084        old_paths.next(&());
4085        new_paths.next(&());
4086        for path in event_paths {
4087            let path = PathKey(path.clone());
4088            if old_paths.item().map_or(false, |e| e.path < path.0) {
4089                old_paths.seek_forward(&path, Bias::Left, &());
4090            }
4091            if new_paths.item().map_or(false, |e| e.path < path.0) {
4092                new_paths.seek_forward(&path, Bias::Left, &());
4093            }
4094            loop {
4095                match (old_paths.item(), new_paths.item()) {
4096                    (Some(old_entry), Some(new_entry)) => {
4097                        if old_entry.path > path.0
4098                            && new_entry.path > path.0
4099                            && !old_entry.path.starts_with(&path.0)
4100                            && !new_entry.path.starts_with(&path.0)
4101                        {
4102                            break;
4103                        }
4104
4105                        match Ord::cmp(&old_entry.path, &new_entry.path) {
4106                            Ordering::Less => {
4107                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4108                                old_paths.next(&());
4109                            }
4110                            Ordering::Equal => {
4111                                if self.phase == EventsReceivedDuringInitialScan {
4112                                    if old_entry.id != new_entry.id {
4113                                        changes.push((
4114                                            old_entry.path.clone(),
4115                                            old_entry.id,
4116                                            Removed,
4117                                        ));
4118                                    }
4119                                    // If the worktree was not fully initialized when this event was generated,
4120                                    // we can't know whether this entry was added during the scan or whether
4121                                    // it was merely updated.
4122                                    changes.push((
4123                                        new_entry.path.clone(),
4124                                        new_entry.id,
4125                                        AddedOrUpdated,
4126                                    ));
4127                                } else if old_entry.id != new_entry.id {
4128                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4129                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
4130                                } else if old_entry != new_entry {
4131                                    if old_entry.kind.is_unloaded() {
4132                                        last_newly_loaded_dir_path = Some(&new_entry.path);
4133                                        changes.push((
4134                                            new_entry.path.clone(),
4135                                            new_entry.id,
4136                                            Loaded,
4137                                        ));
4138                                    } else {
4139                                        changes.push((
4140                                            new_entry.path.clone(),
4141                                            new_entry.id,
4142                                            Updated,
4143                                        ));
4144                                    }
4145                                }
4146                                old_paths.next(&());
4147                                new_paths.next(&());
4148                            }
4149                            Ordering::Greater => {
4150                                let is_newly_loaded = self.phase == InitialScan
4151                                    || last_newly_loaded_dir_path
4152                                        .as_ref()
4153                                        .map_or(false, |dir| new_entry.path.starts_with(&dir));
4154                                changes.push((
4155                                    new_entry.path.clone(),
4156                                    new_entry.id,
4157                                    if is_newly_loaded { Loaded } else { Added },
4158                                ));
4159                                new_paths.next(&());
4160                            }
4161                        }
4162                    }
4163                    (Some(old_entry), None) => {
4164                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
4165                        old_paths.next(&());
4166                    }
4167                    (None, Some(new_entry)) => {
4168                        let is_newly_loaded = self.phase == InitialScan
4169                            || last_newly_loaded_dir_path
4170                                .as_ref()
4171                                .map_or(false, |dir| new_entry.path.starts_with(&dir));
4172                        changes.push((
4173                            new_entry.path.clone(),
4174                            new_entry.id,
4175                            if is_newly_loaded { Loaded } else { Added },
4176                        ));
4177                        new_paths.next(&());
4178                    }
4179                    (None, None) => break,
4180                }
4181            }
4182        }
4183
4184        changes.into()
4185    }
4186
4187    async fn progress_timer(&self, running: bool) {
4188        if !running {
4189            return futures::future::pending().await;
4190        }
4191
4192        #[cfg(any(test, feature = "test-support"))]
4193        if self.fs.is_fake() {
4194            return self.executor.simulate_random_delay().await;
4195        }
4196
4197        smol::Timer::after(Duration::from_millis(100)).await;
4198    }
4199}
4200
4201fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4202    let mut result = root_char_bag;
4203    result.extend(
4204        path.to_string_lossy()
4205            .chars()
4206            .map(|c| c.to_ascii_lowercase()),
4207    );
4208    result
4209}
4210
4211struct ScanJob {
4212    abs_path: Arc<Path>,
4213    path: Arc<Path>,
4214    ignore_stack: Arc<IgnoreStack>,
4215    scan_queue: Sender<ScanJob>,
4216    ancestor_inodes: TreeSet<u64>,
4217    is_external: bool,
4218    containing_repository: Option<(
4219        RepositoryWorkDirectory,
4220        Arc<Mutex<dyn GitRepository>>,
4221        TreeMap<RepoPath, GitFileStatus>,
4222    )>,
4223}
4224
4225struct UpdateIgnoreStatusJob {
4226    abs_path: Arc<Path>,
4227    ignore_stack: Arc<IgnoreStack>,
4228    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4229    scan_queue: Sender<ScanJob>,
4230}
4231
4232pub trait WorktreeModelHandle {
4233    #[cfg(any(test, feature = "test-support"))]
4234    fn flush_fs_events<'a>(
4235        &self,
4236        cx: &'a gpui::TestAppContext,
4237    ) -> futures::future::LocalBoxFuture<'a, ()>;
4238}
4239
4240impl WorktreeModelHandle for ModelHandle<Worktree> {
4241    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4242    // occurred before the worktree was constructed. These events can cause the worktree to perform
4243    // extra directory scans, and emit extra scan-state notifications.
4244    //
4245    // This function mutates the worktree's directory and waits for those mutations to be picked up,
4246    // to ensure that all redundant FS events have already been processed.
4247    #[cfg(any(test, feature = "test-support"))]
4248    fn flush_fs_events<'a>(
4249        &self,
4250        cx: &'a gpui::TestAppContext,
4251    ) -> futures::future::LocalBoxFuture<'a, ()> {
4252        let filename = "fs-event-sentinel";
4253        let tree = self.clone();
4254        let (fs, root_path) = self.read_with(cx, |tree, _| {
4255            let tree = tree.as_local().unwrap();
4256            (tree.fs.clone(), tree.abs_path().clone())
4257        });
4258
4259        async move {
4260            fs.create_file(&root_path.join(filename), Default::default())
4261                .await
4262                .unwrap();
4263            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
4264                .await;
4265
4266            fs.remove_file(&root_path.join(filename), Default::default())
4267                .await
4268                .unwrap();
4269            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
4270                .await;
4271
4272            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4273                .await;
4274        }
4275        .boxed_local()
4276    }
4277}
4278
4279#[derive(Clone, Debug)]
4280struct TraversalProgress<'a> {
4281    max_path: &'a Path,
4282    count: usize,
4283    non_ignored_count: usize,
4284    file_count: usize,
4285    non_ignored_file_count: usize,
4286}
4287
4288impl<'a> TraversalProgress<'a> {
4289    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4290        match (include_ignored, include_dirs) {
4291            (true, true) => self.count,
4292            (true, false) => self.file_count,
4293            (false, true) => self.non_ignored_count,
4294            (false, false) => self.non_ignored_file_count,
4295        }
4296    }
4297}
4298
4299impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4300    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4301        self.max_path = summary.max_path.as_ref();
4302        self.count += summary.count;
4303        self.non_ignored_count += summary.non_ignored_count;
4304        self.file_count += summary.file_count;
4305        self.non_ignored_file_count += summary.non_ignored_file_count;
4306    }
4307}
4308
4309impl<'a> Default for TraversalProgress<'a> {
4310    fn default() -> Self {
4311        Self {
4312            max_path: Path::new(""),
4313            count: 0,
4314            non_ignored_count: 0,
4315            file_count: 0,
4316            non_ignored_file_count: 0,
4317        }
4318    }
4319}
4320
4321#[derive(Clone, Debug, Default, Copy)]
4322struct GitStatuses {
4323    added: usize,
4324    modified: usize,
4325    conflict: usize,
4326}
4327
4328impl AddAssign for GitStatuses {
4329    fn add_assign(&mut self, rhs: Self) {
4330        self.added += rhs.added;
4331        self.modified += rhs.modified;
4332        self.conflict += rhs.conflict;
4333    }
4334}
4335
4336impl Sub for GitStatuses {
4337    type Output = GitStatuses;
4338
4339    fn sub(self, rhs: Self) -> Self::Output {
4340        GitStatuses {
4341            added: self.added - rhs.added,
4342            modified: self.modified - rhs.modified,
4343            conflict: self.conflict - rhs.conflict,
4344        }
4345    }
4346}
4347
4348impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4349    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4350        *self += summary.statuses
4351    }
4352}
4353
4354pub struct Traversal<'a> {
4355    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4356    include_ignored: bool,
4357    include_dirs: bool,
4358}
4359
4360impl<'a> Traversal<'a> {
4361    pub fn advance(&mut self) -> bool {
4362        self.cursor.seek_forward(
4363            &TraversalTarget::Count {
4364                count: self.end_offset() + 1,
4365                include_dirs: self.include_dirs,
4366                include_ignored: self.include_ignored,
4367            },
4368            Bias::Left,
4369            &(),
4370        )
4371    }
4372
4373    pub fn advance_to_sibling(&mut self) -> bool {
4374        while let Some(entry) = self.cursor.item() {
4375            self.cursor.seek_forward(
4376                &TraversalTarget::PathSuccessor(&entry.path),
4377                Bias::Left,
4378                &(),
4379            );
4380            if let Some(entry) = self.cursor.item() {
4381                if (self.include_dirs || !entry.is_dir())
4382                    && (self.include_ignored || !entry.is_ignored)
4383                {
4384                    return true;
4385                }
4386            }
4387        }
4388        false
4389    }
4390
4391    pub fn entry(&self) -> Option<&'a Entry> {
4392        self.cursor.item()
4393    }
4394
4395    pub fn start_offset(&self) -> usize {
4396        self.cursor
4397            .start()
4398            .count(self.include_dirs, self.include_ignored)
4399    }
4400
4401    pub fn end_offset(&self) -> usize {
4402        self.cursor
4403            .end(&())
4404            .count(self.include_dirs, self.include_ignored)
4405    }
4406}
4407
4408impl<'a> Iterator for Traversal<'a> {
4409    type Item = &'a Entry;
4410
4411    fn next(&mut self) -> Option<Self::Item> {
4412        if let Some(item) = self.entry() {
4413            self.advance();
4414            Some(item)
4415        } else {
4416            None
4417        }
4418    }
4419}
4420
4421#[derive(Debug)]
4422enum TraversalTarget<'a> {
4423    Path(&'a Path),
4424    PathSuccessor(&'a Path),
4425    Count {
4426        count: usize,
4427        include_ignored: bool,
4428        include_dirs: bool,
4429    },
4430}
4431
4432impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4433    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4434        match self {
4435            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4436            TraversalTarget::PathSuccessor(path) => {
4437                if !cursor_location.max_path.starts_with(path) {
4438                    Ordering::Equal
4439                } else {
4440                    Ordering::Greater
4441                }
4442            }
4443            TraversalTarget::Count {
4444                count,
4445                include_dirs,
4446                include_ignored,
4447            } => Ord::cmp(
4448                count,
4449                &cursor_location.count(*include_dirs, *include_ignored),
4450            ),
4451        }
4452    }
4453}
4454
4455impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4456    for TraversalTarget<'b>
4457{
4458    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4459        self.cmp(&cursor_location.0, &())
4460    }
4461}
4462
4463struct ChildEntriesIter<'a> {
4464    parent_path: &'a Path,
4465    traversal: Traversal<'a>,
4466}
4467
4468impl<'a> Iterator for ChildEntriesIter<'a> {
4469    type Item = &'a Entry;
4470
4471    fn next(&mut self) -> Option<Self::Item> {
4472        if let Some(item) = self.traversal.entry() {
4473            if item.path.starts_with(&self.parent_path) {
4474                self.traversal.advance_to_sibling();
4475                return Some(item);
4476            }
4477        }
4478        None
4479    }
4480}
4481
4482pub struct DescendentEntriesIter<'a> {
4483    parent_path: &'a Path,
4484    traversal: Traversal<'a>,
4485}
4486
4487impl<'a> Iterator for DescendentEntriesIter<'a> {
4488    type Item = &'a Entry;
4489
4490    fn next(&mut self) -> Option<Self::Item> {
4491        if let Some(item) = self.traversal.entry() {
4492            if item.path.starts_with(&self.parent_path) {
4493                self.traversal.advance();
4494                return Some(item);
4495            }
4496        }
4497        None
4498    }
4499}
4500
4501impl<'a> From<&'a Entry> for proto::Entry {
4502    fn from(entry: &'a Entry) -> Self {
4503        Self {
4504            id: entry.id.to_proto(),
4505            is_dir: entry.is_dir(),
4506            path: entry.path.to_string_lossy().into(),
4507            inode: entry.inode,
4508            mtime: Some(entry.mtime.into()),
4509            is_symlink: entry.is_symlink,
4510            is_ignored: entry.is_ignored,
4511            is_external: entry.is_external,
4512            git_status: entry.git_status.map(git_status_to_proto),
4513        }
4514    }
4515}
4516
4517impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4518    type Error = anyhow::Error;
4519
4520    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4521        if let Some(mtime) = entry.mtime {
4522            let kind = if entry.is_dir {
4523                EntryKind::Dir
4524            } else {
4525                let mut char_bag = *root_char_bag;
4526                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4527                EntryKind::File(char_bag)
4528            };
4529            let path: Arc<Path> = PathBuf::from(entry.path).into();
4530            Ok(Entry {
4531                id: ProjectEntryId::from_proto(entry.id),
4532                kind,
4533                path,
4534                inode: entry.inode,
4535                mtime: mtime.into(),
4536                is_symlink: entry.is_symlink,
4537                is_ignored: entry.is_ignored,
4538                is_external: entry.is_external,
4539                git_status: git_status_from_proto(entry.git_status),
4540            })
4541        } else {
4542            Err(anyhow!(
4543                "missing mtime in remote worktree entry {:?}",
4544                entry.path
4545            ))
4546        }
4547    }
4548}
4549
4550fn combine_git_statuses(
4551    staged: Option<GitFileStatus>,
4552    unstaged: Option<GitFileStatus>,
4553) -> Option<GitFileStatus> {
4554    if let Some(staged) = staged {
4555        if let Some(unstaged) = unstaged {
4556            if unstaged != staged {
4557                Some(GitFileStatus::Modified)
4558            } else {
4559                Some(staged)
4560            }
4561        } else {
4562            Some(staged)
4563        }
4564    } else {
4565        unstaged
4566    }
4567}
4568
4569fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4570    git_status.and_then(|status| {
4571        proto::GitStatus::from_i32(status).map(|status| match status {
4572            proto::GitStatus::Added => GitFileStatus::Added,
4573            proto::GitStatus::Modified => GitFileStatus::Modified,
4574            proto::GitStatus::Conflict => GitFileStatus::Conflict,
4575        })
4576    })
4577}
4578
4579fn git_status_to_proto(status: GitFileStatus) -> i32 {
4580    match status {
4581        GitFileStatus::Added => proto::GitStatus::Added as i32,
4582        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4583        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4584    }
4585}