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