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