worktree.rs

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