worktree.rs

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