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