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 !ignore_stack.is_abs_path_ignored(parent_abs_path, 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 !ignore_stack.is_abs_path_ignored(abs_path, 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_excluded(&self, abs_path: &Path) -> bool {
2168        self.scan_exclude_files
2169            .iter()
2170            .any(|exclude_matcher| exclude_matcher.is_match(abs_path))
2171    }
2172}
2173
2174impl BackgroundScannerState {
2175    fn should_scan_directory(&self, entry: &Entry, entry_abs_path: &Path) -> bool {
2176        !entry.is_external && !self.snapshot.is_abs_path_excluded(entry_abs_path)
2177            || entry.path.file_name() == Some(&*DOT_GIT)
2178            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2179            || self
2180                .paths_to_scan
2181                .iter()
2182                .any(|p| p.starts_with(&entry.path))
2183            || self
2184                .path_prefixes_to_scan
2185                .iter()
2186                .any(|p| entry.path.starts_with(p))
2187    }
2188
2189    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2190        let path = entry.path.clone();
2191        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2192        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2193        let mut containing_repository = None;
2194        if !matches!(ignore_stack.as_ref(), &IgnoreStack::All)
2195            && !self.snapshot.is_abs_path_excluded(&abs_path)
2196        {
2197            if let Some((workdir_path, repo)) = self.snapshot.local_repo_for_path(&path) {
2198                if let Ok(repo_path) = path.strip_prefix(&workdir_path.0) {
2199                    containing_repository = Some((
2200                        workdir_path,
2201                        repo.repo_ptr.clone(),
2202                        repo.repo_ptr.lock().staged_statuses(repo_path),
2203                    ));
2204                }
2205            }
2206        }
2207        if !ancestor_inodes.contains(&entry.inode) {
2208            ancestor_inodes.insert(entry.inode);
2209            scan_job_tx
2210                .try_send(ScanJob {
2211                    abs_path,
2212                    path,
2213                    ignore_stack,
2214                    scan_queue: scan_job_tx.clone(),
2215                    ancestor_inodes,
2216                    is_external: entry.is_external,
2217                    containing_repository,
2218                })
2219                .unwrap();
2220        }
2221    }
2222
2223    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2224        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2225            entry.id = removed_entry_id;
2226        } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2227            entry.id = existing_entry.id;
2228        }
2229    }
2230
2231    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2232        self.reuse_entry_id(&mut entry);
2233        let entry = self.snapshot.insert_entry(entry, fs);
2234        if entry.path.file_name() == Some(&DOT_GIT) {
2235            self.build_git_repository(entry.path.clone(), fs);
2236        }
2237
2238        #[cfg(test)]
2239        self.snapshot.check_invariants(false);
2240
2241        entry
2242    }
2243
2244    fn populate_dir(
2245        &mut self,
2246        parent_path: &Arc<Path>,
2247        entries: impl IntoIterator<Item = Entry>,
2248        ignore: Option<Arc<Gitignore>>,
2249    ) {
2250        let mut parent_entry = if let Some(parent_entry) = self
2251            .snapshot
2252            .entries_by_path
2253            .get(&PathKey(parent_path.clone()), &())
2254        {
2255            parent_entry.clone()
2256        } else {
2257            log::warn!(
2258                "populating a directory {:?} that has been removed",
2259                parent_path
2260            );
2261            return;
2262        };
2263
2264        match parent_entry.kind {
2265            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2266            EntryKind::Dir => {}
2267            _ => return,
2268        }
2269
2270        if let Some(ignore) = ignore {
2271            let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2272            self.snapshot
2273                .ignores_by_parent_abs_path
2274                .insert(abs_parent_path, (ignore, false));
2275        }
2276
2277        let parent_entry_id = parent_entry.id;
2278        self.scanned_dirs.insert(parent_entry_id);
2279        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2280        let mut entries_by_id_edits = Vec::new();
2281        for entry in entries {
2282            entries_by_id_edits.push(Edit::Insert(PathEntry {
2283                id: entry.id,
2284                path: entry.path.clone(),
2285                is_ignored: entry.is_ignored,
2286                scan_id: self.snapshot.scan_id,
2287            }));
2288            entries_by_path_edits.push(Edit::Insert(entry));
2289        }
2290
2291        self.snapshot
2292            .entries_by_path
2293            .edit(entries_by_path_edits, &());
2294        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2295
2296        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2297            self.changed_paths.insert(ix, parent_path.clone());
2298        }
2299
2300        #[cfg(test)]
2301        self.snapshot.check_invariants(false);
2302    }
2303
2304    fn remove_path(&mut self, path: &Path) {
2305        let mut new_entries;
2306        let removed_entries;
2307        {
2308            let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2309            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2310            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2311            new_entries.append(cursor.suffix(&()), &());
2312        }
2313        self.snapshot.entries_by_path = new_entries;
2314
2315        let mut entries_by_id_edits = Vec::new();
2316        for entry in removed_entries.cursor::<()>() {
2317            let removed_entry_id = self
2318                .removed_entry_ids
2319                .entry(entry.inode)
2320                .or_insert(entry.id);
2321            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2322            entries_by_id_edits.push(Edit::Remove(entry.id));
2323        }
2324        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2325
2326        if path.file_name() == Some(&GITIGNORE) {
2327            let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2328            if let Some((_, needs_update)) = self
2329                .snapshot
2330                .ignores_by_parent_abs_path
2331                .get_mut(abs_parent_path.as_path())
2332            {
2333                *needs_update = true;
2334            }
2335        }
2336
2337        #[cfg(test)]
2338        self.snapshot.check_invariants(false);
2339    }
2340
2341    fn reload_repositories(&mut self, changed_paths: &[Arc<Path>], fs: &dyn Fs) {
2342        let scan_id = self.snapshot.scan_id;
2343
2344        // Find each of the .git directories that contain any of the given paths.
2345        let mut prev_dot_git_dir = None;
2346        for changed_path in changed_paths {
2347            let Some(dot_git_dir) = changed_path
2348                .ancestors()
2349                .find(|ancestor| ancestor.file_name() == Some(&*DOT_GIT))
2350            else {
2351                continue;
2352            };
2353
2354            // Avoid processing the same repository multiple times, if multiple paths
2355            // within it have changed.
2356            if prev_dot_git_dir == Some(dot_git_dir) {
2357                continue;
2358            }
2359            prev_dot_git_dir = Some(dot_git_dir);
2360
2361            // If there is already a repository for this .git directory, reload
2362            // the status for all of its files.
2363            let repository = self
2364                .snapshot
2365                .git_repositories
2366                .iter()
2367                .find_map(|(entry_id, repo)| {
2368                    (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2369                });
2370            match repository {
2371                None => {
2372                    self.build_git_repository(dot_git_dir.into(), fs);
2373                }
2374                Some((entry_id, repository)) => {
2375                    if repository.git_dir_scan_id == scan_id {
2376                        continue;
2377                    }
2378                    let Some(work_dir) = self
2379                        .snapshot
2380                        .entry_for_id(entry_id)
2381                        .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2382                    else {
2383                        continue;
2384                    };
2385
2386                    log::info!("reload git repository {:?}", dot_git_dir);
2387                    let repository = repository.repo_ptr.lock();
2388                    let branch = repository.branch_name();
2389                    repository.reload_index();
2390
2391                    self.snapshot
2392                        .git_repositories
2393                        .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2394                    self.snapshot
2395                        .snapshot
2396                        .repository_entries
2397                        .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2398
2399                    self.update_git_statuses(&work_dir, &*repository);
2400                }
2401            }
2402        }
2403
2404        // Remove any git repositories whose .git entry no longer exists.
2405        let snapshot = &mut self.snapshot;
2406        let mut repositories = mem::take(&mut snapshot.git_repositories);
2407        let mut repository_entries = mem::take(&mut snapshot.repository_entries);
2408        repositories.retain(|work_directory_id, _| {
2409            snapshot
2410                .entry_for_id(*work_directory_id)
2411                .map_or(false, |entry| {
2412                    snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2413                })
2414        });
2415        repository_entries.retain(|_, entry| repositories.get(&entry.work_directory.0).is_some());
2416        snapshot.git_repositories = repositories;
2417        snapshot.repository_entries = repository_entries;
2418    }
2419
2420    fn build_git_repository(
2421        &mut self,
2422        dot_git_path: Arc<Path>,
2423        fs: &dyn Fs,
2424    ) -> Option<(
2425        RepositoryWorkDirectory,
2426        Arc<Mutex<dyn GitRepository>>,
2427        TreeMap<RepoPath, GitFileStatus>,
2428    )> {
2429        log::info!("build git repository {:?}", dot_git_path);
2430
2431        let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2432
2433        // Guard against repositories inside the repository metadata
2434        if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2435            return None;
2436        };
2437
2438        let work_dir_id = self
2439            .snapshot
2440            .entry_for_path(work_dir_path.clone())
2441            .map(|entry| entry.id)?;
2442
2443        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2444            return None;
2445        }
2446
2447        let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2448        let repository = fs.open_repo(abs_path.as_path())?;
2449        let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2450
2451        let repo_lock = repository.lock();
2452        self.snapshot.repository_entries.insert(
2453            work_directory.clone(),
2454            RepositoryEntry {
2455                work_directory: work_dir_id.into(),
2456                branch: repo_lock.branch_name().map(Into::into),
2457            },
2458        );
2459
2460        let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2461        drop(repo_lock);
2462
2463        self.snapshot.git_repositories.insert(
2464            work_dir_id,
2465            LocalRepositoryEntry {
2466                git_dir_scan_id: 0,
2467                repo_ptr: repository.clone(),
2468                git_dir_path: dot_git_path.clone(),
2469            },
2470        );
2471
2472        Some((work_directory, repository, staged_statuses))
2473    }
2474
2475    fn update_git_statuses(
2476        &mut self,
2477        work_directory: &RepositoryWorkDirectory,
2478        repo: &dyn GitRepository,
2479    ) -> TreeMap<RepoPath, GitFileStatus> {
2480        let staged_statuses = repo.staged_statuses(Path::new(""));
2481
2482        let mut changes = vec![];
2483        let mut edits = vec![];
2484
2485        for mut entry in self
2486            .snapshot
2487            .descendent_entries(false, false, &work_directory.0)
2488            .cloned()
2489        {
2490            let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2491                continue;
2492            };
2493            let repo_path = RepoPath(repo_path.to_path_buf());
2494            let git_file_status = combine_git_statuses(
2495                staged_statuses.get(&repo_path).copied(),
2496                repo.unstaged_status(&repo_path, entry.mtime),
2497            );
2498            if entry.git_status != git_file_status {
2499                entry.git_status = git_file_status;
2500                changes.push(entry.path.clone());
2501                edits.push(Edit::Insert(entry));
2502            }
2503        }
2504
2505        self.snapshot.entries_by_path.edit(edits, &());
2506        util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2507        staged_statuses
2508    }
2509}
2510
2511async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2512    let contents = fs.load(abs_path).await?;
2513    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2514    let mut builder = GitignoreBuilder::new(parent);
2515    for line in contents.lines() {
2516        builder.add_line(Some(abs_path.into()), line)?;
2517    }
2518    Ok(builder.build()?)
2519}
2520
2521impl WorktreeId {
2522    pub fn from_usize(handle_id: usize) -> Self {
2523        Self(handle_id)
2524    }
2525
2526    pub(crate) fn from_proto(id: u64) -> Self {
2527        Self(id as usize)
2528    }
2529
2530    pub fn to_proto(&self) -> u64 {
2531        self.0 as u64
2532    }
2533
2534    pub fn to_usize(&self) -> usize {
2535        self.0
2536    }
2537}
2538
2539impl fmt::Display for WorktreeId {
2540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2541        self.0.fmt(f)
2542    }
2543}
2544
2545impl Deref for Worktree {
2546    type Target = Snapshot;
2547
2548    fn deref(&self) -> &Self::Target {
2549        match self {
2550            Worktree::Local(worktree) => &worktree.snapshot,
2551            Worktree::Remote(worktree) => &worktree.snapshot,
2552        }
2553    }
2554}
2555
2556impl Deref for LocalWorktree {
2557    type Target = LocalSnapshot;
2558
2559    fn deref(&self) -> &Self::Target {
2560        &self.snapshot
2561    }
2562}
2563
2564impl Deref for RemoteWorktree {
2565    type Target = Snapshot;
2566
2567    fn deref(&self) -> &Self::Target {
2568        &self.snapshot
2569    }
2570}
2571
2572impl fmt::Debug for LocalWorktree {
2573    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2574        self.snapshot.fmt(f)
2575    }
2576}
2577
2578impl fmt::Debug for Snapshot {
2579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2580        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2581        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2582
2583        impl<'a> fmt::Debug for EntriesByPath<'a> {
2584            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2585                f.debug_map()
2586                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2587                    .finish()
2588            }
2589        }
2590
2591        impl<'a> fmt::Debug for EntriesById<'a> {
2592            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2593                f.debug_list().entries(self.0.iter()).finish()
2594            }
2595        }
2596
2597        f.debug_struct("Snapshot")
2598            .field("id", &self.id)
2599            .field("root_name", &self.root_name)
2600            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2601            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2602            .finish()
2603    }
2604}
2605
2606#[derive(Clone, PartialEq)]
2607pub struct File {
2608    pub worktree: ModelHandle<Worktree>,
2609    pub path: Arc<Path>,
2610    pub mtime: SystemTime,
2611    pub(crate) entry_id: ProjectEntryId,
2612    pub(crate) is_local: bool,
2613    pub(crate) is_deleted: bool,
2614}
2615
2616impl language::File for File {
2617    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2618        if self.is_local {
2619            Some(self)
2620        } else {
2621            None
2622        }
2623    }
2624
2625    fn mtime(&self) -> SystemTime {
2626        self.mtime
2627    }
2628
2629    fn path(&self) -> &Arc<Path> {
2630        &self.path
2631    }
2632
2633    fn full_path(&self, cx: &AppContext) -> PathBuf {
2634        let mut full_path = PathBuf::new();
2635        let worktree = self.worktree.read(cx);
2636
2637        if worktree.is_visible() {
2638            full_path.push(worktree.root_name());
2639        } else {
2640            let path = worktree.abs_path();
2641
2642            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2643                full_path.push("~");
2644                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2645            } else {
2646                full_path.push(path)
2647            }
2648        }
2649
2650        if self.path.components().next().is_some() {
2651            full_path.push(&self.path);
2652        }
2653
2654        full_path
2655    }
2656
2657    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2658    /// of its worktree, then this method will return the name of the worktree itself.
2659    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2660        self.path
2661            .file_name()
2662            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2663    }
2664
2665    fn worktree_id(&self) -> usize {
2666        self.worktree.id()
2667    }
2668
2669    fn is_deleted(&self) -> bool {
2670        self.is_deleted
2671    }
2672
2673    fn as_any(&self) -> &dyn Any {
2674        self
2675    }
2676
2677    fn to_proto(&self) -> rpc::proto::File {
2678        rpc::proto::File {
2679            worktree_id: self.worktree.id() as u64,
2680            entry_id: self.entry_id.to_proto(),
2681            path: self.path.to_string_lossy().into(),
2682            mtime: Some(self.mtime.into()),
2683            is_deleted: self.is_deleted,
2684        }
2685    }
2686}
2687
2688impl language::LocalFile for File {
2689    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2690        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2691        if self.path.as_ref() == Path::new("") {
2692            worktree_path.to_path_buf()
2693        } else {
2694            worktree_path.join(&self.path)
2695        }
2696    }
2697
2698    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2699        let worktree = self.worktree.read(cx).as_local().unwrap();
2700        let abs_path = worktree.absolutize(&self.path);
2701        let fs = worktree.fs.clone();
2702        cx.background()
2703            .spawn(async move { fs.load(&abs_path).await })
2704    }
2705
2706    fn buffer_reloaded(
2707        &self,
2708        buffer_id: u64,
2709        version: &clock::Global,
2710        fingerprint: RopeFingerprint,
2711        line_ending: LineEnding,
2712        mtime: SystemTime,
2713        cx: &mut AppContext,
2714    ) {
2715        let worktree = self.worktree.read(cx).as_local().unwrap();
2716        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2717            worktree
2718                .client
2719                .send(proto::BufferReloaded {
2720                    project_id,
2721                    buffer_id,
2722                    version: serialize_version(version),
2723                    mtime: Some(mtime.into()),
2724                    fingerprint: serialize_fingerprint(fingerprint),
2725                    line_ending: serialize_line_ending(line_ending) as i32,
2726                })
2727                .log_err();
2728        }
2729    }
2730}
2731
2732impl File {
2733    pub fn for_entry(entry: Entry, worktree: ModelHandle<Worktree>) -> Arc<Self> {
2734        Arc::new(Self {
2735            worktree,
2736            path: entry.path.clone(),
2737            mtime: entry.mtime,
2738            entry_id: entry.id,
2739            is_local: true,
2740            is_deleted: false,
2741        })
2742    }
2743
2744    pub fn from_proto(
2745        proto: rpc::proto::File,
2746        worktree: ModelHandle<Worktree>,
2747        cx: &AppContext,
2748    ) -> Result<Self> {
2749        let worktree_id = worktree
2750            .read(cx)
2751            .as_remote()
2752            .ok_or_else(|| anyhow!("not remote"))?
2753            .id();
2754
2755        if worktree_id.to_proto() != proto.worktree_id {
2756            return Err(anyhow!("worktree id does not match file"));
2757        }
2758
2759        Ok(Self {
2760            worktree,
2761            path: Path::new(&proto.path).into(),
2762            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2763            entry_id: ProjectEntryId::from_proto(proto.entry_id),
2764            is_local: false,
2765            is_deleted: proto.is_deleted,
2766        })
2767    }
2768
2769    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2770        file.and_then(|f| f.as_any().downcast_ref())
2771    }
2772
2773    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2774        self.worktree.read(cx).id()
2775    }
2776
2777    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2778        if self.is_deleted {
2779            None
2780        } else {
2781            Some(self.entry_id)
2782        }
2783    }
2784}
2785
2786#[derive(Clone, Debug, PartialEq, Eq)]
2787pub struct Entry {
2788    pub id: ProjectEntryId,
2789    pub kind: EntryKind,
2790    pub path: Arc<Path>,
2791    pub inode: u64,
2792    pub mtime: SystemTime,
2793    pub is_symlink: bool,
2794
2795    /// Whether this entry is ignored by Zed.
2796    ///
2797    /// We only scan ignored entries once the directory is expanded and
2798    /// exclude them from searches.
2799    pub is_ignored: bool,
2800
2801    /// Whether this entry's canonical path is outside of the worktree.
2802    /// This means the entry is only accessible from the worktree root via a
2803    /// symlink.
2804    ///
2805    /// We only scan entries outside of the worktree once the symlinked
2806    /// directory is expanded. External entries are treated like gitignored
2807    /// entries in that they are not included in searches.
2808    pub is_external: bool,
2809    pub git_status: Option<GitFileStatus>,
2810}
2811
2812#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2813pub enum EntryKind {
2814    UnloadedDir,
2815    PendingDir,
2816    Dir,
2817    File(CharBag),
2818}
2819
2820#[derive(Clone, Copy, Debug, PartialEq)]
2821pub enum PathChange {
2822    /// A filesystem entry was was created.
2823    Added,
2824    /// A filesystem entry was removed.
2825    Removed,
2826    /// A filesystem entry was updated.
2827    Updated,
2828    /// A filesystem entry was either updated or added. We don't know
2829    /// whether or not it already existed, because the path had not
2830    /// been loaded before the event.
2831    AddedOrUpdated,
2832    /// A filesystem entry was found during the initial scan of the worktree.
2833    Loaded,
2834}
2835
2836pub struct GitRepositoryChange {
2837    /// The previous state of the repository, if it already existed.
2838    pub old_repository: Option<RepositoryEntry>,
2839}
2840
2841pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2842pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2843
2844impl Entry {
2845    fn new(
2846        path: Arc<Path>,
2847        metadata: &fs::Metadata,
2848        next_entry_id: &AtomicUsize,
2849        root_char_bag: CharBag,
2850    ) -> Self {
2851        Self {
2852            id: ProjectEntryId::new(next_entry_id),
2853            kind: if metadata.is_dir {
2854                EntryKind::PendingDir
2855            } else {
2856                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2857            },
2858            path,
2859            inode: metadata.inode,
2860            mtime: metadata.mtime,
2861            is_symlink: metadata.is_symlink,
2862            is_ignored: false,
2863            is_external: false,
2864            git_status: None,
2865        }
2866    }
2867
2868    pub fn is_dir(&self) -> bool {
2869        self.kind.is_dir()
2870    }
2871
2872    pub fn is_file(&self) -> bool {
2873        self.kind.is_file()
2874    }
2875
2876    pub fn git_status(&self) -> Option<GitFileStatus> {
2877        self.git_status
2878    }
2879}
2880
2881impl EntryKind {
2882    pub fn is_dir(&self) -> bool {
2883        matches!(
2884            self,
2885            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
2886        )
2887    }
2888
2889    pub fn is_unloaded(&self) -> bool {
2890        matches!(self, EntryKind::UnloadedDir)
2891    }
2892
2893    pub fn is_file(&self) -> bool {
2894        matches!(self, EntryKind::File(_))
2895    }
2896}
2897
2898impl sum_tree::Item for Entry {
2899    type Summary = EntrySummary;
2900
2901    fn summary(&self) -> Self::Summary {
2902        let non_ignored_count = if self.is_ignored || self.is_external {
2903            0
2904        } else {
2905            1
2906        };
2907        let file_count;
2908        let non_ignored_file_count;
2909        if self.is_file() {
2910            file_count = 1;
2911            non_ignored_file_count = non_ignored_count;
2912        } else {
2913            file_count = 0;
2914            non_ignored_file_count = 0;
2915        }
2916
2917        let mut statuses = GitStatuses::default();
2918        match self.git_status {
2919            Some(status) => match status {
2920                GitFileStatus::Added => statuses.added = 1,
2921                GitFileStatus::Modified => statuses.modified = 1,
2922                GitFileStatus::Conflict => statuses.conflict = 1,
2923            },
2924            None => {}
2925        }
2926
2927        EntrySummary {
2928            max_path: self.path.clone(),
2929            count: 1,
2930            non_ignored_count,
2931            file_count,
2932            non_ignored_file_count,
2933            statuses,
2934        }
2935    }
2936}
2937
2938impl sum_tree::KeyedItem for Entry {
2939    type Key = PathKey;
2940
2941    fn key(&self) -> Self::Key {
2942        PathKey(self.path.clone())
2943    }
2944}
2945
2946#[derive(Clone, Debug)]
2947pub struct EntrySummary {
2948    max_path: Arc<Path>,
2949    count: usize,
2950    non_ignored_count: usize,
2951    file_count: usize,
2952    non_ignored_file_count: usize,
2953    statuses: GitStatuses,
2954}
2955
2956impl Default for EntrySummary {
2957    fn default() -> Self {
2958        Self {
2959            max_path: Arc::from(Path::new("")),
2960            count: 0,
2961            non_ignored_count: 0,
2962            file_count: 0,
2963            non_ignored_file_count: 0,
2964            statuses: Default::default(),
2965        }
2966    }
2967}
2968
2969impl sum_tree::Summary for EntrySummary {
2970    type Context = ();
2971
2972    fn add_summary(&mut self, rhs: &Self, _: &()) {
2973        self.max_path = rhs.max_path.clone();
2974        self.count += rhs.count;
2975        self.non_ignored_count += rhs.non_ignored_count;
2976        self.file_count += rhs.file_count;
2977        self.non_ignored_file_count += rhs.non_ignored_file_count;
2978        self.statuses += rhs.statuses;
2979    }
2980}
2981
2982#[derive(Clone, Debug)]
2983struct PathEntry {
2984    id: ProjectEntryId,
2985    path: Arc<Path>,
2986    is_ignored: bool,
2987    scan_id: usize,
2988}
2989
2990impl sum_tree::Item for PathEntry {
2991    type Summary = PathEntrySummary;
2992
2993    fn summary(&self) -> Self::Summary {
2994        PathEntrySummary { max_id: self.id }
2995    }
2996}
2997
2998impl sum_tree::KeyedItem for PathEntry {
2999    type Key = ProjectEntryId;
3000
3001    fn key(&self) -> Self::Key {
3002        self.id
3003    }
3004}
3005
3006#[derive(Clone, Debug, Default)]
3007struct PathEntrySummary {
3008    max_id: ProjectEntryId,
3009}
3010
3011impl sum_tree::Summary for PathEntrySummary {
3012    type Context = ();
3013
3014    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3015        self.max_id = summary.max_id;
3016    }
3017}
3018
3019impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3020    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3021        *self = summary.max_id;
3022    }
3023}
3024
3025#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3026pub struct PathKey(Arc<Path>);
3027
3028impl Default for PathKey {
3029    fn default() -> Self {
3030        Self(Path::new("").into())
3031    }
3032}
3033
3034impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3035    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3036        self.0 = summary.max_path.clone();
3037    }
3038}
3039
3040struct BackgroundScanner {
3041    state: Mutex<BackgroundScannerState>,
3042    fs: Arc<dyn Fs>,
3043    status_updates_tx: UnboundedSender<ScanState>,
3044    executor: Arc<executor::Background>,
3045    scan_requests_rx: channel::Receiver<ScanRequest>,
3046    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3047    next_entry_id: Arc<AtomicUsize>,
3048    phase: BackgroundScannerPhase,
3049}
3050
3051#[derive(PartialEq)]
3052enum BackgroundScannerPhase {
3053    InitialScan,
3054    EventsReceivedDuringInitialScan,
3055    Events,
3056}
3057
3058impl BackgroundScanner {
3059    fn new(
3060        snapshot: LocalSnapshot,
3061        next_entry_id: Arc<AtomicUsize>,
3062        fs: Arc<dyn Fs>,
3063        status_updates_tx: UnboundedSender<ScanState>,
3064        executor: Arc<executor::Background>,
3065        scan_requests_rx: channel::Receiver<ScanRequest>,
3066        path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3067    ) -> Self {
3068        Self {
3069            fs,
3070            status_updates_tx,
3071            executor,
3072            scan_requests_rx,
3073            path_prefixes_to_scan_rx,
3074            next_entry_id,
3075            state: Mutex::new(BackgroundScannerState {
3076                prev_snapshot: snapshot.snapshot.clone(),
3077                snapshot,
3078                scanned_dirs: Default::default(),
3079                path_prefixes_to_scan: Default::default(),
3080                paths_to_scan: Default::default(),
3081                removed_entry_ids: Default::default(),
3082                changed_paths: Default::default(),
3083            }),
3084            phase: BackgroundScannerPhase::InitialScan,
3085        }
3086    }
3087
3088    async fn run(
3089        &mut self,
3090        mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
3091    ) {
3092        use futures::FutureExt as _;
3093
3094        // Populate ignores above the root.
3095        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3096        for (index, ancestor) in root_abs_path.ancestors().enumerate() {
3097            if index != 0 {
3098                if let Ok(ignore) =
3099                    build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3100                {
3101                    self.state
3102                        .lock()
3103                        .snapshot
3104                        .ignores_by_parent_abs_path
3105                        .insert(ancestor.into(), (ignore.into(), false));
3106                }
3107            }
3108            if ancestor.join(&*DOT_GIT).is_dir() {
3109                // Reached root of git repository.
3110                break;
3111            }
3112        }
3113
3114        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3115        {
3116            let mut state = self.state.lock();
3117            state.snapshot.scan_id += 1;
3118            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3119                let ignore_stack = state
3120                    .snapshot
3121                    .ignore_stack_for_abs_path(&root_abs_path, true);
3122                if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3123                    root_entry.is_ignored = true;
3124                    state.insert_entry(root_entry.clone(), self.fs.as_ref());
3125                }
3126                state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3127            }
3128        };
3129
3130        // Perform an initial scan of the directory.
3131        drop(scan_job_tx);
3132        self.scan_dirs(true, scan_job_rx).await;
3133        {
3134            let mut state = self.state.lock();
3135            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3136        }
3137
3138        self.send_status_update(false, None);
3139
3140        // Process any any FS events that occurred while performing the initial scan.
3141        // For these events, update events cannot be as precise, because we didn't
3142        // have the previous state loaded yet.
3143        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3144        if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3145            let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3146            while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3147                paths.extend(more_events.into_iter().map(|e| e.path));
3148            }
3149            self.process_events(paths).await;
3150        }
3151
3152        // Continue processing events until the worktree is dropped.
3153        self.phase = BackgroundScannerPhase::Events;
3154        loop {
3155            select_biased! {
3156                // Process any path refresh requests from the worktree. Prioritize
3157                // these before handling changes reported by the filesystem.
3158                request = self.scan_requests_rx.recv().fuse() => {
3159                    let Ok(request) = request else { break };
3160                    if !self.process_scan_request(request, false).await {
3161                        return;
3162                    }
3163                }
3164
3165                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3166                    let Ok(path_prefix) = path_prefix else { break };
3167                    log::trace!("adding path prefix {:?}", path_prefix);
3168
3169                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3170                    if did_scan {
3171                        let abs_path =
3172                        {
3173                            let mut state = self.state.lock();
3174                            state.path_prefixes_to_scan.insert(path_prefix.clone());
3175                            state.snapshot.abs_path.join(&path_prefix)
3176                        };
3177
3178                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3179                            self.process_events(vec![abs_path]).await;
3180                        }
3181                    }
3182                }
3183
3184                events = fs_events_rx.next().fuse() => {
3185                    let Some(events) = events else { break };
3186                    let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
3187                    while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3188                        paths.extend(more_events.into_iter().map(|e| e.path));
3189                    }
3190                    self.process_events(paths.clone()).await;
3191                }
3192            }
3193        }
3194    }
3195
3196    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3197        log::debug!("rescanning paths {:?}", request.relative_paths);
3198
3199        request.relative_paths.sort_unstable();
3200        self.forcibly_load_paths(&request.relative_paths).await;
3201
3202        let root_path = self.state.lock().snapshot.abs_path.clone();
3203        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3204            Ok(path) => path,
3205            Err(err) => {
3206                log::error!("failed to canonicalize root path: {}", err);
3207                return false;
3208            }
3209        };
3210        let abs_paths = request
3211            .relative_paths
3212            .iter()
3213            .map(|path| {
3214                if path.file_name().is_some() {
3215                    root_canonical_path.join(path)
3216                } else {
3217                    root_canonical_path.clone()
3218                }
3219            })
3220            .collect::<Vec<_>>();
3221
3222        self.reload_entries_for_paths(
3223            root_path,
3224            root_canonical_path,
3225            &request.relative_paths,
3226            abs_paths,
3227            None,
3228        )
3229        .await;
3230        self.send_status_update(scanning, Some(request.done))
3231    }
3232
3233    async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3234        let root_path = self.state.lock().snapshot.abs_path.clone();
3235        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3236            Ok(path) => path,
3237            Err(err) => {
3238                log::error!("failed to canonicalize root path: {}", err);
3239                return;
3240            }
3241        };
3242
3243        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3244        abs_paths.sort_unstable();
3245        abs_paths.dedup_by(|a, b| a.starts_with(&b));
3246        abs_paths.retain(|abs_path| {
3247            let snapshot = &self.state.lock().snapshot;
3248            {
3249                let relative_path: Arc<Path> =
3250                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3251                        path.into()
3252                    } else {
3253                        log::error!(
3254                        "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3255                    );
3256                        return false;
3257                    };
3258
3259                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3260                    snapshot
3261                        .entry_for_path(parent)
3262                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
3263                });
3264                if !parent_dir_is_loaded {
3265                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3266                    return false;
3267                }
3268
3269                relative_paths.push(relative_path);
3270                true
3271            }
3272        });
3273
3274        if relative_paths.is_empty() {
3275            return;
3276        }
3277
3278        log::debug!("received fs events {:?}", relative_paths);
3279
3280        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3281        self.reload_entries_for_paths(
3282            root_path,
3283            root_canonical_path,
3284            &relative_paths,
3285            abs_paths,
3286            Some(scan_job_tx.clone()),
3287        )
3288        .await;
3289        drop(scan_job_tx);
3290        self.scan_dirs(false, scan_job_rx).await;
3291
3292        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3293        self.update_ignore_statuses(scan_job_tx).await;
3294        self.scan_dirs(false, scan_job_rx).await;
3295
3296        {
3297            let mut state = self.state.lock();
3298            state.reload_repositories(&relative_paths, self.fs.as_ref());
3299            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3300            for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3301                state.scanned_dirs.remove(&entry_id);
3302            }
3303        }
3304
3305        self.send_status_update(false, None);
3306    }
3307
3308    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3309        let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3310        {
3311            let mut state = self.state.lock();
3312            let root_path = state.snapshot.abs_path.clone();
3313            for path in paths {
3314                for ancestor in path.ancestors() {
3315                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3316                        if entry.kind == EntryKind::UnloadedDir {
3317                            let abs_path = root_path.join(ancestor);
3318                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3319                            state.paths_to_scan.insert(path.clone());
3320                            break;
3321                        }
3322                    }
3323                }
3324            }
3325            drop(scan_job_tx);
3326        }
3327        while let Some(job) = scan_job_rx.next().await {
3328            self.scan_dir(&job).await.log_err();
3329        }
3330
3331        mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3332    }
3333
3334    async fn scan_dirs(
3335        &self,
3336        enable_progress_updates: bool,
3337        scan_jobs_rx: channel::Receiver<ScanJob>,
3338    ) {
3339        use futures::FutureExt as _;
3340
3341        if self
3342            .status_updates_tx
3343            .unbounded_send(ScanState::Started)
3344            .is_err()
3345        {
3346            return;
3347        }
3348
3349        let progress_update_count = AtomicUsize::new(0);
3350        self.executor
3351            .scoped(|scope| {
3352                for _ in 0..self.executor.num_cpus() {
3353                    scope.spawn(async {
3354                        let mut last_progress_update_count = 0;
3355                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3356                        futures::pin_mut!(progress_update_timer);
3357
3358                        loop {
3359                            select_biased! {
3360                                // Process any path refresh requests before moving on to process
3361                                // the scan queue, so that user operations are prioritized.
3362                                request = self.scan_requests_rx.recv().fuse() => {
3363                                    let Ok(request) = request else { break };
3364                                    if !self.process_scan_request(request, true).await {
3365                                        return;
3366                                    }
3367                                }
3368
3369                                // Send periodic progress updates to the worktree. Use an atomic counter
3370                                // to ensure that only one of the workers sends a progress update after
3371                                // the update interval elapses.
3372                                _ = progress_update_timer => {
3373                                    match progress_update_count.compare_exchange(
3374                                        last_progress_update_count,
3375                                        last_progress_update_count + 1,
3376                                        SeqCst,
3377                                        SeqCst
3378                                    ) {
3379                                        Ok(_) => {
3380                                            last_progress_update_count += 1;
3381                                            self.send_status_update(true, None);
3382                                        }
3383                                        Err(count) => {
3384                                            last_progress_update_count = count;
3385                                        }
3386                                    }
3387                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3388                                }
3389
3390                                // Recursively load directories from the file system.
3391                                job = scan_jobs_rx.recv().fuse() => {
3392                                    let Ok(job) = job else { break };
3393                                    if let Err(err) = self.scan_dir(&job).await {
3394                                        if job.path.as_ref() != Path::new("") {
3395                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3396                                        }
3397                                    }
3398                                }
3399                            }
3400                        }
3401                    })
3402                }
3403            })
3404            .await;
3405    }
3406
3407    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3408        let mut state = self.state.lock();
3409        if state.changed_paths.is_empty() && scanning {
3410            return true;
3411        }
3412
3413        let new_snapshot = state.snapshot.clone();
3414        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3415        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3416        state.changed_paths.clear();
3417
3418        self.status_updates_tx
3419            .unbounded_send(ScanState::Updated {
3420                snapshot: new_snapshot,
3421                changes,
3422                scanning,
3423                barrier,
3424            })
3425            .is_ok()
3426    }
3427
3428    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3429        log::debug!("scan directory {:?}", job.path);
3430
3431        let mut ignore_stack = job.ignore_stack.clone();
3432        let mut new_ignore = None;
3433        let (root_abs_path, root_char_bag, next_entry_id) = {
3434            let snapshot = &self.state.lock().snapshot;
3435            (
3436                snapshot.abs_path().clone(),
3437                snapshot.root_char_bag,
3438                self.next_entry_id.clone(),
3439            )
3440        };
3441
3442        let mut dotgit_path = None;
3443        let mut root_canonical_path = None;
3444        let mut new_entries: Vec<Entry> = Vec::new();
3445        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3446        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3447        while let Some(child_abs_path) = child_paths.next().await {
3448            let child_abs_path: Arc<Path> = match child_abs_path {
3449                Ok(child_abs_path) => child_abs_path.into(),
3450                Err(error) => {
3451                    log::error!("error processing entry {:?}", error);
3452                    continue;
3453                }
3454            };
3455
3456            let child_name = child_abs_path.file_name().unwrap();
3457            let child_path: Arc<Path> = job.path.join(child_name).into();
3458            let child_metadata = match self.fs.metadata(&child_abs_path).await {
3459                Ok(Some(metadata)) => metadata,
3460                Ok(None) => continue,
3461                Err(err) => {
3462                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
3463                    continue;
3464                }
3465            };
3466
3467            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3468            if child_name == *GITIGNORE {
3469                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3470                    Ok(ignore) => {
3471                        let ignore = Arc::new(ignore);
3472                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3473                        new_ignore = Some(ignore);
3474                    }
3475                    Err(error) => {
3476                        log::error!(
3477                            "error loading .gitignore file {:?} - {:?}",
3478                            child_name,
3479                            error
3480                        );
3481                    }
3482                }
3483
3484                // Update ignore status of any child entries we've already processed to reflect the
3485                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3486                // there should rarely be too numerous. Update the ignore stack associated with any
3487                // new jobs as well.
3488                let mut new_jobs = new_jobs.iter_mut();
3489                for entry in &mut new_entries {
3490                    let entry_abs_path = root_abs_path.join(&entry.path);
3491                    entry.is_ignored =
3492                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3493
3494                    if entry.is_dir() {
3495                        if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3496                            job.ignore_stack = if entry.is_ignored {
3497                                IgnoreStack::all()
3498                            } else {
3499                                ignore_stack.clone()
3500                            };
3501                        }
3502                    }
3503                }
3504            }
3505            // If we find a .git, we'll need to load the repository.
3506            else if child_name == *DOT_GIT {
3507                dotgit_path = Some(child_path.clone());
3508            }
3509
3510            let mut child_entry = Entry::new(
3511                child_path.clone(),
3512                &child_metadata,
3513                &next_entry_id,
3514                root_char_bag,
3515            );
3516
3517            if job.is_external {
3518                child_entry.is_external = true;
3519            } else if child_metadata.is_symlink {
3520                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3521                    Ok(path) => path,
3522                    Err(err) => {
3523                        log::error!(
3524                            "error reading target of symlink {:?}: {:?}",
3525                            child_abs_path,
3526                            err
3527                        );
3528                        continue;
3529                    }
3530                };
3531
3532                // lazily canonicalize the root path in order to determine if
3533                // symlinks point outside of the worktree.
3534                let root_canonical_path = match &root_canonical_path {
3535                    Some(path) => path,
3536                    None => match self.fs.canonicalize(&root_abs_path).await {
3537                        Ok(path) => root_canonical_path.insert(path),
3538                        Err(err) => {
3539                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3540                            continue;
3541                        }
3542                    },
3543                };
3544
3545                if !canonical_path.starts_with(root_canonical_path) {
3546                    child_entry.is_external = true;
3547                }
3548            }
3549
3550            if child_entry.is_dir() {
3551                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3552
3553                // Avoid recursing until crash in the case of a recursive symlink
3554                if !job.ancestor_inodes.contains(&child_entry.inode) {
3555                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3556                    ancestor_inodes.insert(child_entry.inode);
3557
3558                    new_jobs.push(Some(ScanJob {
3559                        path: child_path,
3560                        is_external: child_entry.is_external,
3561                        ignore_stack: if child_entry.is_ignored {
3562                            IgnoreStack::all()
3563                        } else {
3564                            ignore_stack.clone()
3565                        },
3566                        ancestor_inodes,
3567                        abs_path: child_abs_path,
3568                        scan_queue: job.scan_queue.clone(),
3569                        containing_repository: job.containing_repository.clone(),
3570                    }));
3571                } else {
3572                    new_jobs.push(None);
3573                }
3574            } else {
3575                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3576                if let Some((repository_dir, repository, staged_statuses)) =
3577                    &job.containing_repository
3578                {
3579                    if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3580                        let repo_path = RepoPath(repo_path.into());
3581                        child_entry.git_status = combine_git_statuses(
3582                            staged_statuses.get(&repo_path).copied(),
3583                            repository
3584                                .lock()
3585                                .unstaged_status(&repo_path, child_entry.mtime),
3586                        );
3587                    }
3588                }
3589            }
3590
3591            new_entries.push(child_entry);
3592        }
3593
3594        let mut state = self.state.lock();
3595
3596        // Identify any subdirectories that should not be scanned.
3597        let mut job_ix = 0;
3598        for entry in &mut new_entries {
3599            state.reuse_entry_id(entry);
3600            if entry.is_dir() {
3601                if state.should_scan_directory(&entry, &job.path.join(&entry.path)) {
3602                    job_ix += 1;
3603                } else {
3604                    log::debug!("defer scanning directory {:?}", entry.path);
3605                    entry.kind = EntryKind::UnloadedDir;
3606                    new_jobs.remove(job_ix);
3607                }
3608            }
3609        }
3610
3611        state.populate_dir(&job.path, new_entries, new_ignore);
3612
3613        let repository =
3614            dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3615
3616        for new_job in new_jobs {
3617            if let Some(mut new_job) = new_job {
3618                if let Some(containing_repository) = &repository {
3619                    new_job.containing_repository = Some(containing_repository.clone());
3620                }
3621
3622                job.scan_queue
3623                    .try_send(new_job)
3624                    .expect("channel is unbounded");
3625            }
3626        }
3627
3628        Ok(())
3629    }
3630
3631    async fn reload_entries_for_paths(
3632        &self,
3633        root_abs_path: Arc<Path>,
3634        root_canonical_path: PathBuf,
3635        relative_paths: &[Arc<Path>],
3636        abs_paths: Vec<PathBuf>,
3637        scan_queue_tx: Option<Sender<ScanJob>>,
3638    ) {
3639        let metadata = futures::future::join_all(
3640            abs_paths
3641                .iter()
3642                .map(|abs_path| async move {
3643                    let metadata = self.fs.metadata(&abs_path).await?;
3644                    if let Some(metadata) = metadata {
3645                        let canonical_path = self.fs.canonicalize(&abs_path).await?;
3646                        anyhow::Ok(Some((metadata, canonical_path)))
3647                    } else {
3648                        Ok(None)
3649                    }
3650                })
3651                .collect::<Vec<_>>(),
3652        )
3653        .await;
3654
3655        let mut state = self.state.lock();
3656        let snapshot = &mut state.snapshot;
3657        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3658        let doing_recursive_update = scan_queue_tx.is_some();
3659        snapshot.scan_id += 1;
3660        if is_idle && !doing_recursive_update {
3661            snapshot.completed_scan_id = snapshot.scan_id;
3662        }
3663
3664        // Remove any entries for paths that no longer exist or are being recursively
3665        // refreshed. Do this before adding any new entries, so that renames can be
3666        // detected regardless of the order of the paths.
3667        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3668            if matches!(metadata, Ok(None)) || doing_recursive_update {
3669                log::trace!("remove path {:?}", path);
3670                state.remove_path(path);
3671            }
3672        }
3673
3674        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3675            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3676            match metadata {
3677                Ok(Some((metadata, canonical_path))) => {
3678                    let ignore_stack = state
3679                        .snapshot
3680                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3681
3682                    let mut fs_entry = Entry::new(
3683                        path.clone(),
3684                        metadata,
3685                        self.next_entry_id.as_ref(),
3686                        state.snapshot.root_char_bag,
3687                    );
3688                    let is_dir = fs_entry.is_dir();
3689                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
3690                    fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
3691
3692                    if !is_dir
3693                        && !(fs_entry.is_ignored || state.snapshot.is_abs_path_excluded(&abs_path))
3694                    {
3695                        if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(&path) {
3696                            if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
3697                                let repo_path = RepoPath(repo_path.into());
3698                                let repo = repo.repo_ptr.lock();
3699                                fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
3700                            }
3701                        }
3702                    }
3703
3704                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
3705                        if state.should_scan_directory(&fs_entry, &abs_path) {
3706                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
3707                        } else {
3708                            fs_entry.kind = EntryKind::UnloadedDir;
3709                        }
3710                    }
3711
3712                    state.insert_entry(fs_entry, self.fs.as_ref());
3713                }
3714                Ok(None) => {
3715                    self.remove_repo_path(&path, &mut state.snapshot);
3716                }
3717                Err(err) => {
3718                    // TODO - create a special 'error' entry in the entries tree to mark this
3719                    log::error!("error reading file {abs_path:?} on event: {err:#}");
3720                }
3721            }
3722        }
3723
3724        util::extend_sorted(
3725            &mut state.changed_paths,
3726            relative_paths.iter().cloned(),
3727            usize::MAX,
3728            Ord::cmp,
3729        );
3730    }
3731
3732    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3733        if !path
3734            .components()
3735            .any(|component| component.as_os_str() == *DOT_GIT)
3736        {
3737            if let Some(repository) = snapshot.repository_for_work_directory(path) {
3738                let entry = repository.work_directory.0;
3739                snapshot.git_repositories.remove(&entry);
3740                snapshot
3741                    .snapshot
3742                    .repository_entries
3743                    .remove(&RepositoryWorkDirectory(path.into()));
3744                return Some(());
3745            }
3746        }
3747
3748        // TODO statuses
3749        // Track when a .git is removed and iterate over the file system there
3750
3751        Some(())
3752    }
3753
3754    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
3755        use futures::FutureExt as _;
3756
3757        let mut snapshot = self.state.lock().snapshot.clone();
3758        let mut ignores_to_update = Vec::new();
3759        let mut ignores_to_delete = Vec::new();
3760        let abs_path = snapshot.abs_path.clone();
3761        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3762            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3763                if *needs_update {
3764                    *needs_update = false;
3765                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3766                        ignores_to_update.push(parent_abs_path.clone());
3767                    }
3768                }
3769
3770                let ignore_path = parent_path.join(&*GITIGNORE);
3771                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3772                    ignores_to_delete.push(parent_abs_path.clone());
3773                }
3774            }
3775        }
3776
3777        for parent_abs_path in ignores_to_delete {
3778            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3779            self.state
3780                .lock()
3781                .snapshot
3782                .ignores_by_parent_abs_path
3783                .remove(&parent_abs_path);
3784        }
3785
3786        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3787        ignores_to_update.sort_unstable();
3788        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3789        while let Some(parent_abs_path) = ignores_to_update.next() {
3790            while ignores_to_update
3791                .peek()
3792                .map_or(false, |p| p.starts_with(&parent_abs_path))
3793            {
3794                ignores_to_update.next().unwrap();
3795            }
3796
3797            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3798            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3799                abs_path: parent_abs_path,
3800                ignore_stack,
3801                ignore_queue: ignore_queue_tx.clone(),
3802                scan_queue: scan_job_tx.clone(),
3803            }))
3804            .unwrap();
3805        }
3806        drop(ignore_queue_tx);
3807
3808        self.executor
3809            .scoped(|scope| {
3810                for _ in 0..self.executor.num_cpus() {
3811                    scope.spawn(async {
3812                        loop {
3813                            select_biased! {
3814                                // Process any path refresh requests before moving on to process
3815                                // the queue of ignore statuses.
3816                                request = self.scan_requests_rx.recv().fuse() => {
3817                                    let Ok(request) = request else { break };
3818                                    if !self.process_scan_request(request, true).await {
3819                                        return;
3820                                    }
3821                                }
3822
3823                                // Recursively process directories whose ignores have changed.
3824                                job = ignore_queue_rx.recv().fuse() => {
3825                                    let Ok(job) = job else { break };
3826                                    self.update_ignore_status(job, &snapshot).await;
3827                                }
3828                            }
3829                        }
3830                    });
3831                }
3832            })
3833            .await;
3834    }
3835
3836    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3837        log::trace!("update ignore status {:?}", job.abs_path);
3838
3839        let mut ignore_stack = job.ignore_stack;
3840        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3841            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3842        }
3843
3844        let mut entries_by_id_edits = Vec::new();
3845        let mut entries_by_path_edits = Vec::new();
3846        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3847        for mut entry in snapshot.child_entries(path).cloned() {
3848            let was_ignored = entry.is_ignored;
3849            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
3850            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3851            if entry.is_dir() {
3852                let child_ignore_stack = if entry.is_ignored {
3853                    IgnoreStack::all()
3854                } else {
3855                    ignore_stack.clone()
3856                };
3857
3858                // Scan any directories that were previously ignored and weren't previously scanned.
3859                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
3860                    let state = self.state.lock();
3861                    if state.should_scan_directory(&entry, &abs_path) {
3862                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
3863                    }
3864                }
3865
3866                job.ignore_queue
3867                    .send(UpdateIgnoreStatusJob {
3868                        abs_path: abs_path.clone(),
3869                        ignore_stack: child_ignore_stack,
3870                        ignore_queue: job.ignore_queue.clone(),
3871                        scan_queue: job.scan_queue.clone(),
3872                    })
3873                    .await
3874                    .unwrap();
3875            }
3876
3877            if entry.is_ignored != was_ignored {
3878                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3879                path_entry.scan_id = snapshot.scan_id;
3880                path_entry.is_ignored = entry.is_ignored;
3881                entries_by_id_edits.push(Edit::Insert(path_entry));
3882                entries_by_path_edits.push(Edit::Insert(entry));
3883            }
3884        }
3885
3886        let state = &mut self.state.lock();
3887        for edit in &entries_by_path_edits {
3888            if let Edit::Insert(entry) = edit {
3889                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
3890                    state.changed_paths.insert(ix, entry.path.clone());
3891                }
3892            }
3893        }
3894
3895        state
3896            .snapshot
3897            .entries_by_path
3898            .edit(entries_by_path_edits, &());
3899        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3900    }
3901
3902    fn build_change_set(
3903        &self,
3904        old_snapshot: &Snapshot,
3905        new_snapshot: &Snapshot,
3906        event_paths: &[Arc<Path>],
3907    ) -> UpdatedEntriesSet {
3908        use BackgroundScannerPhase::*;
3909        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
3910
3911        // Identify which paths have changed. Use the known set of changed
3912        // parent paths to optimize the search.
3913        let mut changes = Vec::new();
3914        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
3915        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
3916        let mut last_newly_loaded_dir_path = None;
3917        old_paths.next(&());
3918        new_paths.next(&());
3919        for path in event_paths {
3920            let path = PathKey(path.clone());
3921            if old_paths.item().map_or(false, |e| e.path < path.0) {
3922                old_paths.seek_forward(&path, Bias::Left, &());
3923            }
3924            if new_paths.item().map_or(false, |e| e.path < path.0) {
3925                new_paths.seek_forward(&path, Bias::Left, &());
3926            }
3927            loop {
3928                match (old_paths.item(), new_paths.item()) {
3929                    (Some(old_entry), Some(new_entry)) => {
3930                        if old_entry.path > path.0
3931                            && new_entry.path > path.0
3932                            && !old_entry.path.starts_with(&path.0)
3933                            && !new_entry.path.starts_with(&path.0)
3934                        {
3935                            break;
3936                        }
3937
3938                        match Ord::cmp(&old_entry.path, &new_entry.path) {
3939                            Ordering::Less => {
3940                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
3941                                old_paths.next(&());
3942                            }
3943                            Ordering::Equal => {
3944                                if self.phase == EventsReceivedDuringInitialScan {
3945                                    if old_entry.id != new_entry.id {
3946                                        changes.push((
3947                                            old_entry.path.clone(),
3948                                            old_entry.id,
3949                                            Removed,
3950                                        ));
3951                                    }
3952                                    // If the worktree was not fully initialized when this event was generated,
3953                                    // we can't know whether this entry was added during the scan or whether
3954                                    // it was merely updated.
3955                                    changes.push((
3956                                        new_entry.path.clone(),
3957                                        new_entry.id,
3958                                        AddedOrUpdated,
3959                                    ));
3960                                } else if old_entry.id != new_entry.id {
3961                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
3962                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
3963                                } else if old_entry != new_entry {
3964                                    if old_entry.kind.is_unloaded() {
3965                                        last_newly_loaded_dir_path = Some(&new_entry.path);
3966                                        changes.push((
3967                                            new_entry.path.clone(),
3968                                            new_entry.id,
3969                                            Loaded,
3970                                        ));
3971                                    } else {
3972                                        changes.push((
3973                                            new_entry.path.clone(),
3974                                            new_entry.id,
3975                                            Updated,
3976                                        ));
3977                                    }
3978                                }
3979                                old_paths.next(&());
3980                                new_paths.next(&());
3981                            }
3982                            Ordering::Greater => {
3983                                let is_newly_loaded = self.phase == InitialScan
3984                                    || last_newly_loaded_dir_path
3985                                        .as_ref()
3986                                        .map_or(false, |dir| new_entry.path.starts_with(&dir));
3987                                changes.push((
3988                                    new_entry.path.clone(),
3989                                    new_entry.id,
3990                                    if is_newly_loaded { Loaded } else { Added },
3991                                ));
3992                                new_paths.next(&());
3993                            }
3994                        }
3995                    }
3996                    (Some(old_entry), None) => {
3997                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
3998                        old_paths.next(&());
3999                    }
4000                    (None, Some(new_entry)) => {
4001                        let is_newly_loaded = self.phase == InitialScan
4002                            || last_newly_loaded_dir_path
4003                                .as_ref()
4004                                .map_or(false, |dir| new_entry.path.starts_with(&dir));
4005                        changes.push((
4006                            new_entry.path.clone(),
4007                            new_entry.id,
4008                            if is_newly_loaded { Loaded } else { Added },
4009                        ));
4010                        new_paths.next(&());
4011                    }
4012                    (None, None) => break,
4013                }
4014            }
4015        }
4016
4017        changes.into()
4018    }
4019
4020    async fn progress_timer(&self, running: bool) {
4021        if !running {
4022            return futures::future::pending().await;
4023        }
4024
4025        #[cfg(any(test, feature = "test-support"))]
4026        if self.fs.is_fake() {
4027            return self.executor.simulate_random_delay().await;
4028        }
4029
4030        smol::Timer::after(Duration::from_millis(100)).await;
4031    }
4032}
4033
4034fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4035    let mut result = root_char_bag;
4036    result.extend(
4037        path.to_string_lossy()
4038            .chars()
4039            .map(|c| c.to_ascii_lowercase()),
4040    );
4041    result
4042}
4043
4044struct ScanJob {
4045    abs_path: Arc<Path>,
4046    path: Arc<Path>,
4047    ignore_stack: Arc<IgnoreStack>,
4048    scan_queue: Sender<ScanJob>,
4049    ancestor_inodes: TreeSet<u64>,
4050    is_external: bool,
4051    containing_repository: Option<(
4052        RepositoryWorkDirectory,
4053        Arc<Mutex<dyn GitRepository>>,
4054        TreeMap<RepoPath, GitFileStatus>,
4055    )>,
4056}
4057
4058struct UpdateIgnoreStatusJob {
4059    abs_path: Arc<Path>,
4060    ignore_stack: Arc<IgnoreStack>,
4061    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4062    scan_queue: Sender<ScanJob>,
4063}
4064
4065pub trait WorktreeModelHandle {
4066    #[cfg(any(test, feature = "test-support"))]
4067    fn flush_fs_events<'a>(
4068        &self,
4069        cx: &'a gpui::TestAppContext,
4070    ) -> futures::future::LocalBoxFuture<'a, ()>;
4071}
4072
4073impl WorktreeModelHandle for ModelHandle<Worktree> {
4074    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4075    // occurred before the worktree was constructed. These events can cause the worktree to perform
4076    // extra directory scans, and emit extra scan-state notifications.
4077    //
4078    // This function mutates the worktree's directory and waits for those mutations to be picked up,
4079    // to ensure that all redundant FS events have already been processed.
4080    #[cfg(any(test, feature = "test-support"))]
4081    fn flush_fs_events<'a>(
4082        &self,
4083        cx: &'a gpui::TestAppContext,
4084    ) -> futures::future::LocalBoxFuture<'a, ()> {
4085        let filename = "fs-event-sentinel";
4086        let tree = self.clone();
4087        let (fs, root_path) = self.read_with(cx, |tree, _| {
4088            let tree = tree.as_local().unwrap();
4089            (tree.fs.clone(), tree.abs_path().clone())
4090        });
4091
4092        async move {
4093            fs.create_file(&root_path.join(filename), Default::default())
4094                .await
4095                .unwrap();
4096            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
4097                .await;
4098
4099            fs.remove_file(&root_path.join(filename), Default::default())
4100                .await
4101                .unwrap();
4102            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
4103                .await;
4104
4105            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4106                .await;
4107        }
4108        .boxed_local()
4109    }
4110}
4111
4112#[derive(Clone, Debug)]
4113struct TraversalProgress<'a> {
4114    max_path: &'a Path,
4115    count: usize,
4116    non_ignored_count: usize,
4117    file_count: usize,
4118    non_ignored_file_count: usize,
4119}
4120
4121impl<'a> TraversalProgress<'a> {
4122    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4123        match (include_ignored, include_dirs) {
4124            (true, true) => self.count,
4125            (true, false) => self.file_count,
4126            (false, true) => self.non_ignored_count,
4127            (false, false) => self.non_ignored_file_count,
4128        }
4129    }
4130}
4131
4132impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4133    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4134        self.max_path = summary.max_path.as_ref();
4135        self.count += summary.count;
4136        self.non_ignored_count += summary.non_ignored_count;
4137        self.file_count += summary.file_count;
4138        self.non_ignored_file_count += summary.non_ignored_file_count;
4139    }
4140}
4141
4142impl<'a> Default for TraversalProgress<'a> {
4143    fn default() -> Self {
4144        Self {
4145            max_path: Path::new(""),
4146            count: 0,
4147            non_ignored_count: 0,
4148            file_count: 0,
4149            non_ignored_file_count: 0,
4150        }
4151    }
4152}
4153
4154#[derive(Clone, Debug, Default, Copy)]
4155struct GitStatuses {
4156    added: usize,
4157    modified: usize,
4158    conflict: usize,
4159}
4160
4161impl AddAssign for GitStatuses {
4162    fn add_assign(&mut self, rhs: Self) {
4163        self.added += rhs.added;
4164        self.modified += rhs.modified;
4165        self.conflict += rhs.conflict;
4166    }
4167}
4168
4169impl Sub for GitStatuses {
4170    type Output = GitStatuses;
4171
4172    fn sub(self, rhs: Self) -> Self::Output {
4173        GitStatuses {
4174            added: self.added - rhs.added,
4175            modified: self.modified - rhs.modified,
4176            conflict: self.conflict - rhs.conflict,
4177        }
4178    }
4179}
4180
4181impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4182    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4183        *self += summary.statuses
4184    }
4185}
4186
4187pub struct Traversal<'a> {
4188    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4189    include_ignored: bool,
4190    include_dirs: bool,
4191}
4192
4193impl<'a> Traversal<'a> {
4194    pub fn advance(&mut self) -> bool {
4195        self.cursor.seek_forward(
4196            &TraversalTarget::Count {
4197                count: self.end_offset() + 1,
4198                include_dirs: self.include_dirs,
4199                include_ignored: self.include_ignored,
4200            },
4201            Bias::Left,
4202            &(),
4203        )
4204    }
4205
4206    pub fn advance_to_sibling(&mut self) -> bool {
4207        while let Some(entry) = self.cursor.item() {
4208            self.cursor.seek_forward(
4209                &TraversalTarget::PathSuccessor(&entry.path),
4210                Bias::Left,
4211                &(),
4212            );
4213            if let Some(entry) = self.cursor.item() {
4214                if (self.include_dirs || !entry.is_dir())
4215                    && (self.include_ignored || !entry.is_ignored)
4216                {
4217                    return true;
4218                }
4219            }
4220        }
4221        false
4222    }
4223
4224    pub fn entry(&self) -> Option<&'a Entry> {
4225        self.cursor.item()
4226    }
4227
4228    pub fn start_offset(&self) -> usize {
4229        self.cursor
4230            .start()
4231            .count(self.include_dirs, self.include_ignored)
4232    }
4233
4234    pub fn end_offset(&self) -> usize {
4235        self.cursor
4236            .end(&())
4237            .count(self.include_dirs, self.include_ignored)
4238    }
4239}
4240
4241impl<'a> Iterator for Traversal<'a> {
4242    type Item = &'a Entry;
4243
4244    fn next(&mut self) -> Option<Self::Item> {
4245        if let Some(item) = self.entry() {
4246            self.advance();
4247            Some(item)
4248        } else {
4249            None
4250        }
4251    }
4252}
4253
4254#[derive(Debug)]
4255enum TraversalTarget<'a> {
4256    Path(&'a Path),
4257    PathSuccessor(&'a Path),
4258    Count {
4259        count: usize,
4260        include_ignored: bool,
4261        include_dirs: bool,
4262    },
4263}
4264
4265impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4266    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4267        match self {
4268            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4269            TraversalTarget::PathSuccessor(path) => {
4270                if !cursor_location.max_path.starts_with(path) {
4271                    Ordering::Equal
4272                } else {
4273                    Ordering::Greater
4274                }
4275            }
4276            TraversalTarget::Count {
4277                count,
4278                include_dirs,
4279                include_ignored,
4280            } => Ord::cmp(
4281                count,
4282                &cursor_location.count(*include_dirs, *include_ignored),
4283            ),
4284        }
4285    }
4286}
4287
4288impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4289    for TraversalTarget<'b>
4290{
4291    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4292        self.cmp(&cursor_location.0, &())
4293    }
4294}
4295
4296struct ChildEntriesIter<'a> {
4297    parent_path: &'a Path,
4298    traversal: Traversal<'a>,
4299}
4300
4301impl<'a> Iterator for ChildEntriesIter<'a> {
4302    type Item = &'a Entry;
4303
4304    fn next(&mut self) -> Option<Self::Item> {
4305        if let Some(item) = self.traversal.entry() {
4306            if item.path.starts_with(&self.parent_path) {
4307                self.traversal.advance_to_sibling();
4308                return Some(item);
4309            }
4310        }
4311        None
4312    }
4313}
4314
4315pub struct DescendentEntriesIter<'a> {
4316    parent_path: &'a Path,
4317    traversal: Traversal<'a>,
4318}
4319
4320impl<'a> Iterator for DescendentEntriesIter<'a> {
4321    type Item = &'a Entry;
4322
4323    fn next(&mut self) -> Option<Self::Item> {
4324        if let Some(item) = self.traversal.entry() {
4325            if item.path.starts_with(&self.parent_path) {
4326                self.traversal.advance();
4327                return Some(item);
4328            }
4329        }
4330        None
4331    }
4332}
4333
4334impl<'a> From<&'a Entry> for proto::Entry {
4335    fn from(entry: &'a Entry) -> Self {
4336        Self {
4337            id: entry.id.to_proto(),
4338            is_dir: entry.is_dir(),
4339            path: entry.path.to_string_lossy().into(),
4340            inode: entry.inode,
4341            mtime: Some(entry.mtime.into()),
4342            is_symlink: entry.is_symlink,
4343            is_ignored: entry.is_ignored,
4344            is_external: entry.is_external,
4345            git_status: entry.git_status.map(git_status_to_proto),
4346        }
4347    }
4348}
4349
4350impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4351    type Error = anyhow::Error;
4352
4353    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4354        if let Some(mtime) = entry.mtime {
4355            let kind = if entry.is_dir {
4356                EntryKind::Dir
4357            } else {
4358                let mut char_bag = *root_char_bag;
4359                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4360                EntryKind::File(char_bag)
4361            };
4362            let path: Arc<Path> = PathBuf::from(entry.path).into();
4363            Ok(Entry {
4364                id: ProjectEntryId::from_proto(entry.id),
4365                kind,
4366                path,
4367                inode: entry.inode,
4368                mtime: mtime.into(),
4369                is_symlink: entry.is_symlink,
4370                is_ignored: entry.is_ignored,
4371                is_external: entry.is_external,
4372                git_status: git_status_from_proto(entry.git_status),
4373            })
4374        } else {
4375            Err(anyhow!(
4376                "missing mtime in remote worktree entry {:?}",
4377                entry.path
4378            ))
4379        }
4380    }
4381}
4382
4383fn combine_git_statuses(
4384    staged: Option<GitFileStatus>,
4385    unstaged: Option<GitFileStatus>,
4386) -> Option<GitFileStatus> {
4387    if let Some(staged) = staged {
4388        if let Some(unstaged) = unstaged {
4389            if unstaged != staged {
4390                Some(GitFileStatus::Modified)
4391            } else {
4392                Some(staged)
4393            }
4394        } else {
4395            Some(staged)
4396        }
4397    } else {
4398        unstaged
4399    }
4400}
4401
4402fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4403    git_status.and_then(|status| {
4404        proto::GitStatus::from_i32(status).map(|status| match status {
4405            proto::GitStatus::Added => GitFileStatus::Added,
4406            proto::GitStatus::Modified => GitFileStatus::Modified,
4407            proto::GitStatus::Conflict => GitFileStatus::Conflict,
4408        })
4409    })
4410}
4411
4412fn git_status_to_proto(status: GitFileStatus) -> i32 {
4413    match status {
4414        GitFileStatus::Added => proto::GitStatus::Added as i32,
4415        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4416        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4417    }
4418}