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