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