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