worktree.rs

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