worktree.rs

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