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