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