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::{AddAssign, Deref, DerefMut, Sub},
  49    path::{Path, PathBuf},
  50    pin::Pin,
  51    sync::{
  52        atomic::{AtomicUsize, Ordering::SeqCst},
  53        Arc,
  54    },
  55    time::{Duration, SystemTime},
  56};
  57use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  58use util::{paths::HOME, ResultExt};
  59
  60#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  61pub struct WorktreeId(usize);
  62
  63pub enum Worktree {
  64    Local(LocalWorktree),
  65    Remote(RemoteWorktree),
  66}
  67
  68pub struct LocalWorktree {
  69    snapshot: LocalSnapshot,
  70    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::<TraversalProgress>();
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 statuses_for_paths<'a>(
1674        &self,
1675        paths: impl IntoIterator<Item = &'a Path>,
1676    ) -> Vec<Option<GitFileStatus>> {
1677        let mut cursor = self
1678            .entries_by_path
1679            .cursor::<(TraversalProgress, GitStatuses)>();
1680        let mut paths = paths.into_iter().peekable();
1681        let mut path_stack = Vec::<(&Path, usize, GitStatuses)>::new();
1682        let mut result = Vec::new();
1683
1684        loop {
1685            let next_path = paths.peek();
1686            let containing_path = path_stack.last();
1687
1688            let mut entry_to_finish = None;
1689            let mut path_to_start = None;
1690            match (containing_path, next_path) {
1691                (Some((containing_path, _, _)), Some(next_path)) => {
1692                    if next_path.starts_with(containing_path) {
1693                        path_to_start = paths.next();
1694                    } else {
1695                        entry_to_finish = path_stack.pop();
1696                    }
1697                }
1698                (None, Some(_)) => path_to_start = paths.next(),
1699                (Some(_), None) => entry_to_finish = path_stack.pop(),
1700                (None, None) => break,
1701            }
1702
1703            if let Some((containing_path, result_ix, prev_statuses)) = entry_to_finish {
1704                cursor.seek_forward(
1705                    &TraversalTarget::PathSuccessor(containing_path),
1706                    Bias::Left,
1707                    &(),
1708                );
1709
1710                let statuses = cursor.start().1 - prev_statuses;
1711
1712                result[result_ix] = if statuses.conflict > 0 {
1713                    Some(GitFileStatus::Conflict)
1714                } else if statuses.modified > 0 {
1715                    Some(GitFileStatus::Modified)
1716                } else if statuses.added > 0 {
1717                    Some(GitFileStatus::Added)
1718                } else {
1719                    None
1720                };
1721            }
1722            if let Some(path_to_start) = path_to_start {
1723                cursor.seek_forward(&TraversalTarget::Path(path_to_start), Bias::Left, &());
1724                path_stack.push((path_to_start, result.len(), cursor.start().1));
1725                result.push(None);
1726            }
1727        }
1728
1729        return result;
1730    }
1731
1732    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1733        let empty_path = Path::new("");
1734        self.entries_by_path
1735            .cursor::<()>()
1736            .filter(move |entry| entry.path.as_ref() != empty_path)
1737            .map(|entry| &entry.path)
1738    }
1739
1740    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1741        let mut cursor = self.entries_by_path.cursor();
1742        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1743        let traversal = Traversal {
1744            cursor,
1745            include_dirs: true,
1746            include_ignored: true,
1747        };
1748        ChildEntriesIter {
1749            traversal,
1750            parent_path,
1751        }
1752    }
1753
1754    fn descendent_entries<'a>(
1755        &'a self,
1756        include_dirs: bool,
1757        include_ignored: bool,
1758        parent_path: &'a Path,
1759    ) -> DescendentEntriesIter<'a> {
1760        let mut cursor = self.entries_by_path.cursor();
1761        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Left, &());
1762        let mut traversal = Traversal {
1763            cursor,
1764            include_dirs,
1765            include_ignored,
1766        };
1767
1768        if traversal.end_offset() == traversal.start_offset() {
1769            traversal.advance();
1770        }
1771
1772        DescendentEntriesIter {
1773            traversal,
1774            parent_path,
1775        }
1776    }
1777
1778    pub fn root_entry(&self) -> Option<&Entry> {
1779        self.entry_for_path("")
1780    }
1781
1782    pub fn root_name(&self) -> &str {
1783        &self.root_name
1784    }
1785
1786    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1787        self.repository_entries
1788            .get(&RepositoryWorkDirectory(Path::new("").into()))
1789            .map(|entry| entry.to_owned())
1790    }
1791
1792    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1793        self.repository_entries.values()
1794    }
1795
1796    pub fn scan_id(&self) -> usize {
1797        self.scan_id
1798    }
1799
1800    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1801        let path = path.as_ref();
1802        self.traverse_from_path(true, true, path)
1803            .entry()
1804            .and_then(|entry| {
1805                if entry.path.as_ref() == path {
1806                    Some(entry)
1807                } else {
1808                    None
1809                }
1810            })
1811    }
1812
1813    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1814        let entry = self.entries_by_id.get(&id, &())?;
1815        self.entry_for_path(&entry.path)
1816    }
1817
1818    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1819        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1820    }
1821}
1822
1823impl LocalSnapshot {
1824    pub(crate) fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
1825        self.git_repositories.get(&repo.work_directory.0)
1826    }
1827
1828    pub(crate) fn local_repo_for_path(
1829        &self,
1830        path: &Path,
1831    ) -> Option<(RepositoryWorkDirectory, &LocalRepositoryEntry)> {
1832        let (path, repo) = self.repository_and_work_directory_for_path(path)?;
1833        Some((path, self.git_repositories.get(&repo.work_directory_id())?))
1834    }
1835
1836    pub(crate) fn repo_for_metadata(
1837        &self,
1838        path: &Path,
1839    ) -> Option<(&ProjectEntryId, &LocalRepositoryEntry)> {
1840        self.git_repositories
1841            .iter()
1842            .find(|(_, repo)| repo.in_dot_git(path))
1843    }
1844
1845    fn build_update(
1846        &self,
1847        project_id: u64,
1848        worktree_id: u64,
1849        entry_changes: UpdatedEntriesSet,
1850        repo_changes: UpdatedGitRepositoriesSet,
1851    ) -> proto::UpdateWorktree {
1852        let mut updated_entries = Vec::new();
1853        let mut removed_entries = Vec::new();
1854        let mut updated_repositories = Vec::new();
1855        let mut removed_repositories = Vec::new();
1856
1857        for (_, entry_id, path_change) in entry_changes.iter() {
1858            if let PathChange::Removed = path_change {
1859                removed_entries.push(entry_id.0 as u64);
1860            } else if let Some(entry) = self.entry_for_id(*entry_id) {
1861                updated_entries.push(proto::Entry::from(entry));
1862            }
1863        }
1864
1865        for (work_dir_path, change) in repo_changes.iter() {
1866            let new_repo = self
1867                .repository_entries
1868                .get(&RepositoryWorkDirectory(work_dir_path.clone()));
1869            match (&change.old_repository, new_repo) {
1870                (Some(old_repo), Some(new_repo)) => {
1871                    updated_repositories.push(new_repo.build_update(old_repo));
1872                }
1873                (None, Some(new_repo)) => {
1874                    updated_repositories.push(proto::RepositoryEntry::from(new_repo));
1875                }
1876                (Some(old_repo), None) => {
1877                    removed_repositories.push(old_repo.work_directory.0.to_proto());
1878                }
1879                _ => {}
1880            }
1881        }
1882
1883        removed_entries.sort_unstable();
1884        updated_entries.sort_unstable_by_key(|e| e.id);
1885        removed_repositories.sort_unstable();
1886        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
1887
1888        // TODO - optimize, knowing that removed_entries are sorted.
1889        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
1890
1891        proto::UpdateWorktree {
1892            project_id,
1893            worktree_id,
1894            abs_path: self.abs_path().to_string_lossy().into(),
1895            root_name: self.root_name().to_string(),
1896            updated_entries,
1897            removed_entries,
1898            scan_id: self.scan_id as u64,
1899            is_last_update: self.completed_scan_id == self.scan_id,
1900            updated_repositories,
1901            removed_repositories,
1902        }
1903    }
1904
1905    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
1906        let mut updated_entries = self
1907            .entries_by_path
1908            .iter()
1909            .map(proto::Entry::from)
1910            .collect::<Vec<_>>();
1911        updated_entries.sort_unstable_by_key(|e| e.id);
1912
1913        let mut updated_repositories = self
1914            .repository_entries
1915            .values()
1916            .map(proto::RepositoryEntry::from)
1917            .collect::<Vec<_>>();
1918        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
1919
1920        proto::UpdateWorktree {
1921            project_id,
1922            worktree_id,
1923            abs_path: self.abs_path().to_string_lossy().into(),
1924            root_name: self.root_name().to_string(),
1925            updated_entries,
1926            removed_entries: Vec::new(),
1927            scan_id: self.scan_id as u64,
1928            is_last_update: self.completed_scan_id == self.scan_id,
1929            updated_repositories,
1930            removed_repositories: Vec::new(),
1931        }
1932    }
1933
1934    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1935        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1936            let abs_path = self.abs_path.join(&entry.path);
1937            match smol::block_on(build_gitignore(&abs_path, fs)) {
1938                Ok(ignore) => {
1939                    self.ignores_by_parent_abs_path
1940                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
1941                }
1942                Err(error) => {
1943                    log::error!(
1944                        "error loading .gitignore file {:?} - {:?}",
1945                        &entry.path,
1946                        error
1947                    );
1948                }
1949            }
1950        }
1951
1952        if entry.kind == EntryKind::PendingDir {
1953            if let Some(existing_entry) =
1954                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1955            {
1956                entry.kind = existing_entry.kind;
1957            }
1958        }
1959
1960        let scan_id = self.scan_id;
1961        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
1962        if let Some(removed) = removed {
1963            if removed.id != entry.id {
1964                self.entries_by_id.remove(&removed.id, &());
1965            }
1966        }
1967        self.entries_by_id.insert_or_replace(
1968            PathEntry {
1969                id: entry.id,
1970                path: entry.path.clone(),
1971                is_ignored: entry.is_ignored,
1972                scan_id,
1973            },
1974            &(),
1975        );
1976
1977        entry
1978    }
1979
1980    #[must_use = "Changed paths must be used for diffing later"]
1981    fn build_repo(&mut self, parent_path: Arc<Path>, fs: &dyn Fs) -> Option<Vec<Arc<Path>>> {
1982        let abs_path = self.abs_path.join(&parent_path);
1983        let work_dir: Arc<Path> = parent_path.parent().unwrap().into();
1984
1985        // Guard against repositories inside the repository metadata
1986        if work_dir
1987            .components()
1988            .find(|component| component.as_os_str() == *DOT_GIT)
1989            .is_some()
1990        {
1991            return None;
1992        };
1993
1994        let work_dir_id = self
1995            .entry_for_path(work_dir.clone())
1996            .map(|entry| entry.id)?;
1997
1998        if self.git_repositories.get(&work_dir_id).is_some() {
1999            return None;
2000        }
2001
2002        let repo = fs.open_repo(abs_path.as_path())?;
2003        let work_directory = RepositoryWorkDirectory(work_dir.clone());
2004
2005        let repo_lock = repo.lock();
2006
2007        self.repository_entries.insert(
2008            work_directory.clone(),
2009            RepositoryEntry {
2010                work_directory: work_dir_id.into(),
2011                branch: repo_lock.branch_name().map(Into::into),
2012            },
2013        );
2014
2015        let changed_paths = self.scan_statuses(repo_lock.deref(), &work_directory);
2016
2017        drop(repo_lock);
2018
2019        self.git_repositories.insert(
2020            work_dir_id,
2021            LocalRepositoryEntry {
2022                git_dir_scan_id: 0,
2023                repo_ptr: repo,
2024                git_dir_path: parent_path.clone(),
2025            },
2026        );
2027
2028        Some(changed_paths)
2029    }
2030
2031    #[must_use = "Changed paths must be used for diffing later"]
2032    fn scan_statuses(
2033        &mut self,
2034        repo_ptr: &dyn GitRepository,
2035        work_directory: &RepositoryWorkDirectory,
2036    ) -> Vec<Arc<Path>> {
2037        let mut changes = vec![];
2038        let mut edits = vec![];
2039        for mut entry in self
2040            .descendent_entries(false, false, &work_directory.0)
2041            .cloned()
2042        {
2043            let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2044                continue;
2045            };
2046            let git_file_status = repo_ptr
2047                .status(&RepoPath(repo_path.into()))
2048                .log_err()
2049                .flatten();
2050            if entry.git_status != git_file_status {
2051                entry.git_status = git_file_status;
2052                changes.push(entry.path.clone());
2053                edits.push(Edit::Insert(entry));
2054            }
2055        }
2056
2057        self.entries_by_path.edit(edits, &());
2058        changes
2059    }
2060
2061    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2062        let mut inodes = TreeSet::default();
2063        for ancestor in path.ancestors().skip(1) {
2064            if let Some(entry) = self.entry_for_path(ancestor) {
2065                inodes.insert(entry.inode);
2066            }
2067        }
2068        inodes
2069    }
2070
2071    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2072        let mut new_ignores = Vec::new();
2073        for ancestor in abs_path.ancestors().skip(1) {
2074            if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2075                new_ignores.push((ancestor, Some(ignore.clone())));
2076            } else {
2077                new_ignores.push((ancestor, None));
2078            }
2079        }
2080
2081        let mut ignore_stack = IgnoreStack::none();
2082        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2083            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2084                ignore_stack = IgnoreStack::all();
2085                break;
2086            } else if let Some(ignore) = ignore {
2087                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2088            }
2089        }
2090
2091        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2092            ignore_stack = IgnoreStack::all();
2093        }
2094
2095        ignore_stack
2096    }
2097}
2098
2099impl BackgroundScannerState {
2100    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2101        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2102            entry.id = removed_entry_id;
2103        } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2104            entry.id = existing_entry.id;
2105        }
2106    }
2107
2108    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2109        self.reuse_entry_id(&mut entry);
2110        self.snapshot.insert_entry(entry, fs)
2111    }
2112
2113    #[must_use = "Changed paths must be used for diffing later"]
2114    fn populate_dir(
2115        &mut self,
2116        parent_path: Arc<Path>,
2117        entries: impl IntoIterator<Item = Entry>,
2118        ignore: Option<Arc<Gitignore>>,
2119        fs: &dyn Fs,
2120    ) -> Option<Vec<Arc<Path>>> {
2121        let mut parent_entry = if let Some(parent_entry) = self
2122            .snapshot
2123            .entries_by_path
2124            .get(&PathKey(parent_path.clone()), &())
2125        {
2126            parent_entry.clone()
2127        } else {
2128            log::warn!(
2129                "populating a directory {:?} that has been removed",
2130                parent_path
2131            );
2132            return None;
2133        };
2134
2135        match parent_entry.kind {
2136            EntryKind::PendingDir => {
2137                parent_entry.kind = EntryKind::Dir;
2138            }
2139            EntryKind::Dir => {}
2140            _ => return None,
2141        }
2142
2143        if let Some(ignore) = ignore {
2144            let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2145            self.snapshot
2146                .ignores_by_parent_abs_path
2147                .insert(abs_parent_path, (ignore, false));
2148        }
2149
2150        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2151        let mut entries_by_id_edits = Vec::new();
2152
2153        for mut entry in entries {
2154            self.reuse_entry_id(&mut entry);
2155            entries_by_id_edits.push(Edit::Insert(PathEntry {
2156                id: entry.id,
2157                path: entry.path.clone(),
2158                is_ignored: entry.is_ignored,
2159                scan_id: self.snapshot.scan_id,
2160            }));
2161            entries_by_path_edits.push(Edit::Insert(entry));
2162        }
2163
2164        self.snapshot
2165            .entries_by_path
2166            .edit(entries_by_path_edits, &());
2167        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2168
2169        if parent_path.file_name() == Some(&DOT_GIT) {
2170            return self.snapshot.build_repo(parent_path, fs);
2171        }
2172        None
2173    }
2174
2175    fn remove_path(&mut self, path: &Path) {
2176        let mut new_entries;
2177        let removed_entries;
2178        {
2179            let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2180            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2181            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2182            new_entries.push_tree(cursor.suffix(&()), &());
2183        }
2184        self.snapshot.entries_by_path = new_entries;
2185
2186        let mut entries_by_id_edits = Vec::new();
2187        for entry in removed_entries.cursor::<()>() {
2188            let removed_entry_id = self
2189                .removed_entry_ids
2190                .entry(entry.inode)
2191                .or_insert(entry.id);
2192            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2193            entries_by_id_edits.push(Edit::Remove(entry.id));
2194        }
2195        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2196
2197        if path.file_name() == Some(&GITIGNORE) {
2198            let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2199            if let Some((_, needs_update)) = self
2200                .snapshot
2201                .ignores_by_parent_abs_path
2202                .get_mut(abs_parent_path.as_path())
2203            {
2204                *needs_update = true;
2205            }
2206        }
2207    }
2208}
2209
2210async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2211    let contents = fs.load(abs_path).await?;
2212    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2213    let mut builder = GitignoreBuilder::new(parent);
2214    for line in contents.lines() {
2215        builder.add_line(Some(abs_path.into()), line)?;
2216    }
2217    Ok(builder.build()?)
2218}
2219
2220impl WorktreeId {
2221    pub fn from_usize(handle_id: usize) -> Self {
2222        Self(handle_id)
2223    }
2224
2225    pub(crate) fn from_proto(id: u64) -> Self {
2226        Self(id as usize)
2227    }
2228
2229    pub fn to_proto(&self) -> u64 {
2230        self.0 as u64
2231    }
2232
2233    pub fn to_usize(&self) -> usize {
2234        self.0
2235    }
2236}
2237
2238impl fmt::Display for WorktreeId {
2239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2240        self.0.fmt(f)
2241    }
2242}
2243
2244impl Deref for Worktree {
2245    type Target = Snapshot;
2246
2247    fn deref(&self) -> &Self::Target {
2248        match self {
2249            Worktree::Local(worktree) => &worktree.snapshot,
2250            Worktree::Remote(worktree) => &worktree.snapshot,
2251        }
2252    }
2253}
2254
2255impl Deref for LocalWorktree {
2256    type Target = LocalSnapshot;
2257
2258    fn deref(&self) -> &Self::Target {
2259        &self.snapshot
2260    }
2261}
2262
2263impl Deref for RemoteWorktree {
2264    type Target = Snapshot;
2265
2266    fn deref(&self) -> &Self::Target {
2267        &self.snapshot
2268    }
2269}
2270
2271impl fmt::Debug for LocalWorktree {
2272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2273        self.snapshot.fmt(f)
2274    }
2275}
2276
2277impl fmt::Debug for Snapshot {
2278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2279        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2280        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2281
2282        impl<'a> fmt::Debug for EntriesByPath<'a> {
2283            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2284                f.debug_map()
2285                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2286                    .finish()
2287            }
2288        }
2289
2290        impl<'a> fmt::Debug for EntriesById<'a> {
2291            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2292                f.debug_list().entries(self.0.iter()).finish()
2293            }
2294        }
2295
2296        f.debug_struct("Snapshot")
2297            .field("id", &self.id)
2298            .field("root_name", &self.root_name)
2299            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2300            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2301            .finish()
2302    }
2303}
2304
2305#[derive(Clone, PartialEq)]
2306pub struct File {
2307    pub worktree: ModelHandle<Worktree>,
2308    pub path: Arc<Path>,
2309    pub mtime: SystemTime,
2310    pub(crate) entry_id: ProjectEntryId,
2311    pub(crate) is_local: bool,
2312    pub(crate) is_deleted: bool,
2313}
2314
2315impl language::File for File {
2316    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2317        if self.is_local {
2318            Some(self)
2319        } else {
2320            None
2321        }
2322    }
2323
2324    fn mtime(&self) -> SystemTime {
2325        self.mtime
2326    }
2327
2328    fn path(&self) -> &Arc<Path> {
2329        &self.path
2330    }
2331
2332    fn full_path(&self, cx: &AppContext) -> PathBuf {
2333        let mut full_path = PathBuf::new();
2334        let worktree = self.worktree.read(cx);
2335
2336        if worktree.is_visible() {
2337            full_path.push(worktree.root_name());
2338        } else {
2339            let path = worktree.abs_path();
2340
2341            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2342                full_path.push("~");
2343                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2344            } else {
2345                full_path.push(path)
2346            }
2347        }
2348
2349        if self.path.components().next().is_some() {
2350            full_path.push(&self.path);
2351        }
2352
2353        full_path
2354    }
2355
2356    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2357    /// of its worktree, then this method will return the name of the worktree itself.
2358    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2359        self.path
2360            .file_name()
2361            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2362    }
2363
2364    fn is_deleted(&self) -> bool {
2365        self.is_deleted
2366    }
2367
2368    fn as_any(&self) -> &dyn Any {
2369        self
2370    }
2371
2372    fn to_proto(&self) -> rpc::proto::File {
2373        rpc::proto::File {
2374            worktree_id: self.worktree.id() as u64,
2375            entry_id: self.entry_id.to_proto(),
2376            path: self.path.to_string_lossy().into(),
2377            mtime: Some(self.mtime.into()),
2378            is_deleted: self.is_deleted,
2379        }
2380    }
2381}
2382
2383impl language::LocalFile for File {
2384    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2385        self.worktree
2386            .read(cx)
2387            .as_local()
2388            .unwrap()
2389            .abs_path
2390            .join(&self.path)
2391    }
2392
2393    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2394        let worktree = self.worktree.read(cx).as_local().unwrap();
2395        let abs_path = worktree.absolutize(&self.path);
2396        let fs = worktree.fs.clone();
2397        cx.background()
2398            .spawn(async move { fs.load(&abs_path).await })
2399    }
2400
2401    fn buffer_reloaded(
2402        &self,
2403        buffer_id: u64,
2404        version: &clock::Global,
2405        fingerprint: RopeFingerprint,
2406        line_ending: LineEnding,
2407        mtime: SystemTime,
2408        cx: &mut AppContext,
2409    ) {
2410        let worktree = self.worktree.read(cx).as_local().unwrap();
2411        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2412            worktree
2413                .client
2414                .send(proto::BufferReloaded {
2415                    project_id,
2416                    buffer_id,
2417                    version: serialize_version(version),
2418                    mtime: Some(mtime.into()),
2419                    fingerprint: serialize_fingerprint(fingerprint),
2420                    line_ending: serialize_line_ending(line_ending) as i32,
2421                })
2422                .log_err();
2423        }
2424    }
2425}
2426
2427impl File {
2428    pub fn from_proto(
2429        proto: rpc::proto::File,
2430        worktree: ModelHandle<Worktree>,
2431        cx: &AppContext,
2432    ) -> Result<Self> {
2433        let worktree_id = worktree
2434            .read(cx)
2435            .as_remote()
2436            .ok_or_else(|| anyhow!("not remote"))?
2437            .id();
2438
2439        if worktree_id.to_proto() != proto.worktree_id {
2440            return Err(anyhow!("worktree id does not match file"));
2441        }
2442
2443        Ok(Self {
2444            worktree,
2445            path: Path::new(&proto.path).into(),
2446            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2447            entry_id: ProjectEntryId::from_proto(proto.entry_id),
2448            is_local: false,
2449            is_deleted: proto.is_deleted,
2450        })
2451    }
2452
2453    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2454        file.and_then(|f| f.as_any().downcast_ref())
2455    }
2456
2457    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2458        self.worktree.read(cx).id()
2459    }
2460
2461    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2462        if self.is_deleted {
2463            None
2464        } else {
2465            Some(self.entry_id)
2466        }
2467    }
2468}
2469
2470#[derive(Clone, Debug, PartialEq, Eq)]
2471pub struct Entry {
2472    pub id: ProjectEntryId,
2473    pub kind: EntryKind,
2474    pub path: Arc<Path>,
2475    pub inode: u64,
2476    pub mtime: SystemTime,
2477    pub is_symlink: bool,
2478    pub is_ignored: bool,
2479    pub git_status: Option<GitFileStatus>,
2480}
2481
2482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2483pub enum EntryKind {
2484    PendingDir,
2485    Dir,
2486    File(CharBag),
2487}
2488
2489#[derive(Clone, Copy, Debug)]
2490pub enum PathChange {
2491    /// A filesystem entry was was created.
2492    Added,
2493    /// A filesystem entry was removed.
2494    Removed,
2495    /// A filesystem entry was updated.
2496    Updated,
2497    /// A filesystem entry was either updated or added. We don't know
2498    /// whether or not it already existed, because the path had not
2499    /// been loaded before the event.
2500    AddedOrUpdated,
2501    /// A filesystem entry was found during the initial scan of the worktree.
2502    Loaded,
2503}
2504
2505pub struct GitRepositoryChange {
2506    /// The previous state of the repository, if it already existed.
2507    pub old_repository: Option<RepositoryEntry>,
2508}
2509
2510pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
2511pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
2512
2513impl Entry {
2514    fn new(
2515        path: Arc<Path>,
2516        metadata: &fs::Metadata,
2517        next_entry_id: &AtomicUsize,
2518        root_char_bag: CharBag,
2519    ) -> Self {
2520        Self {
2521            id: ProjectEntryId::new(next_entry_id),
2522            kind: if metadata.is_dir {
2523                EntryKind::PendingDir
2524            } else {
2525                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2526            },
2527            path,
2528            inode: metadata.inode,
2529            mtime: metadata.mtime,
2530            is_symlink: metadata.is_symlink,
2531            is_ignored: false,
2532            git_status: None,
2533        }
2534    }
2535
2536    pub fn is_dir(&self) -> bool {
2537        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2538    }
2539
2540    pub fn is_file(&self) -> bool {
2541        matches!(self.kind, EntryKind::File(_))
2542    }
2543
2544    pub fn git_status(&self) -> Option<GitFileStatus> {
2545        self.git_status /*.status() */
2546    }
2547}
2548
2549impl sum_tree::Item for Entry {
2550    type Summary = EntrySummary;
2551
2552    fn summary(&self) -> Self::Summary {
2553        let visible_count = if self.is_ignored { 0 } else { 1 };
2554        let file_count;
2555        let visible_file_count;
2556        if self.is_file() {
2557            file_count = 1;
2558            visible_file_count = visible_count;
2559        } else {
2560            file_count = 0;
2561            visible_file_count = 0;
2562        }
2563
2564        let mut statuses = GitStatuses::default();
2565        match self.git_status {
2566            Some(status) => match status {
2567                GitFileStatus::Added => statuses.added = 1,
2568                GitFileStatus::Modified => statuses.modified = 1,
2569                GitFileStatus::Conflict => statuses.conflict = 1,
2570            },
2571            None => {}
2572        }
2573
2574        EntrySummary {
2575            max_path: self.path.clone(),
2576            count: 1,
2577            visible_count,
2578            file_count,
2579            visible_file_count,
2580            statuses,
2581        }
2582    }
2583}
2584
2585impl sum_tree::KeyedItem for Entry {
2586    type Key = PathKey;
2587
2588    fn key(&self) -> Self::Key {
2589        PathKey(self.path.clone())
2590    }
2591}
2592
2593#[derive(Clone, Debug)]
2594pub struct EntrySummary {
2595    max_path: Arc<Path>,
2596    count: usize,
2597    visible_count: usize,
2598    file_count: usize,
2599    visible_file_count: usize,
2600    statuses: GitStatuses,
2601}
2602
2603impl Default for EntrySummary {
2604    fn default() -> Self {
2605        Self {
2606            max_path: Arc::from(Path::new("")),
2607            count: 0,
2608            visible_count: 0,
2609            file_count: 0,
2610            visible_file_count: 0,
2611            statuses: Default::default(),
2612        }
2613    }
2614}
2615
2616impl sum_tree::Summary for EntrySummary {
2617    type Context = ();
2618
2619    fn add_summary(&mut self, rhs: &Self, _: &()) {
2620        self.max_path = rhs.max_path.clone();
2621        self.count += rhs.count;
2622        self.visible_count += rhs.visible_count;
2623        self.file_count += rhs.file_count;
2624        self.visible_file_count += rhs.visible_file_count;
2625        self.statuses += rhs.statuses;
2626    }
2627}
2628
2629#[derive(Clone, Debug)]
2630struct PathEntry {
2631    id: ProjectEntryId,
2632    path: Arc<Path>,
2633    is_ignored: bool,
2634    scan_id: usize,
2635}
2636
2637impl sum_tree::Item for PathEntry {
2638    type Summary = PathEntrySummary;
2639
2640    fn summary(&self) -> Self::Summary {
2641        PathEntrySummary { max_id: self.id }
2642    }
2643}
2644
2645impl sum_tree::KeyedItem for PathEntry {
2646    type Key = ProjectEntryId;
2647
2648    fn key(&self) -> Self::Key {
2649        self.id
2650    }
2651}
2652
2653#[derive(Clone, Debug, Default)]
2654struct PathEntrySummary {
2655    max_id: ProjectEntryId,
2656}
2657
2658impl sum_tree::Summary for PathEntrySummary {
2659    type Context = ();
2660
2661    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2662        self.max_id = summary.max_id;
2663    }
2664}
2665
2666impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2667    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2668        *self = summary.max_id;
2669    }
2670}
2671
2672#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2673pub struct PathKey(Arc<Path>);
2674
2675impl Default for PathKey {
2676    fn default() -> Self {
2677        Self(Path::new("").into())
2678    }
2679}
2680
2681impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2682    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2683        self.0 = summary.max_path.clone();
2684    }
2685}
2686
2687struct BackgroundScanner {
2688    state: Mutex<BackgroundScannerState>,
2689    fs: Arc<dyn Fs>,
2690    status_updates_tx: UnboundedSender<ScanState>,
2691    executor: Arc<executor::Background>,
2692    refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2693    next_entry_id: Arc<AtomicUsize>,
2694    phase: BackgroundScannerPhase,
2695}
2696
2697#[derive(PartialEq)]
2698enum BackgroundScannerPhase {
2699    InitialScan,
2700    EventsReceivedDuringInitialScan,
2701    Events,
2702}
2703
2704impl BackgroundScanner {
2705    fn new(
2706        snapshot: LocalSnapshot,
2707        next_entry_id: Arc<AtomicUsize>,
2708        fs: Arc<dyn Fs>,
2709        status_updates_tx: UnboundedSender<ScanState>,
2710        executor: Arc<executor::Background>,
2711        refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2712    ) -> Self {
2713        Self {
2714            fs,
2715            status_updates_tx,
2716            executor,
2717            refresh_requests_rx,
2718            next_entry_id,
2719            state: Mutex::new(BackgroundScannerState {
2720                prev_snapshot: snapshot.snapshot.clone(),
2721                snapshot,
2722                removed_entry_ids: Default::default(),
2723                changed_paths: Default::default(),
2724            }),
2725            phase: BackgroundScannerPhase::InitialScan,
2726        }
2727    }
2728
2729    async fn run(
2730        &mut self,
2731        mut events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
2732    ) {
2733        use futures::FutureExt as _;
2734
2735        let (root_abs_path, root_inode) = {
2736            let snapshot = &self.state.lock().snapshot;
2737            (
2738                snapshot.abs_path.clone(),
2739                snapshot.root_entry().map(|e| e.inode),
2740            )
2741        };
2742
2743        // Populate ignores above the root.
2744        let ignore_stack;
2745        for ancestor in root_abs_path.ancestors().skip(1) {
2746            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2747            {
2748                self.state
2749                    .lock()
2750                    .snapshot
2751                    .ignores_by_parent_abs_path
2752                    .insert(ancestor.into(), (ignore.into(), false));
2753            }
2754        }
2755        {
2756            let mut state = self.state.lock();
2757            state.snapshot.scan_id += 1;
2758            ignore_stack = state
2759                .snapshot
2760                .ignore_stack_for_abs_path(&root_abs_path, true);
2761            if ignore_stack.is_all() {
2762                if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
2763                    root_entry.is_ignored = true;
2764                    state.insert_entry(root_entry, self.fs.as_ref());
2765                }
2766            }
2767        };
2768
2769        // Perform an initial scan of the directory.
2770        let (scan_job_tx, scan_job_rx) = channel::unbounded();
2771        smol::block_on(scan_job_tx.send(ScanJob {
2772            abs_path: root_abs_path,
2773            path: Arc::from(Path::new("")),
2774            ignore_stack,
2775            ancestor_inodes: TreeSet::from_ordered_entries(root_inode),
2776            scan_queue: scan_job_tx.clone(),
2777        }))
2778        .unwrap();
2779        drop(scan_job_tx);
2780        self.scan_dirs(true, scan_job_rx).await;
2781        {
2782            let mut state = self.state.lock();
2783            state.snapshot.completed_scan_id = state.snapshot.scan_id;
2784        }
2785
2786        self.send_status_update(false, None);
2787
2788        // Process any any FS events that occurred while performing the initial scan.
2789        // For these events, update events cannot be as precise, because we didn't
2790        // have the previous state loaded yet.
2791        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
2792        if let Poll::Ready(Some(events)) = futures::poll!(events_rx.next()) {
2793            let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2794            while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2795                paths.extend(more_events.into_iter().map(|e| e.path));
2796            }
2797            self.process_events(paths).await;
2798        }
2799
2800        // Continue processing events until the worktree is dropped.
2801        self.phase = BackgroundScannerPhase::Events;
2802        loop {
2803            select_biased! {
2804                // Process any path refresh requests from the worktree. Prioritize
2805                // these before handling changes reported by the filesystem.
2806                request = self.refresh_requests_rx.recv().fuse() => {
2807                    let Ok((paths, barrier)) = request else { break };
2808                    if !self.process_refresh_request(paths.clone(), barrier).await {
2809                        return;
2810                    }
2811                }
2812
2813                events = events_rx.next().fuse() => {
2814                    let Some(events) = events else { break };
2815                    let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2816                    while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2817                        paths.extend(more_events.into_iter().map(|e| e.path));
2818                    }
2819                    self.process_events(paths.clone()).await;
2820                }
2821            }
2822        }
2823    }
2824
2825    async fn process_refresh_request(&self, paths: Vec<PathBuf>, barrier: barrier::Sender) -> bool {
2826        self.reload_entries_for_paths(paths, None).await;
2827        self.send_status_update(false, Some(barrier))
2828    }
2829
2830    async fn process_events(&mut self, paths: Vec<PathBuf>) {
2831        let (scan_job_tx, scan_job_rx) = channel::unbounded();
2832        let paths = self
2833            .reload_entries_for_paths(paths, Some(scan_job_tx.clone()))
2834            .await;
2835        drop(scan_job_tx);
2836        self.scan_dirs(false, scan_job_rx).await;
2837
2838        self.update_ignore_statuses().await;
2839
2840        {
2841            let mut state = self.state.lock();
2842
2843            if let Some(paths) = paths {
2844                for path in paths {
2845                    self.reload_git_repo(&path, &mut *state, self.fs.as_ref());
2846                }
2847            }
2848
2849            let mut snapshot = &mut state.snapshot;
2850
2851            let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2852            git_repositories.retain(|work_directory_id, _| {
2853                snapshot
2854                    .entry_for_id(*work_directory_id)
2855                    .map_or(false, |entry| {
2856                        snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2857                    })
2858            });
2859            snapshot.git_repositories = git_repositories;
2860
2861            let mut git_repository_entries = mem::take(&mut snapshot.snapshot.repository_entries);
2862            git_repository_entries.retain(|_, entry| {
2863                snapshot
2864                    .git_repositories
2865                    .get(&entry.work_directory.0)
2866                    .is_some()
2867            });
2868            snapshot.snapshot.repository_entries = git_repository_entries;
2869            snapshot.completed_scan_id = snapshot.scan_id;
2870        }
2871
2872        self.send_status_update(false, None);
2873    }
2874
2875    async fn scan_dirs(
2876        &self,
2877        enable_progress_updates: bool,
2878        scan_jobs_rx: channel::Receiver<ScanJob>,
2879    ) {
2880        use futures::FutureExt as _;
2881
2882        if self
2883            .status_updates_tx
2884            .unbounded_send(ScanState::Started)
2885            .is_err()
2886        {
2887            return;
2888        }
2889
2890        let progress_update_count = AtomicUsize::new(0);
2891        self.executor
2892            .scoped(|scope| {
2893                for _ in 0..self.executor.num_cpus() {
2894                    scope.spawn(async {
2895                        let mut last_progress_update_count = 0;
2896                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
2897                        futures::pin_mut!(progress_update_timer);
2898
2899                        loop {
2900                            select_biased! {
2901                                // Process any path refresh requests before moving on to process
2902                                // the scan queue, so that user operations are prioritized.
2903                                request = self.refresh_requests_rx.recv().fuse() => {
2904                                    let Ok((paths, barrier)) = request else { break };
2905                                    if !self.process_refresh_request(paths, barrier).await {
2906                                        return;
2907                                    }
2908                                }
2909
2910                                // Send periodic progress updates to the worktree. Use an atomic counter
2911                                // to ensure that only one of the workers sends a progress update after
2912                                // the update interval elapses.
2913                                _ = progress_update_timer => {
2914                                    match progress_update_count.compare_exchange(
2915                                        last_progress_update_count,
2916                                        last_progress_update_count + 1,
2917                                        SeqCst,
2918                                        SeqCst
2919                                    ) {
2920                                        Ok(_) => {
2921                                            last_progress_update_count += 1;
2922                                            self.send_status_update(true, None);
2923                                        }
2924                                        Err(count) => {
2925                                            last_progress_update_count = count;
2926                                        }
2927                                    }
2928                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
2929                                }
2930
2931                                // Recursively load directories from the file system.
2932                                job = scan_jobs_rx.recv().fuse() => {
2933                                    let Ok(job) = job else { break };
2934                                    if let Err(err) = self.scan_dir(&job).await {
2935                                        if job.path.as_ref() != Path::new("") {
2936                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
2937                                        }
2938                                    }
2939                                }
2940                            }
2941                        }
2942                    })
2943                }
2944            })
2945            .await;
2946    }
2947
2948    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
2949        let mut state = self.state.lock();
2950        if state.changed_paths.is_empty() && scanning {
2951            return true;
2952        }
2953
2954        let new_snapshot = state.snapshot.clone();
2955        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
2956        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
2957        state.changed_paths.clear();
2958
2959        self.status_updates_tx
2960            .unbounded_send(ScanState::Updated {
2961                snapshot: new_snapshot,
2962                changes,
2963                scanning,
2964                barrier,
2965            })
2966            .is_ok()
2967    }
2968
2969    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
2970        let mut new_entries: Vec<Entry> = Vec::new();
2971        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2972        let mut ignore_stack = job.ignore_stack.clone();
2973        let mut new_ignore = None;
2974        let (root_abs_path, root_char_bag, next_entry_id, repository) = {
2975            let snapshot = &self.state.lock().snapshot;
2976            (
2977                snapshot.abs_path().clone(),
2978                snapshot.root_char_bag,
2979                self.next_entry_id.clone(),
2980                snapshot
2981                    .local_repo_for_path(&job.path)
2982                    .map(|(work_dir, repo)| (work_dir, repo.clone())),
2983            )
2984        };
2985
2986        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2987        while let Some(child_abs_path) = child_paths.next().await {
2988            let child_abs_path: Arc<Path> = match child_abs_path {
2989                Ok(child_abs_path) => child_abs_path.into(),
2990                Err(error) => {
2991                    log::error!("error processing entry {:?}", error);
2992                    continue;
2993                }
2994            };
2995
2996            let child_name = child_abs_path.file_name().unwrap();
2997            let child_path: Arc<Path> = job.path.join(child_name).into();
2998            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2999                Ok(Some(metadata)) => metadata,
3000                Ok(None) => continue,
3001                Err(err) => {
3002                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
3003                    continue;
3004                }
3005            };
3006
3007            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3008            if child_name == *GITIGNORE {
3009                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3010                    Ok(ignore) => {
3011                        let ignore = Arc::new(ignore);
3012                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3013                        new_ignore = Some(ignore);
3014                    }
3015                    Err(error) => {
3016                        log::error!(
3017                            "error loading .gitignore file {:?} - {:?}",
3018                            child_name,
3019                            error
3020                        );
3021                    }
3022                }
3023
3024                // Update ignore status of any child entries we've already processed to reflect the
3025                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3026                // there should rarely be too numerous. Update the ignore stack associated with any
3027                // new jobs as well.
3028                let mut new_jobs = new_jobs.iter_mut();
3029                for entry in &mut new_entries {
3030                    let entry_abs_path = root_abs_path.join(&entry.path);
3031                    entry.is_ignored =
3032                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3033
3034                    if entry.is_dir() {
3035                        if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
3036                            job.ignore_stack = if entry.is_ignored {
3037                                IgnoreStack::all()
3038                            } else {
3039                                ignore_stack.clone()
3040                            };
3041                        }
3042                    }
3043                }
3044            }
3045
3046            let mut child_entry = Entry::new(
3047                child_path.clone(),
3048                &child_metadata,
3049                &next_entry_id,
3050                root_char_bag,
3051            );
3052
3053            if child_entry.is_dir() {
3054                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3055                child_entry.is_ignored = is_ignored;
3056
3057                // Avoid recursing until crash in the case of a recursive symlink
3058                if !job.ancestor_inodes.contains(&child_entry.inode) {
3059                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3060                    ancestor_inodes.insert(child_entry.inode);
3061
3062                    new_jobs.push(Some(ScanJob {
3063                        abs_path: child_abs_path,
3064                        path: child_path,
3065                        ignore_stack: if is_ignored {
3066                            IgnoreStack::all()
3067                        } else {
3068                            ignore_stack.clone()
3069                        },
3070                        ancestor_inodes,
3071                        scan_queue: job.scan_queue.clone(),
3072                    }));
3073                } else {
3074                    new_jobs.push(None);
3075                }
3076            } else {
3077                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3078                if !child_entry.is_ignored {
3079                    if let Some((repo_path, repo)) = &repository {
3080                        if let Ok(path) = child_path.strip_prefix(&repo_path.0) {
3081                            child_entry.git_status = repo
3082                                .repo_ptr
3083                                .lock()
3084                                .status(&RepoPath(path.into()))
3085                                .log_err()
3086                                .flatten();
3087                        }
3088                    }
3089                }
3090            }
3091
3092            new_entries.push(child_entry);
3093        }
3094
3095        {
3096            let mut state = self.state.lock();
3097            let changed_paths =
3098                state.populate_dir(job.path.clone(), new_entries, new_ignore, self.fs.as_ref());
3099            if let Err(ix) = state.changed_paths.binary_search(&job.path) {
3100                state.changed_paths.insert(ix, job.path.clone());
3101            }
3102            if let Some(changed_paths) = changed_paths {
3103                util::extend_sorted(
3104                    &mut state.changed_paths,
3105                    changed_paths,
3106                    usize::MAX,
3107                    Ord::cmp,
3108                )
3109            }
3110        }
3111
3112        for new_job in new_jobs {
3113            if let Some(new_job) = new_job {
3114                job.scan_queue.send(new_job).await.unwrap();
3115            }
3116        }
3117
3118        Ok(())
3119    }
3120
3121    async fn reload_entries_for_paths(
3122        &self,
3123        mut abs_paths: Vec<PathBuf>,
3124        scan_queue_tx: Option<Sender<ScanJob>>,
3125    ) -> Option<Vec<Arc<Path>>> {
3126        let doing_recursive_update = scan_queue_tx.is_some();
3127
3128        abs_paths.sort_unstable();
3129        abs_paths.dedup_by(|a, b| a.starts_with(&b));
3130
3131        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3132        let root_canonical_path = self.fs.canonicalize(&root_abs_path).await.log_err()?;
3133        let metadata = futures::future::join_all(
3134            abs_paths
3135                .iter()
3136                .map(|abs_path| self.fs.metadata(&abs_path))
3137                .collect::<Vec<_>>(),
3138        )
3139        .await;
3140
3141        let mut state = self.state.lock();
3142        let snapshot = &mut state.snapshot;
3143        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3144        snapshot.scan_id += 1;
3145        if is_idle && !doing_recursive_update {
3146            snapshot.completed_scan_id = snapshot.scan_id;
3147        }
3148
3149        // Remove any entries for paths that no longer exist or are being recursively
3150        // refreshed. Do this before adding any new entries, so that renames can be
3151        // detected regardless of the order of the paths.
3152        let mut event_paths = Vec::<Arc<Path>>::with_capacity(abs_paths.len());
3153        for (abs_path, metadata) in abs_paths.iter().zip(metadata.iter()) {
3154            if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3155                if matches!(metadata, Ok(None)) || doing_recursive_update {
3156                    state.remove_path(path);
3157                }
3158                event_paths.push(path.into());
3159            } else {
3160                log::error!(
3161                    "unexpected event {:?} for root path {:?}",
3162                    abs_path,
3163                    root_canonical_path
3164                );
3165            }
3166        }
3167
3168        for (path, metadata) in event_paths.iter().cloned().zip(metadata.into_iter()) {
3169            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3170
3171            match metadata {
3172                Ok(Some(metadata)) => {
3173                    let ignore_stack = state
3174                        .snapshot
3175                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
3176
3177                    let mut fs_entry = Entry::new(
3178                        path.clone(),
3179                        &metadata,
3180                        self.next_entry_id.as_ref(),
3181                        state.snapshot.root_char_bag,
3182                    );
3183                    fs_entry.is_ignored = ignore_stack.is_all();
3184
3185                    if !fs_entry.is_ignored {
3186                        if !fs_entry.is_dir() {
3187                            if let Some((work_dir, repo)) =
3188                                state.snapshot.local_repo_for_path(&path)
3189                            {
3190                                if let Ok(path) = path.strip_prefix(work_dir.0) {
3191                                    fs_entry.git_status = repo
3192                                        .repo_ptr
3193                                        .lock()
3194                                        .status(&RepoPath(path.into()))
3195                                        .log_err()
3196                                        .flatten()
3197                                }
3198                            }
3199                        }
3200                    }
3201
3202                    state.insert_entry(fs_entry, self.fs.as_ref());
3203
3204                    if let Some(scan_queue_tx) = &scan_queue_tx {
3205                        let mut ancestor_inodes = state.snapshot.ancestor_inodes_for_path(&path);
3206                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
3207                            ancestor_inodes.insert(metadata.inode);
3208                            smol::block_on(scan_queue_tx.send(ScanJob {
3209                                abs_path,
3210                                path,
3211                                ignore_stack,
3212                                ancestor_inodes,
3213                                scan_queue: scan_queue_tx.clone(),
3214                            }))
3215                            .unwrap();
3216                        }
3217                    }
3218                }
3219                Ok(None) => {
3220                    self.remove_repo_path(&path, &mut state.snapshot);
3221                }
3222                Err(err) => {
3223                    // TODO - create a special 'error' entry in the entries tree to mark this
3224                    log::error!("error reading file on event {:?}", err);
3225                }
3226            }
3227        }
3228
3229        util::extend_sorted(
3230            &mut state.changed_paths,
3231            event_paths.iter().cloned(),
3232            usize::MAX,
3233            Ord::cmp,
3234        );
3235
3236        Some(event_paths)
3237    }
3238
3239    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
3240        if !path
3241            .components()
3242            .any(|component| component.as_os_str() == *DOT_GIT)
3243        {
3244            if let Some(repository) = snapshot.repository_for_work_directory(path) {
3245                let entry = repository.work_directory.0;
3246                snapshot.git_repositories.remove(&entry);
3247                snapshot
3248                    .snapshot
3249                    .repository_entries
3250                    .remove(&RepositoryWorkDirectory(path.into()));
3251                return Some(());
3252            }
3253        }
3254
3255        // TODO statuses
3256        // Track when a .git is removed and iterate over the file system there
3257
3258        Some(())
3259    }
3260
3261    fn reload_git_repo(
3262        &self,
3263        path: &Path,
3264        state: &mut BackgroundScannerState,
3265        fs: &dyn Fs,
3266    ) -> Option<()> {
3267        let scan_id = state.snapshot.scan_id;
3268
3269        if path
3270            .components()
3271            .any(|component| component.as_os_str() == *DOT_GIT)
3272        {
3273            let (entry_id, repo_ptr) = {
3274                let Some((entry_id, repo)) = state.snapshot.repo_for_metadata(&path) else {
3275                    let dot_git_dir = path.ancestors()
3276                    .skip_while(|ancestor| ancestor.file_name() != Some(&*DOT_GIT))
3277                    .next()?;
3278
3279                    let changed_paths =  state.snapshot.build_repo(dot_git_dir.into(), fs);
3280                    if let Some(changed_paths) = changed_paths {
3281                        util::extend_sorted(
3282                            &mut state.changed_paths,
3283                            changed_paths,
3284                            usize::MAX,
3285                            Ord::cmp,
3286                        );
3287                    }
3288
3289                    return None;
3290                };
3291                if repo.git_dir_scan_id == scan_id {
3292                    return None;
3293                }
3294
3295                (*entry_id, repo.repo_ptr.to_owned())
3296            };
3297
3298            let work_dir = state
3299                .snapshot
3300                .entry_for_id(entry_id)
3301                .map(|entry| RepositoryWorkDirectory(entry.path.clone()))?;
3302
3303            let repo = repo_ptr.lock();
3304            repo.reload_index();
3305            let branch = repo.branch_name();
3306
3307            state.snapshot.git_repositories.update(&entry_id, |entry| {
3308                entry.git_dir_scan_id = scan_id;
3309            });
3310
3311            state
3312                .snapshot
3313                .snapshot
3314                .repository_entries
3315                .update(&work_dir, |entry| {
3316                    entry.branch = branch.map(Into::into);
3317                });
3318
3319            let changed_paths = state.snapshot.scan_statuses(repo.deref(), &work_dir);
3320
3321            util::extend_sorted(
3322                &mut state.changed_paths,
3323                changed_paths,
3324                usize::MAX,
3325                Ord::cmp,
3326            )
3327        }
3328
3329        Some(())
3330    }
3331
3332    async fn update_ignore_statuses(&self) {
3333        use futures::FutureExt as _;
3334
3335        let mut snapshot = self.state.lock().snapshot.clone();
3336        let mut ignores_to_update = Vec::new();
3337        let mut ignores_to_delete = Vec::new();
3338        let abs_path = snapshot.abs_path.clone();
3339        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
3340            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
3341                if *needs_update {
3342                    *needs_update = false;
3343                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
3344                        ignores_to_update.push(parent_abs_path.clone());
3345                    }
3346                }
3347
3348                let ignore_path = parent_path.join(&*GITIGNORE);
3349                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
3350                    ignores_to_delete.push(parent_abs_path.clone());
3351                }
3352            }
3353        }
3354
3355        for parent_abs_path in ignores_to_delete {
3356            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
3357            self.state
3358                .lock()
3359                .snapshot
3360                .ignores_by_parent_abs_path
3361                .remove(&parent_abs_path);
3362        }
3363
3364        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
3365        ignores_to_update.sort_unstable();
3366        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
3367        while let Some(parent_abs_path) = ignores_to_update.next() {
3368            while ignores_to_update
3369                .peek()
3370                .map_or(false, |p| p.starts_with(&parent_abs_path))
3371            {
3372                ignores_to_update.next().unwrap();
3373            }
3374
3375            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
3376            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
3377                abs_path: parent_abs_path,
3378                ignore_stack,
3379                ignore_queue: ignore_queue_tx.clone(),
3380            }))
3381            .unwrap();
3382        }
3383        drop(ignore_queue_tx);
3384
3385        self.executor
3386            .scoped(|scope| {
3387                for _ in 0..self.executor.num_cpus() {
3388                    scope.spawn(async {
3389                        loop {
3390                            select_biased! {
3391                                // Process any path refresh requests before moving on to process
3392                                // the queue of ignore statuses.
3393                                request = self.refresh_requests_rx.recv().fuse() => {
3394                                    let Ok((paths, barrier)) = request else { break };
3395                                    if !self.process_refresh_request(paths, barrier).await {
3396                                        return;
3397                                    }
3398                                }
3399
3400                                // Recursively process directories whose ignores have changed.
3401                                job = ignore_queue_rx.recv().fuse() => {
3402                                    let Ok(job) = job else { break };
3403                                    self.update_ignore_status(job, &snapshot).await;
3404                                }
3405                            }
3406                        }
3407                    });
3408                }
3409            })
3410            .await;
3411    }
3412
3413    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
3414        let mut ignore_stack = job.ignore_stack;
3415        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
3416            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3417        }
3418
3419        let mut entries_by_id_edits = Vec::new();
3420        let mut entries_by_path_edits = Vec::new();
3421        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
3422        for mut entry in snapshot.child_entries(path).cloned() {
3423            let was_ignored = entry.is_ignored;
3424            let abs_path = snapshot.abs_path().join(&entry.path);
3425            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
3426            if entry.is_dir() {
3427                let child_ignore_stack = if entry.is_ignored {
3428                    IgnoreStack::all()
3429                } else {
3430                    ignore_stack.clone()
3431                };
3432                job.ignore_queue
3433                    .send(UpdateIgnoreStatusJob {
3434                        abs_path: abs_path.into(),
3435                        ignore_stack: child_ignore_stack,
3436                        ignore_queue: job.ignore_queue.clone(),
3437                    })
3438                    .await
3439                    .unwrap();
3440            }
3441
3442            if entry.is_ignored != was_ignored {
3443                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
3444                path_entry.scan_id = snapshot.scan_id;
3445                path_entry.is_ignored = entry.is_ignored;
3446                entries_by_id_edits.push(Edit::Insert(path_entry));
3447                entries_by_path_edits.push(Edit::Insert(entry));
3448            }
3449        }
3450
3451        let state = &mut self.state.lock();
3452        for edit in &entries_by_path_edits {
3453            if let Edit::Insert(entry) = edit {
3454                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
3455                    state.changed_paths.insert(ix, entry.path.clone());
3456                }
3457            }
3458        }
3459
3460        state
3461            .snapshot
3462            .entries_by_path
3463            .edit(entries_by_path_edits, &());
3464        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3465    }
3466
3467    fn build_change_set(
3468        &self,
3469        old_snapshot: &Snapshot,
3470        new_snapshot: &Snapshot,
3471        event_paths: &[Arc<Path>],
3472    ) -> UpdatedEntriesSet {
3473        use BackgroundScannerPhase::*;
3474        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
3475
3476        // Identify which paths have changed. Use the known set of changed
3477        // parent paths to optimize the search.
3478        let mut changes = Vec::new();
3479        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
3480        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
3481        old_paths.next(&());
3482        new_paths.next(&());
3483        for path in event_paths {
3484            let path = PathKey(path.clone());
3485            if old_paths.item().map_or(false, |e| e.path < path.0) {
3486                old_paths.seek_forward(&path, Bias::Left, &());
3487            }
3488            if new_paths.item().map_or(false, |e| e.path < path.0) {
3489                new_paths.seek_forward(&path, Bias::Left, &());
3490            }
3491
3492            loop {
3493                match (old_paths.item(), new_paths.item()) {
3494                    (Some(old_entry), Some(new_entry)) => {
3495                        if old_entry.path > path.0
3496                            && new_entry.path > path.0
3497                            && !old_entry.path.starts_with(&path.0)
3498                            && !new_entry.path.starts_with(&path.0)
3499                        {
3500                            break;
3501                        }
3502
3503                        match Ord::cmp(&old_entry.path, &new_entry.path) {
3504                            Ordering::Less => {
3505                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
3506                                old_paths.next(&());
3507                            }
3508                            Ordering::Equal => {
3509                                if self.phase == EventsReceivedDuringInitialScan {
3510                                    // If the worktree was not fully initialized when this event was generated,
3511                                    // we can't know whether this entry was added during the scan or whether
3512                                    // it was merely updated.
3513                                    changes.push((
3514                                        new_entry.path.clone(),
3515                                        new_entry.id,
3516                                        AddedOrUpdated,
3517                                    ));
3518                                } else if old_entry.id != new_entry.id {
3519                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
3520                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
3521                                } else if old_entry != new_entry {
3522                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
3523                                }
3524                                old_paths.next(&());
3525                                new_paths.next(&());
3526                            }
3527                            Ordering::Greater => {
3528                                changes.push((
3529                                    new_entry.path.clone(),
3530                                    new_entry.id,
3531                                    if self.phase == InitialScan {
3532                                        Loaded
3533                                    } else {
3534                                        Added
3535                                    },
3536                                ));
3537                                new_paths.next(&());
3538                            }
3539                        }
3540                    }
3541                    (Some(old_entry), None) => {
3542                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
3543                        old_paths.next(&());
3544                    }
3545                    (None, Some(new_entry)) => {
3546                        changes.push((
3547                            new_entry.path.clone(),
3548                            new_entry.id,
3549                            if self.phase == InitialScan {
3550                                Loaded
3551                            } else {
3552                                Added
3553                            },
3554                        ));
3555                        new_paths.next(&());
3556                    }
3557                    (None, None) => break,
3558                }
3559            }
3560        }
3561
3562        changes.into()
3563    }
3564
3565    async fn progress_timer(&self, running: bool) {
3566        if !running {
3567            return futures::future::pending().await;
3568        }
3569
3570        #[cfg(any(test, feature = "test-support"))]
3571        if self.fs.is_fake() {
3572            return self.executor.simulate_random_delay().await;
3573        }
3574
3575        smol::Timer::after(Duration::from_millis(100)).await;
3576    }
3577}
3578
3579fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
3580    let mut result = root_char_bag;
3581    result.extend(
3582        path.to_string_lossy()
3583            .chars()
3584            .map(|c| c.to_ascii_lowercase()),
3585    );
3586    result
3587}
3588
3589struct ScanJob {
3590    abs_path: Arc<Path>,
3591    path: Arc<Path>,
3592    ignore_stack: Arc<IgnoreStack>,
3593    scan_queue: Sender<ScanJob>,
3594    ancestor_inodes: TreeSet<u64>,
3595}
3596
3597struct UpdateIgnoreStatusJob {
3598    abs_path: Arc<Path>,
3599    ignore_stack: Arc<IgnoreStack>,
3600    ignore_queue: Sender<UpdateIgnoreStatusJob>,
3601}
3602
3603pub trait WorktreeHandle {
3604    #[cfg(any(test, feature = "test-support"))]
3605    fn flush_fs_events<'a>(
3606        &self,
3607        cx: &'a gpui::TestAppContext,
3608    ) -> futures::future::LocalBoxFuture<'a, ()>;
3609}
3610
3611impl WorktreeHandle for ModelHandle<Worktree> {
3612    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
3613    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
3614    // extra directory scans, and emit extra scan-state notifications.
3615    //
3616    // This function mutates the worktree's directory and waits for those mutations to be picked up,
3617    // to ensure that all redundant FS events have already been processed.
3618    #[cfg(any(test, feature = "test-support"))]
3619    fn flush_fs_events<'a>(
3620        &self,
3621        cx: &'a gpui::TestAppContext,
3622    ) -> futures::future::LocalBoxFuture<'a, ()> {
3623        let filename = "fs-event-sentinel";
3624        let tree = self.clone();
3625        let (fs, root_path) = self.read_with(cx, |tree, _| {
3626            let tree = tree.as_local().unwrap();
3627            (tree.fs.clone(), tree.abs_path().clone())
3628        });
3629
3630        async move {
3631            fs.create_file(&root_path.join(filename), Default::default())
3632                .await
3633                .unwrap();
3634            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
3635                .await;
3636
3637            fs.remove_file(&root_path.join(filename), Default::default())
3638                .await
3639                .unwrap();
3640            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
3641                .await;
3642
3643            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3644                .await;
3645        }
3646        .boxed_local()
3647    }
3648}
3649
3650#[derive(Clone, Debug)]
3651struct TraversalProgress<'a> {
3652    max_path: &'a Path,
3653    count: usize,
3654    visible_count: usize,
3655    file_count: usize,
3656    visible_file_count: usize,
3657}
3658
3659impl<'a> TraversalProgress<'a> {
3660    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
3661        match (include_ignored, include_dirs) {
3662            (true, true) => self.count,
3663            (true, false) => self.file_count,
3664            (false, true) => self.visible_count,
3665            (false, false) => self.visible_file_count,
3666        }
3667    }
3668}
3669
3670impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
3671    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3672        self.max_path = summary.max_path.as_ref();
3673        self.count += summary.count;
3674        self.visible_count += summary.visible_count;
3675        self.file_count += summary.file_count;
3676        self.visible_file_count += summary.visible_file_count;
3677    }
3678}
3679
3680impl<'a> Default for TraversalProgress<'a> {
3681    fn default() -> Self {
3682        Self {
3683            max_path: Path::new(""),
3684            count: 0,
3685            visible_count: 0,
3686            file_count: 0,
3687            visible_file_count: 0,
3688        }
3689    }
3690}
3691
3692#[derive(Clone, Debug, Default, Copy)]
3693struct GitStatuses {
3694    added: usize,
3695    modified: usize,
3696    conflict: usize,
3697}
3698
3699impl AddAssign for GitStatuses {
3700    fn add_assign(&mut self, rhs: Self) {
3701        self.added += rhs.added;
3702        self.modified += rhs.modified;
3703        self.conflict += rhs.conflict;
3704    }
3705}
3706
3707impl Sub for GitStatuses {
3708    type Output = GitStatuses;
3709
3710    fn sub(self, rhs: Self) -> Self::Output {
3711        GitStatuses {
3712            added: self.added - rhs.added,
3713            modified: self.modified - rhs.modified,
3714            conflict: self.conflict - rhs.conflict,
3715        }
3716    }
3717}
3718
3719impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
3720    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3721        *self += summary.statuses
3722    }
3723}
3724
3725pub struct Traversal<'a> {
3726    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
3727    include_ignored: bool,
3728    include_dirs: bool,
3729}
3730
3731impl<'a> Traversal<'a> {
3732    pub fn advance(&mut self) -> bool {
3733        self.cursor.seek_forward(
3734            &TraversalTarget::Count {
3735                count: self.end_offset() + 1,
3736                include_dirs: self.include_dirs,
3737                include_ignored: self.include_ignored,
3738            },
3739            Bias::Left,
3740            &(),
3741        )
3742    }
3743
3744    pub fn advance_to_sibling(&mut self) -> bool {
3745        while let Some(entry) = self.cursor.item() {
3746            self.cursor.seek_forward(
3747                &TraversalTarget::PathSuccessor(&entry.path),
3748                Bias::Left,
3749                &(),
3750            );
3751            if let Some(entry) = self.cursor.item() {
3752                if (self.include_dirs || !entry.is_dir())
3753                    && (self.include_ignored || !entry.is_ignored)
3754                {
3755                    return true;
3756                }
3757            }
3758        }
3759        false
3760    }
3761
3762    pub fn entry(&self) -> Option<&'a Entry> {
3763        self.cursor.item()
3764    }
3765
3766    pub fn start_offset(&self) -> usize {
3767        self.cursor
3768            .start()
3769            .count(self.include_dirs, self.include_ignored)
3770    }
3771
3772    pub fn end_offset(&self) -> usize {
3773        self.cursor
3774            .end(&())
3775            .count(self.include_dirs, self.include_ignored)
3776    }
3777}
3778
3779impl<'a> Iterator for Traversal<'a> {
3780    type Item = &'a Entry;
3781
3782    fn next(&mut self) -> Option<Self::Item> {
3783        if let Some(item) = self.entry() {
3784            self.advance();
3785            Some(item)
3786        } else {
3787            None
3788        }
3789    }
3790}
3791
3792#[derive(Debug)]
3793enum TraversalTarget<'a> {
3794    Path(&'a Path),
3795    PathSuccessor(&'a Path),
3796    Count {
3797        count: usize,
3798        include_ignored: bool,
3799        include_dirs: bool,
3800    },
3801}
3802
3803impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3804    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3805        match self {
3806            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3807            TraversalTarget::PathSuccessor(path) => {
3808                if !cursor_location.max_path.starts_with(path) {
3809                    Ordering::Equal
3810                } else {
3811                    Ordering::Greater
3812                }
3813            }
3814            TraversalTarget::Count {
3815                count,
3816                include_dirs,
3817                include_ignored,
3818            } => Ord::cmp(
3819                count,
3820                &cursor_location.count(*include_dirs, *include_ignored),
3821            ),
3822        }
3823    }
3824}
3825
3826impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
3827    for TraversalTarget<'b>
3828{
3829    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
3830        self.cmp(&cursor_location.0, &())
3831    }
3832}
3833
3834struct ChildEntriesIter<'a> {
3835    parent_path: &'a Path,
3836    traversal: Traversal<'a>,
3837}
3838
3839impl<'a> Iterator for ChildEntriesIter<'a> {
3840    type Item = &'a Entry;
3841
3842    fn next(&mut self) -> Option<Self::Item> {
3843        if let Some(item) = self.traversal.entry() {
3844            if item.path.starts_with(&self.parent_path) {
3845                self.traversal.advance_to_sibling();
3846                return Some(item);
3847            }
3848        }
3849        None
3850    }
3851}
3852
3853struct DescendentEntriesIter<'a> {
3854    parent_path: &'a Path,
3855    traversal: Traversal<'a>,
3856}
3857
3858impl<'a> Iterator for DescendentEntriesIter<'a> {
3859    type Item = &'a Entry;
3860
3861    fn next(&mut self) -> Option<Self::Item> {
3862        if let Some(item) = self.traversal.entry() {
3863            if item.path.starts_with(&self.parent_path) {
3864                self.traversal.advance();
3865                return Some(item);
3866            }
3867        }
3868        None
3869    }
3870}
3871
3872impl<'a> From<&'a Entry> for proto::Entry {
3873    fn from(entry: &'a Entry) -> Self {
3874        Self {
3875            id: entry.id.to_proto(),
3876            is_dir: entry.is_dir(),
3877            path: entry.path.to_string_lossy().into(),
3878            inode: entry.inode,
3879            mtime: Some(entry.mtime.into()),
3880            is_symlink: entry.is_symlink,
3881            is_ignored: entry.is_ignored,
3882            git_status: entry.git_status.map(|status| status.to_proto()),
3883        }
3884    }
3885}
3886
3887impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3888    type Error = anyhow::Error;
3889
3890    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3891        if let Some(mtime) = entry.mtime {
3892            let kind = if entry.is_dir {
3893                EntryKind::Dir
3894            } else {
3895                let mut char_bag = *root_char_bag;
3896                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3897                EntryKind::File(char_bag)
3898            };
3899            let path: Arc<Path> = PathBuf::from(entry.path).into();
3900            Ok(Entry {
3901                id: ProjectEntryId::from_proto(entry.id),
3902                kind,
3903                path,
3904                inode: entry.inode,
3905                mtime: mtime.into(),
3906                is_symlink: entry.is_symlink,
3907                is_ignored: entry.is_ignored,
3908                git_status: GitFileStatus::from_proto(entry.git_status),
3909            })
3910        } else {
3911            Err(anyhow!(
3912                "missing mtime in remote worktree entry {:?}",
3913                entry.path
3914            ))
3915        }
3916    }
3917}
3918
3919#[cfg(test)]
3920mod tests {
3921    use super::*;
3922    use fs::{FakeFs, RealFs};
3923    use gpui::{executor::Deterministic, TestAppContext};
3924    use pretty_assertions::assert_eq;
3925    use rand::prelude::*;
3926    use serde_json::json;
3927    use std::{env, fmt::Write};
3928    use util::{http::FakeHttpClient, test::temp_tree};
3929
3930    #[gpui::test]
3931    async fn test_traversal(cx: &mut TestAppContext) {
3932        let fs = FakeFs::new(cx.background());
3933        fs.insert_tree(
3934            "/root",
3935            json!({
3936               ".gitignore": "a/b\n",
3937               "a": {
3938                   "b": "",
3939                   "c": "",
3940               }
3941            }),
3942        )
3943        .await;
3944
3945        let http_client = FakeHttpClient::with_404_response();
3946        let client = cx.read(|cx| Client::new(http_client, cx));
3947
3948        let tree = Worktree::local(
3949            client,
3950            Path::new("/root"),
3951            true,
3952            fs,
3953            Default::default(),
3954            &mut cx.to_async(),
3955        )
3956        .await
3957        .unwrap();
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(".gitignore"),
3969                    Path::new("a"),
3970                    Path::new("a/c"),
3971                ]
3972            );
3973            assert_eq!(
3974                tree.entries(true)
3975                    .map(|entry| entry.path.as_ref())
3976                    .collect::<Vec<_>>(),
3977                vec![
3978                    Path::new(""),
3979                    Path::new(".gitignore"),
3980                    Path::new("a"),
3981                    Path::new("a/b"),
3982                    Path::new("a/c"),
3983                ]
3984            );
3985        })
3986    }
3987
3988    #[gpui::test]
3989    async fn test_descendent_entries(cx: &mut TestAppContext) {
3990        let fs = FakeFs::new(cx.background());
3991        fs.insert_tree(
3992            "/root",
3993            json!({
3994                "a": "",
3995                "b": {
3996                   "c": {
3997                       "d": ""
3998                   },
3999                   "e": {}
4000                },
4001                "f": "",
4002                "g": {
4003                    "h": {}
4004                },
4005                "i": {
4006                    "j": {
4007                        "k": ""
4008                    },
4009                    "l": {
4010
4011                    }
4012                },
4013                ".gitignore": "i/j\n",
4014            }),
4015        )
4016        .await;
4017
4018        let http_client = FakeHttpClient::with_404_response();
4019        let client = cx.read(|cx| Client::new(http_client, cx));
4020
4021        let tree = Worktree::local(
4022            client,
4023            Path::new("/root"),
4024            true,
4025            fs,
4026            Default::default(),
4027            &mut cx.to_async(),
4028        )
4029        .await
4030        .unwrap();
4031        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4032            .await;
4033
4034        tree.read_with(cx, |tree, _| {
4035            assert_eq!(
4036                tree.descendent_entries(false, false, Path::new("b"))
4037                    .map(|entry| entry.path.as_ref())
4038                    .collect::<Vec<_>>(),
4039                vec![Path::new("b/c/d"),]
4040            );
4041            assert_eq!(
4042                tree.descendent_entries(true, false, Path::new("b"))
4043                    .map(|entry| entry.path.as_ref())
4044                    .collect::<Vec<_>>(),
4045                vec![
4046                    Path::new("b"),
4047                    Path::new("b/c"),
4048                    Path::new("b/c/d"),
4049                    Path::new("b/e"),
4050                ]
4051            );
4052
4053            assert_eq!(
4054                tree.descendent_entries(false, false, Path::new("g"))
4055                    .map(|entry| entry.path.as_ref())
4056                    .collect::<Vec<_>>(),
4057                Vec::<PathBuf>::new()
4058            );
4059            assert_eq!(
4060                tree.descendent_entries(true, false, Path::new("g"))
4061                    .map(|entry| entry.path.as_ref())
4062                    .collect::<Vec<_>>(),
4063                vec![Path::new("g"), Path::new("g/h"),]
4064            );
4065
4066            assert_eq!(
4067                tree.descendent_entries(false, false, Path::new("i"))
4068                    .map(|entry| entry.path.as_ref())
4069                    .collect::<Vec<_>>(),
4070                Vec::<PathBuf>::new()
4071            );
4072            assert_eq!(
4073                tree.descendent_entries(false, true, Path::new("i"))
4074                    .map(|entry| entry.path.as_ref())
4075                    .collect::<Vec<_>>(),
4076                vec![Path::new("i/j/k")]
4077            );
4078            assert_eq!(
4079                tree.descendent_entries(true, false, Path::new("i"))
4080                    .map(|entry| entry.path.as_ref())
4081                    .collect::<Vec<_>>(),
4082                vec![Path::new("i"), Path::new("i/l"),]
4083            );
4084        })
4085    }
4086
4087    #[gpui::test(iterations = 10)]
4088    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
4089        let fs = FakeFs::new(cx.background());
4090        fs.insert_tree(
4091            "/root",
4092            json!({
4093                "lib": {
4094                    "a": {
4095                        "a.txt": ""
4096                    },
4097                    "b": {
4098                        "b.txt": ""
4099                    }
4100                }
4101            }),
4102        )
4103        .await;
4104        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
4105        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
4106
4107        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4108        let tree = Worktree::local(
4109            client,
4110            Path::new("/root"),
4111            true,
4112            fs.clone(),
4113            Default::default(),
4114            &mut cx.to_async(),
4115        )
4116        .await
4117        .unwrap();
4118
4119        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4120            .await;
4121
4122        tree.read_with(cx, |tree, _| {
4123            assert_eq!(
4124                tree.entries(false)
4125                    .map(|entry| entry.path.as_ref())
4126                    .collect::<Vec<_>>(),
4127                vec![
4128                    Path::new(""),
4129                    Path::new("lib"),
4130                    Path::new("lib/a"),
4131                    Path::new("lib/a/a.txt"),
4132                    Path::new("lib/a/lib"),
4133                    Path::new("lib/b"),
4134                    Path::new("lib/b/b.txt"),
4135                    Path::new("lib/b/lib"),
4136                ]
4137            );
4138        });
4139
4140        fs.rename(
4141            Path::new("/root/lib/a/lib"),
4142            Path::new("/root/lib/a/lib-2"),
4143            Default::default(),
4144        )
4145        .await
4146        .unwrap();
4147        executor.run_until_parked();
4148        tree.read_with(cx, |tree, _| {
4149            assert_eq!(
4150                tree.entries(false)
4151                    .map(|entry| entry.path.as_ref())
4152                    .collect::<Vec<_>>(),
4153                vec![
4154                    Path::new(""),
4155                    Path::new("lib"),
4156                    Path::new("lib/a"),
4157                    Path::new("lib/a/a.txt"),
4158                    Path::new("lib/a/lib-2"),
4159                    Path::new("lib/b"),
4160                    Path::new("lib/b/b.txt"),
4161                    Path::new("lib/b/lib"),
4162                ]
4163            );
4164        });
4165    }
4166
4167    #[gpui::test]
4168    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
4169        // .gitignores are handled explicitly by Zed and do not use the git
4170        // machinery that the git_tests module checks
4171        let parent_dir = temp_tree(json!({
4172            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
4173            "tree": {
4174                ".git": {},
4175                ".gitignore": "ignored-dir\n",
4176                "tracked-dir": {
4177                    "tracked-file1": "",
4178                    "ancestor-ignored-file1": "",
4179                },
4180                "ignored-dir": {
4181                    "ignored-file1": ""
4182                }
4183            }
4184        }));
4185        let dir = parent_dir.path().join("tree");
4186
4187        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4188
4189        let tree = Worktree::local(
4190            client,
4191            dir.as_path(),
4192            true,
4193            Arc::new(RealFs),
4194            Default::default(),
4195            &mut cx.to_async(),
4196        )
4197        .await
4198        .unwrap();
4199        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4200            .await;
4201        tree.flush_fs_events(cx).await;
4202        cx.read(|cx| {
4203            let tree = tree.read(cx);
4204            assert!(
4205                !tree
4206                    .entry_for_path("tracked-dir/tracked-file1")
4207                    .unwrap()
4208                    .is_ignored
4209            );
4210            assert!(
4211                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
4212                    .unwrap()
4213                    .is_ignored
4214            );
4215            assert!(
4216                tree.entry_for_path("ignored-dir/ignored-file1")
4217                    .unwrap()
4218                    .is_ignored
4219            );
4220        });
4221
4222        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
4223        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
4224        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
4225        tree.flush_fs_events(cx).await;
4226        cx.read(|cx| {
4227            let tree = tree.read(cx);
4228            assert!(
4229                !tree
4230                    .entry_for_path("tracked-dir/tracked-file2")
4231                    .unwrap()
4232                    .is_ignored
4233            );
4234            assert!(
4235                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
4236                    .unwrap()
4237                    .is_ignored
4238            );
4239            assert!(
4240                tree.entry_for_path("ignored-dir/ignored-file2")
4241                    .unwrap()
4242                    .is_ignored
4243            );
4244            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
4245        });
4246    }
4247
4248    #[gpui::test]
4249    async fn test_write_file(cx: &mut TestAppContext) {
4250        let dir = temp_tree(json!({
4251            ".git": {},
4252            ".gitignore": "ignored-dir\n",
4253            "tracked-dir": {},
4254            "ignored-dir": {}
4255        }));
4256
4257        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4258
4259        let tree = Worktree::local(
4260            client,
4261            dir.path(),
4262            true,
4263            Arc::new(RealFs),
4264            Default::default(),
4265            &mut cx.to_async(),
4266        )
4267        .await
4268        .unwrap();
4269        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4270            .await;
4271        tree.flush_fs_events(cx).await;
4272
4273        tree.update(cx, |tree, cx| {
4274            tree.as_local().unwrap().write_file(
4275                Path::new("tracked-dir/file.txt"),
4276                "hello".into(),
4277                Default::default(),
4278                cx,
4279            )
4280        })
4281        .await
4282        .unwrap();
4283        tree.update(cx, |tree, cx| {
4284            tree.as_local().unwrap().write_file(
4285                Path::new("ignored-dir/file.txt"),
4286                "world".into(),
4287                Default::default(),
4288                cx,
4289            )
4290        })
4291        .await
4292        .unwrap();
4293
4294        tree.read_with(cx, |tree, _| {
4295            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
4296            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
4297            assert!(!tracked.is_ignored);
4298            assert!(ignored.is_ignored);
4299        });
4300    }
4301
4302    #[gpui::test(iterations = 30)]
4303    async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
4304        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4305
4306        let fs = FakeFs::new(cx.background());
4307        fs.insert_tree(
4308            "/root",
4309            json!({
4310                "b": {},
4311                "c": {},
4312                "d": {},
4313            }),
4314        )
4315        .await;
4316
4317        let tree = Worktree::local(
4318            client,
4319            "/root".as_ref(),
4320            true,
4321            fs,
4322            Default::default(),
4323            &mut cx.to_async(),
4324        )
4325        .await
4326        .unwrap();
4327
4328        let snapshot1 = tree.update(cx, |tree, cx| {
4329            let tree = tree.as_local_mut().unwrap();
4330            let snapshot = Arc::new(Mutex::new(tree.snapshot()));
4331            let _ = tree.observe_updates(0, cx, {
4332                let snapshot = snapshot.clone();
4333                move |update| {
4334                    snapshot.lock().apply_remote_update(update).unwrap();
4335                    async { true }
4336                }
4337            });
4338            snapshot
4339        });
4340
4341        let entry = tree
4342            .update(cx, |tree, cx| {
4343                tree.as_local_mut()
4344                    .unwrap()
4345                    .create_entry("a/e".as_ref(), true, cx)
4346            })
4347            .await
4348            .unwrap();
4349        assert!(entry.is_dir());
4350
4351        cx.foreground().run_until_parked();
4352        tree.read_with(cx, |tree, _| {
4353            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
4354        });
4355
4356        let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
4357        assert_eq!(
4358            snapshot1.lock().entries(true).collect::<Vec<_>>(),
4359            snapshot2.entries(true).collect::<Vec<_>>()
4360        );
4361    }
4362
4363    #[gpui::test(iterations = 100)]
4364    async fn test_random_worktree_operations_during_initial_scan(
4365        cx: &mut TestAppContext,
4366        mut rng: StdRng,
4367    ) {
4368        let operations = env::var("OPERATIONS")
4369            .map(|o| o.parse().unwrap())
4370            .unwrap_or(5);
4371        let initial_entries = env::var("INITIAL_ENTRIES")
4372            .map(|o| o.parse().unwrap())
4373            .unwrap_or(20);
4374
4375        let root_dir = Path::new("/test");
4376        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
4377        fs.as_fake().insert_tree(root_dir, json!({})).await;
4378        for _ in 0..initial_entries {
4379            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4380        }
4381        log::info!("generated initial tree");
4382
4383        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4384        let worktree = Worktree::local(
4385            client.clone(),
4386            root_dir,
4387            true,
4388            fs.clone(),
4389            Default::default(),
4390            &mut cx.to_async(),
4391        )
4392        .await
4393        .unwrap();
4394
4395        let mut snapshots =
4396            vec![worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot())];
4397        let updates = Arc::new(Mutex::new(Vec::new()));
4398        worktree.update(cx, |tree, cx| {
4399            check_worktree_change_events(tree, cx);
4400
4401            let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
4402                let updates = updates.clone();
4403                move |update| {
4404                    updates.lock().push(update);
4405                    async { true }
4406                }
4407            });
4408        });
4409
4410        for _ in 0..operations {
4411            worktree
4412                .update(cx, |worktree, cx| {
4413                    randomly_mutate_worktree(worktree, &mut rng, cx)
4414                })
4415                .await
4416                .log_err();
4417            worktree.read_with(cx, |tree, _| {
4418                tree.as_local().unwrap().snapshot.check_invariants()
4419            });
4420
4421            if rng.gen_bool(0.6) {
4422                snapshots
4423                    .push(worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot()));
4424            }
4425        }
4426
4427        worktree
4428            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4429            .await;
4430
4431        cx.foreground().run_until_parked();
4432
4433        let final_snapshot = worktree.read_with(cx, |tree, _| {
4434            let tree = tree.as_local().unwrap();
4435            tree.snapshot.check_invariants();
4436            tree.snapshot()
4437        });
4438
4439        for (i, snapshot) in snapshots.into_iter().enumerate().rev() {
4440            let mut updated_snapshot = snapshot.clone();
4441            for update in updates.lock().iter() {
4442                if update.scan_id >= updated_snapshot.scan_id() as u64 {
4443                    updated_snapshot
4444                        .apply_remote_update(update.clone())
4445                        .unwrap();
4446                }
4447            }
4448
4449            assert_eq!(
4450                updated_snapshot.entries(true).collect::<Vec<_>>(),
4451                final_snapshot.entries(true).collect::<Vec<_>>(),
4452                "wrong updates after snapshot {i}: {snapshot:#?} {updates:#?}",
4453            );
4454        }
4455    }
4456
4457    #[gpui::test(iterations = 100)]
4458    async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
4459        let operations = env::var("OPERATIONS")
4460            .map(|o| o.parse().unwrap())
4461            .unwrap_or(40);
4462        let initial_entries = env::var("INITIAL_ENTRIES")
4463            .map(|o| o.parse().unwrap())
4464            .unwrap_or(20);
4465
4466        let root_dir = Path::new("/test");
4467        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
4468        fs.as_fake().insert_tree(root_dir, json!({})).await;
4469        for _ in 0..initial_entries {
4470            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4471        }
4472        log::info!("generated initial tree");
4473
4474        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
4475        let worktree = Worktree::local(
4476            client.clone(),
4477            root_dir,
4478            true,
4479            fs.clone(),
4480            Default::default(),
4481            &mut cx.to_async(),
4482        )
4483        .await
4484        .unwrap();
4485
4486        let updates = Arc::new(Mutex::new(Vec::new()));
4487        worktree.update(cx, |tree, cx| {
4488            check_worktree_change_events(tree, cx);
4489
4490            let _ = tree.as_local_mut().unwrap().observe_updates(0, cx, {
4491                let updates = updates.clone();
4492                move |update| {
4493                    updates.lock().push(update);
4494                    async { true }
4495                }
4496            });
4497        });
4498
4499        worktree
4500            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4501            .await;
4502
4503        fs.as_fake().pause_events();
4504        let mut snapshots = Vec::new();
4505        let mut mutations_len = operations;
4506        while mutations_len > 1 {
4507            if rng.gen_bool(0.2) {
4508                worktree
4509                    .update(cx, |worktree, cx| {
4510                        randomly_mutate_worktree(worktree, &mut rng, cx)
4511                    })
4512                    .await
4513                    .log_err();
4514            } else {
4515                randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
4516            }
4517
4518            let buffered_event_count = fs.as_fake().buffered_event_count();
4519            if buffered_event_count > 0 && rng.gen_bool(0.3) {
4520                let len = rng.gen_range(0..=buffered_event_count);
4521                log::info!("flushing {} events", len);
4522                fs.as_fake().flush_events(len);
4523            } else {
4524                randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
4525                mutations_len -= 1;
4526            }
4527
4528            cx.foreground().run_until_parked();
4529            if rng.gen_bool(0.2) {
4530                log::info!("storing snapshot {}", snapshots.len());
4531                let snapshot =
4532                    worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4533                snapshots.push(snapshot);
4534            }
4535        }
4536
4537        log::info!("quiescing");
4538        fs.as_fake().flush_events(usize::MAX);
4539        cx.foreground().run_until_parked();
4540        let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4541        snapshot.check_invariants();
4542
4543        {
4544            let new_worktree = Worktree::local(
4545                client.clone(),
4546                root_dir,
4547                true,
4548                fs.clone(),
4549                Default::default(),
4550                &mut cx.to_async(),
4551            )
4552            .await
4553            .unwrap();
4554            new_worktree
4555                .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4556                .await;
4557            let new_snapshot =
4558                new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4559            assert_eq!(
4560                snapshot.entries_without_ids(true),
4561                new_snapshot.entries_without_ids(true)
4562            );
4563        }
4564
4565        for (i, mut prev_snapshot) in snapshots.into_iter().enumerate().rev() {
4566            for update in updates.lock().iter() {
4567                if update.scan_id >= prev_snapshot.scan_id() as u64 {
4568                    prev_snapshot.apply_remote_update(update.clone()).unwrap();
4569                }
4570            }
4571
4572            assert_eq!(
4573                prev_snapshot.entries(true).collect::<Vec<_>>(),
4574                snapshot.entries(true).collect::<Vec<_>>(),
4575                "wrong updates after snapshot {i}: {updates:#?}",
4576            );
4577        }
4578    }
4579
4580    // The worktree's `UpdatedEntries` event can be used to follow along with
4581    // all changes to the worktree's snapshot.
4582    fn check_worktree_change_events(tree: &mut Worktree, cx: &mut ModelContext<Worktree>) {
4583        let mut entries = tree.entries(true).cloned().collect::<Vec<_>>();
4584        cx.subscribe(&cx.handle(), move |tree, _, event, _| {
4585            if let Event::UpdatedEntries(changes) = event {
4586                for (path, _, change_type) in changes.iter() {
4587                    let entry = tree.entry_for_path(&path).cloned();
4588                    let ix = match entries.binary_search_by_key(&path, |e| &e.path) {
4589                        Ok(ix) | Err(ix) => ix,
4590                    };
4591                    match change_type {
4592                        PathChange::Loaded => entries.insert(ix, entry.unwrap()),
4593                        PathChange::Added => entries.insert(ix, entry.unwrap()),
4594                        PathChange::Removed => drop(entries.remove(ix)),
4595                        PathChange::Updated => {
4596                            let entry = entry.unwrap();
4597                            let existing_entry = entries.get_mut(ix).unwrap();
4598                            assert_eq!(existing_entry.path, entry.path);
4599                            *existing_entry = entry;
4600                        }
4601                        PathChange::AddedOrUpdated => {
4602                            let entry = entry.unwrap();
4603                            if entries.get(ix).map(|e| &e.path) == Some(&entry.path) {
4604                                *entries.get_mut(ix).unwrap() = entry;
4605                            } else {
4606                                entries.insert(ix, entry);
4607                            }
4608                        }
4609                    }
4610                }
4611
4612                let new_entries = tree.entries(true).cloned().collect::<Vec<_>>();
4613                assert_eq!(entries, new_entries, "incorrect changes: {:?}", changes);
4614            }
4615        })
4616        .detach();
4617    }
4618
4619    fn randomly_mutate_worktree(
4620        worktree: &mut Worktree,
4621        rng: &mut impl Rng,
4622        cx: &mut ModelContext<Worktree>,
4623    ) -> Task<Result<()>> {
4624        log::info!("mutating worktree");
4625        let worktree = worktree.as_local_mut().unwrap();
4626        let snapshot = worktree.snapshot();
4627        let entry = snapshot.entries(false).choose(rng).unwrap();
4628
4629        match rng.gen_range(0_u32..100) {
4630            0..=33 if entry.path.as_ref() != Path::new("") => {
4631                log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
4632                worktree.delete_entry(entry.id, cx).unwrap()
4633            }
4634            ..=66 if entry.path.as_ref() != Path::new("") => {
4635                let other_entry = snapshot.entries(false).choose(rng).unwrap();
4636                let new_parent_path = if other_entry.is_dir() {
4637                    other_entry.path.clone()
4638                } else {
4639                    other_entry.path.parent().unwrap().into()
4640                };
4641                let mut new_path = new_parent_path.join(gen_name(rng));
4642                if new_path.starts_with(&entry.path) {
4643                    new_path = gen_name(rng).into();
4644                }
4645
4646                log::info!(
4647                    "renaming entry {:?} ({}) to {:?}",
4648                    entry.path,
4649                    entry.id.0,
4650                    new_path
4651                );
4652                let task = worktree.rename_entry(entry.id, new_path, cx).unwrap();
4653                cx.foreground().spawn(async move {
4654                    task.await?;
4655                    Ok(())
4656                })
4657            }
4658            _ => {
4659                let task = if entry.is_dir() {
4660                    let child_path = entry.path.join(gen_name(rng));
4661                    let is_dir = rng.gen_bool(0.3);
4662                    log::info!(
4663                        "creating {} at {:?}",
4664                        if is_dir { "dir" } else { "file" },
4665                        child_path,
4666                    );
4667                    worktree.create_entry(child_path, is_dir, cx)
4668                } else {
4669                    log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
4670                    worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx)
4671                };
4672                cx.foreground().spawn(async move {
4673                    task.await?;
4674                    Ok(())
4675                })
4676            }
4677        }
4678    }
4679
4680    async fn randomly_mutate_fs(
4681        fs: &Arc<dyn Fs>,
4682        root_path: &Path,
4683        insertion_probability: f64,
4684        rng: &mut impl Rng,
4685    ) {
4686        log::info!("mutating fs");
4687        let mut files = Vec::new();
4688        let mut dirs = Vec::new();
4689        for path in fs.as_fake().paths() {
4690            if path.starts_with(root_path) {
4691                if fs.is_file(&path).await {
4692                    files.push(path);
4693                } else {
4694                    dirs.push(path);
4695                }
4696            }
4697        }
4698
4699        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
4700            let path = dirs.choose(rng).unwrap();
4701            let new_path = path.join(gen_name(rng));
4702
4703            if rng.gen() {
4704                log::info!(
4705                    "creating dir {:?}",
4706                    new_path.strip_prefix(root_path).unwrap()
4707                );
4708                fs.create_dir(&new_path).await.unwrap();
4709            } else {
4710                log::info!(
4711                    "creating file {:?}",
4712                    new_path.strip_prefix(root_path).unwrap()
4713                );
4714                fs.create_file(&new_path, Default::default()).await.unwrap();
4715            }
4716        } else if rng.gen_bool(0.05) {
4717            let ignore_dir_path = dirs.choose(rng).unwrap();
4718            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
4719
4720            let subdirs = dirs
4721                .iter()
4722                .filter(|d| d.starts_with(&ignore_dir_path))
4723                .cloned()
4724                .collect::<Vec<_>>();
4725            let subfiles = files
4726                .iter()
4727                .filter(|d| d.starts_with(&ignore_dir_path))
4728                .cloned()
4729                .collect::<Vec<_>>();
4730            let files_to_ignore = {
4731                let len = rng.gen_range(0..=subfiles.len());
4732                subfiles.choose_multiple(rng, len)
4733            };
4734            let dirs_to_ignore = {
4735                let len = rng.gen_range(0..subdirs.len());
4736                subdirs.choose_multiple(rng, len)
4737            };
4738
4739            let mut ignore_contents = String::new();
4740            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
4741                writeln!(
4742                    ignore_contents,
4743                    "{}",
4744                    path_to_ignore
4745                        .strip_prefix(&ignore_dir_path)
4746                        .unwrap()
4747                        .to_str()
4748                        .unwrap()
4749                )
4750                .unwrap();
4751            }
4752            log::info!(
4753                "creating gitignore {:?} with contents:\n{}",
4754                ignore_path.strip_prefix(&root_path).unwrap(),
4755                ignore_contents
4756            );
4757            fs.save(
4758                &ignore_path,
4759                &ignore_contents.as_str().into(),
4760                Default::default(),
4761            )
4762            .await
4763            .unwrap();
4764        } else {
4765            let old_path = {
4766                let file_path = files.choose(rng);
4767                let dir_path = dirs[1..].choose(rng);
4768                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
4769            };
4770
4771            let is_rename = rng.gen();
4772            if is_rename {
4773                let new_path_parent = dirs
4774                    .iter()
4775                    .filter(|d| !d.starts_with(old_path))
4776                    .choose(rng)
4777                    .unwrap();
4778
4779                let overwrite_existing_dir =
4780                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
4781                let new_path = if overwrite_existing_dir {
4782                    fs.remove_dir(
4783                        &new_path_parent,
4784                        RemoveOptions {
4785                            recursive: true,
4786                            ignore_if_not_exists: true,
4787                        },
4788                    )
4789                    .await
4790                    .unwrap();
4791                    new_path_parent.to_path_buf()
4792                } else {
4793                    new_path_parent.join(gen_name(rng))
4794                };
4795
4796                log::info!(
4797                    "renaming {:?} to {}{:?}",
4798                    old_path.strip_prefix(&root_path).unwrap(),
4799                    if overwrite_existing_dir {
4800                        "overwrite "
4801                    } else {
4802                        ""
4803                    },
4804                    new_path.strip_prefix(&root_path).unwrap()
4805                );
4806                fs.rename(
4807                    &old_path,
4808                    &new_path,
4809                    fs::RenameOptions {
4810                        overwrite: true,
4811                        ignore_if_exists: true,
4812                    },
4813                )
4814                .await
4815                .unwrap();
4816            } else if fs.is_file(&old_path).await {
4817                log::info!(
4818                    "deleting file {:?}",
4819                    old_path.strip_prefix(&root_path).unwrap()
4820                );
4821                fs.remove_file(old_path, Default::default()).await.unwrap();
4822            } else {
4823                log::info!(
4824                    "deleting dir {:?}",
4825                    old_path.strip_prefix(&root_path).unwrap()
4826                );
4827                fs.remove_dir(
4828                    &old_path,
4829                    RemoveOptions {
4830                        recursive: true,
4831                        ignore_if_not_exists: true,
4832                    },
4833                )
4834                .await
4835                .unwrap();
4836            }
4837        }
4838    }
4839
4840    fn gen_name(rng: &mut impl Rng) -> String {
4841        (0..6)
4842            .map(|_| rng.sample(rand::distributions::Alphanumeric))
4843            .map(char::from)
4844            .collect()
4845    }
4846
4847    impl LocalSnapshot {
4848        fn check_invariants(&self) {
4849            assert_eq!(
4850                self.entries_by_path
4851                    .cursor::<()>()
4852                    .map(|e| (&e.path, e.id))
4853                    .collect::<Vec<_>>(),
4854                self.entries_by_id
4855                    .cursor::<()>()
4856                    .map(|e| (&e.path, e.id))
4857                    .collect::<collections::BTreeSet<_>>()
4858                    .into_iter()
4859                    .collect::<Vec<_>>(),
4860                "entries_by_path and entries_by_id are inconsistent"
4861            );
4862
4863            let mut files = self.files(true, 0);
4864            let mut visible_files = self.files(false, 0);
4865            for entry in self.entries_by_path.cursor::<()>() {
4866                if entry.is_file() {
4867                    assert_eq!(files.next().unwrap().inode, entry.inode);
4868                    if !entry.is_ignored {
4869                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
4870                    }
4871                }
4872            }
4873
4874            assert!(files.next().is_none());
4875            assert!(visible_files.next().is_none());
4876
4877            let mut bfs_paths = Vec::new();
4878            let mut stack = vec![Path::new("")];
4879            while let Some(path) = stack.pop() {
4880                bfs_paths.push(path);
4881                let ix = stack.len();
4882                for child_entry in self.child_entries(path) {
4883                    stack.insert(ix, &child_entry.path);
4884                }
4885            }
4886
4887            let dfs_paths_via_iter = self
4888                .entries_by_path
4889                .cursor::<()>()
4890                .map(|e| e.path.as_ref())
4891                .collect::<Vec<_>>();
4892            assert_eq!(bfs_paths, dfs_paths_via_iter);
4893
4894            let dfs_paths_via_traversal = self
4895                .entries(true)
4896                .map(|e| e.path.as_ref())
4897                .collect::<Vec<_>>();
4898            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
4899
4900            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
4901                let ignore_parent_path =
4902                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
4903                assert!(self.entry_for_path(&ignore_parent_path).is_some());
4904                assert!(self
4905                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
4906                    .is_some());
4907            }
4908        }
4909
4910        fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
4911            let mut paths = Vec::new();
4912            for entry in self.entries_by_path.cursor::<()>() {
4913                if include_ignored || !entry.is_ignored {
4914                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
4915                }
4916            }
4917            paths.sort_by(|a, b| a.0.cmp(b.0));
4918            paths
4919        }
4920    }
4921
4922    mod git_tests {
4923        use super::*;
4924        use pretty_assertions::assert_eq;
4925
4926        #[gpui::test]
4927        async fn test_rename_work_directory(cx: &mut TestAppContext) {
4928            let root = temp_tree(json!({
4929                "projects": {
4930                    "project1": {
4931                        "a": "",
4932                        "b": "",
4933                    }
4934                },
4935
4936            }));
4937            let root_path = root.path();
4938
4939            let http_client = FakeHttpClient::with_404_response();
4940            let client = cx.read(|cx| Client::new(http_client, cx));
4941            let tree = Worktree::local(
4942                client,
4943                root_path,
4944                true,
4945                Arc::new(RealFs),
4946                Default::default(),
4947                &mut cx.to_async(),
4948            )
4949            .await
4950            .unwrap();
4951
4952            let repo = git_init(&root_path.join("projects/project1"));
4953            git_add("a", &repo);
4954            git_commit("init", &repo);
4955            std::fs::write(root_path.join("projects/project1/a"), "aa").ok();
4956
4957            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4958                .await;
4959
4960            tree.flush_fs_events(cx).await;
4961
4962            cx.read(|cx| {
4963                let tree = tree.read(cx);
4964                let (work_dir, _) = tree.repositories().next().unwrap();
4965                assert_eq!(work_dir.as_ref(), Path::new("projects/project1"));
4966                assert_eq!(
4967                    tree.status_for_file(Path::new("projects/project1/a")),
4968                    Some(GitFileStatus::Modified)
4969                );
4970                assert_eq!(
4971                    tree.status_for_file(Path::new("projects/project1/b")),
4972                    Some(GitFileStatus::Added)
4973                );
4974            });
4975
4976            std::fs::rename(
4977                root_path.join("projects/project1"),
4978                root_path.join("projects/project2"),
4979            )
4980            .ok();
4981            tree.flush_fs_events(cx).await;
4982
4983            cx.read(|cx| {
4984                let tree = tree.read(cx);
4985                let (work_dir, _) = tree.repositories().next().unwrap();
4986                assert_eq!(work_dir.as_ref(), Path::new("projects/project2"));
4987                assert_eq!(
4988                    tree.status_for_file(Path::new("projects/project2/a")),
4989                    Some(GitFileStatus::Modified)
4990                );
4991                assert_eq!(
4992                    tree.status_for_file(Path::new("projects/project2/b")),
4993                    Some(GitFileStatus::Added)
4994                );
4995            });
4996        }
4997
4998        #[gpui::test]
4999        async fn test_git_repository_for_path(cx: &mut TestAppContext) {
5000            let root = temp_tree(json!({
5001                "c.txt": "",
5002                "dir1": {
5003                    ".git": {},
5004                    "deps": {
5005                        "dep1": {
5006                            ".git": {},
5007                            "src": {
5008                                "a.txt": ""
5009                            }
5010                        }
5011                    },
5012                    "src": {
5013                        "b.txt": ""
5014                    }
5015                },
5016            }));
5017
5018            let http_client = FakeHttpClient::with_404_response();
5019            let client = cx.read(|cx| Client::new(http_client, cx));
5020            let tree = Worktree::local(
5021                client,
5022                root.path(),
5023                true,
5024                Arc::new(RealFs),
5025                Default::default(),
5026                &mut cx.to_async(),
5027            )
5028            .await
5029            .unwrap();
5030
5031            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5032                .await;
5033            tree.flush_fs_events(cx).await;
5034
5035            tree.read_with(cx, |tree, _cx| {
5036                let tree = tree.as_local().unwrap();
5037
5038                assert!(tree.repository_for_path("c.txt".as_ref()).is_none());
5039
5040                let entry = tree.repository_for_path("dir1/src/b.txt".as_ref()).unwrap();
5041                assert_eq!(
5042                    entry
5043                        .work_directory(tree)
5044                        .map(|directory| directory.as_ref().to_owned()),
5045                    Some(Path::new("dir1").to_owned())
5046                );
5047
5048                let entry = tree
5049                    .repository_for_path("dir1/deps/dep1/src/a.txt".as_ref())
5050                    .unwrap();
5051                assert_eq!(
5052                    entry
5053                        .work_directory(tree)
5054                        .map(|directory| directory.as_ref().to_owned()),
5055                    Some(Path::new("dir1/deps/dep1").to_owned())
5056                );
5057
5058                let entries = tree.files(false, 0);
5059
5060                let paths_with_repos = tree
5061                    .entries_with_repositories(entries)
5062                    .map(|(entry, repo)| {
5063                        (
5064                            entry.path.as_ref(),
5065                            repo.and_then(|repo| {
5066                                repo.work_directory(&tree)
5067                                    .map(|work_directory| work_directory.0.to_path_buf())
5068                            }),
5069                        )
5070                    })
5071                    .collect::<Vec<_>>();
5072
5073                assert_eq!(
5074                    paths_with_repos,
5075                    &[
5076                        (Path::new("c.txt"), None),
5077                        (
5078                            Path::new("dir1/deps/dep1/src/a.txt"),
5079                            Some(Path::new("dir1/deps/dep1").into())
5080                        ),
5081                        (Path::new("dir1/src/b.txt"), Some(Path::new("dir1").into())),
5082                    ]
5083                );
5084            });
5085
5086            let repo_update_events = Arc::new(Mutex::new(vec![]));
5087            tree.update(cx, |_, cx| {
5088                let repo_update_events = repo_update_events.clone();
5089                cx.subscribe(&tree, move |_, _, event, _| {
5090                    if let Event::UpdatedGitRepositories(update) = event {
5091                        repo_update_events.lock().push(update.clone());
5092                    }
5093                })
5094                .detach();
5095            });
5096
5097            std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
5098            tree.flush_fs_events(cx).await;
5099
5100            assert_eq!(
5101                repo_update_events.lock()[0]
5102                    .iter()
5103                    .map(|e| e.0.clone())
5104                    .collect::<Vec<Arc<Path>>>(),
5105                vec![Path::new("dir1").into()]
5106            );
5107
5108            std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
5109            tree.flush_fs_events(cx).await;
5110
5111            tree.read_with(cx, |tree, _cx| {
5112                let tree = tree.as_local().unwrap();
5113
5114                assert!(tree
5115                    .repository_for_path("dir1/src/b.txt".as_ref())
5116                    .is_none());
5117            });
5118        }
5119
5120        #[gpui::test]
5121        async fn test_git_status(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
5122            const IGNORE_RULE: &'static str = "**/target";
5123
5124            let root = temp_tree(json!({
5125                "project": {
5126                    "a.txt": "a",
5127                    "b.txt": "bb",
5128                    "c": {
5129                        "d": {
5130                            "e.txt": "eee"
5131                        }
5132                    },
5133                    "f.txt": "ffff",
5134                    "target": {
5135                        "build_file": "???"
5136                    },
5137                    ".gitignore": IGNORE_RULE
5138                },
5139
5140            }));
5141
5142            let http_client = FakeHttpClient::with_404_response();
5143            let client = cx.read(|cx| Client::new(http_client, cx));
5144            let tree = Worktree::local(
5145                client,
5146                root.path(),
5147                true,
5148                Arc::new(RealFs),
5149                Default::default(),
5150                &mut cx.to_async(),
5151            )
5152            .await
5153            .unwrap();
5154
5155            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5156                .await;
5157
5158            const A_TXT: &'static str = "a.txt";
5159            const B_TXT: &'static str = "b.txt";
5160            const E_TXT: &'static str = "c/d/e.txt";
5161            const F_TXT: &'static str = "f.txt";
5162            const DOTGITIGNORE: &'static str = ".gitignore";
5163            const BUILD_FILE: &'static str = "target/build_file";
5164            let project_path: &Path = &Path::new("project");
5165
5166            let work_dir = root.path().join("project");
5167            let mut repo = git_init(work_dir.as_path());
5168            repo.add_ignore_rule(IGNORE_RULE).unwrap();
5169            git_add(Path::new(A_TXT), &repo);
5170            git_add(Path::new(E_TXT), &repo);
5171            git_add(Path::new(DOTGITIGNORE), &repo);
5172            git_commit("Initial commit", &repo);
5173
5174            tree.flush_fs_events(cx).await;
5175            deterministic.run_until_parked();
5176
5177            // Check that the right git state is observed on startup
5178            tree.read_with(cx, |tree, _cx| {
5179                let snapshot = tree.snapshot();
5180                assert_eq!(snapshot.repository_entries.iter().count(), 1);
5181                let (dir, _) = snapshot.repository_entries.iter().next().unwrap();
5182                assert_eq!(dir.0.as_ref(), Path::new("project"));
5183
5184                assert_eq!(
5185                    snapshot.status_for_file(project_path.join(B_TXT)),
5186                    Some(GitFileStatus::Added)
5187                );
5188                assert_eq!(
5189                    snapshot.status_for_file(project_path.join(F_TXT)),
5190                    Some(GitFileStatus::Added)
5191                );
5192            });
5193
5194            std::fs::write(work_dir.join(A_TXT), "aa").unwrap();
5195
5196            tree.flush_fs_events(cx).await;
5197            deterministic.run_until_parked();
5198
5199            tree.read_with(cx, |tree, _cx| {
5200                let snapshot = tree.snapshot();
5201
5202                assert_eq!(
5203                    snapshot.status_for_file(project_path.join(A_TXT)),
5204                    Some(GitFileStatus::Modified)
5205                );
5206            });
5207
5208            git_add(Path::new(A_TXT), &repo);
5209            git_add(Path::new(B_TXT), &repo);
5210            git_commit("Committing modified and added", &repo);
5211            tree.flush_fs_events(cx).await;
5212            deterministic.run_until_parked();
5213
5214            // Check that repo only changes are tracked
5215            tree.read_with(cx, |tree, _cx| {
5216                let snapshot = tree.snapshot();
5217
5218                assert_eq!(
5219                    snapshot.status_for_file(project_path.join(F_TXT)),
5220                    Some(GitFileStatus::Added)
5221                );
5222
5223                assert_eq!(snapshot.status_for_file(project_path.join(B_TXT)), None);
5224                assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
5225            });
5226
5227            git_reset(0, &repo);
5228            git_remove_index(Path::new(B_TXT), &repo);
5229            git_stash(&mut repo);
5230            std::fs::write(work_dir.join(E_TXT), "eeee").unwrap();
5231            std::fs::write(work_dir.join(BUILD_FILE), "this should be ignored").unwrap();
5232            tree.flush_fs_events(cx).await;
5233            deterministic.run_until_parked();
5234
5235            // Check that more complex repo changes are tracked
5236            tree.read_with(cx, |tree, _cx| {
5237                let snapshot = tree.snapshot();
5238
5239                assert_eq!(snapshot.status_for_file(project_path.join(A_TXT)), None);
5240                assert_eq!(
5241                    snapshot.status_for_file(project_path.join(B_TXT)),
5242                    Some(GitFileStatus::Added)
5243                );
5244                assert_eq!(
5245                    snapshot.status_for_file(project_path.join(E_TXT)),
5246                    Some(GitFileStatus::Modified)
5247                );
5248            });
5249
5250            std::fs::remove_file(work_dir.join(B_TXT)).unwrap();
5251            std::fs::remove_dir_all(work_dir.join("c")).unwrap();
5252            std::fs::write(
5253                work_dir.join(DOTGITIGNORE),
5254                [IGNORE_RULE, "f.txt"].join("\n"),
5255            )
5256            .unwrap();
5257
5258            git_add(Path::new(DOTGITIGNORE), &repo);
5259            git_commit("Committing modified git ignore", &repo);
5260
5261            tree.flush_fs_events(cx).await;
5262            deterministic.run_until_parked();
5263
5264            let mut renamed_dir_name = "first_directory/second_directory";
5265            const RENAMED_FILE: &'static str = "rf.txt";
5266
5267            std::fs::create_dir_all(work_dir.join(renamed_dir_name)).unwrap();
5268            std::fs::write(
5269                work_dir.join(renamed_dir_name).join(RENAMED_FILE),
5270                "new-contents",
5271            )
5272            .unwrap();
5273
5274            tree.flush_fs_events(cx).await;
5275            deterministic.run_until_parked();
5276
5277            tree.read_with(cx, |tree, _cx| {
5278                let snapshot = tree.snapshot();
5279                assert_eq!(
5280                    snapshot
5281                        .status_for_file(&project_path.join(renamed_dir_name).join(RENAMED_FILE)),
5282                    Some(GitFileStatus::Added)
5283                );
5284            });
5285
5286            renamed_dir_name = "new_first_directory/second_directory";
5287
5288            std::fs::rename(
5289                work_dir.join("first_directory"),
5290                work_dir.join("new_first_directory"),
5291            )
5292            .unwrap();
5293
5294            tree.flush_fs_events(cx).await;
5295            deterministic.run_until_parked();
5296
5297            tree.read_with(cx, |tree, _cx| {
5298                let snapshot = tree.snapshot();
5299
5300                assert_eq!(
5301                    snapshot.status_for_file(
5302                        project_path
5303                            .join(Path::new(renamed_dir_name))
5304                            .join(RENAMED_FILE)
5305                    ),
5306                    Some(GitFileStatus::Added)
5307                );
5308            });
5309        }
5310
5311        #[gpui::test]
5312        async fn test_statuses_for_paths(cx: &mut TestAppContext) {
5313            let fs = FakeFs::new(cx.background());
5314            fs.insert_tree(
5315                "/root",
5316                json!({
5317                    ".git": {},
5318                    "a": {
5319                        "b": {
5320                            "c1.txt": "",
5321                            "c2.txt": "",
5322                        },
5323                        "d": {
5324                            "e1.txt": "",
5325                            "e2.txt": "",
5326                            "e3.txt": "",
5327                        }
5328                    },
5329                    "f": {
5330                        "no-status.txt": ""
5331                    },
5332                    "g": {
5333                        "h1.txt": "",
5334                        "h2.txt": ""
5335                    },
5336
5337                }),
5338            )
5339            .await;
5340
5341            fs.set_status_for_repo(
5342                &Path::new("/root/.git"),
5343                &[
5344                    (Path::new("a/b/c1.txt"), GitFileStatus::Added),
5345                    (Path::new("a/d/e2.txt"), GitFileStatus::Modified),
5346                    (Path::new("g/h2.txt"), GitFileStatus::Conflict),
5347                ],
5348            );
5349
5350            let http_client = FakeHttpClient::with_404_response();
5351            let client = cx.read(|cx| Client::new(http_client, cx));
5352            let tree = Worktree::local(
5353                client,
5354                Path::new("/root"),
5355                true,
5356                fs.clone(),
5357                Default::default(),
5358                &mut cx.to_async(),
5359            )
5360            .await
5361            .unwrap();
5362
5363            cx.foreground().run_until_parked();
5364
5365            let snapshot = tree.read_with(cx, |tree, _| tree.snapshot());
5366
5367            assert_eq!(
5368                snapshot.statuses_for_paths([
5369                    Path::new(""),
5370                    Path::new("a"),
5371                    Path::new("a/b"),
5372                    Path::new("a/d"),
5373                    Path::new("f"),
5374                    Path::new("g"),
5375                ]),
5376                &[
5377                    Some(GitFileStatus::Conflict),
5378                    Some(GitFileStatus::Modified),
5379                    Some(GitFileStatus::Added),
5380                    Some(GitFileStatus::Modified),
5381                    None,
5382                    Some(GitFileStatus::Conflict),
5383                ]
5384            )
5385        }
5386
5387        #[track_caller]
5388        fn git_init(path: &Path) -> git2::Repository {
5389            git2::Repository::init(path).expect("Failed to initialize git repository")
5390        }
5391
5392        #[track_caller]
5393        fn git_add<P: AsRef<Path>>(path: P, repo: &git2::Repository) {
5394            let path = path.as_ref();
5395            let mut index = repo.index().expect("Failed to get index");
5396            index.add_path(path).expect("Failed to add a.txt");
5397            index.write().expect("Failed to write index");
5398        }
5399
5400        #[track_caller]
5401        fn git_remove_index(path: &Path, repo: &git2::Repository) {
5402            let mut index = repo.index().expect("Failed to get index");
5403            index.remove_path(path).expect("Failed to add a.txt");
5404            index.write().expect("Failed to write index");
5405        }
5406
5407        #[track_caller]
5408        fn git_commit(msg: &'static str, repo: &git2::Repository) {
5409            use git2::Signature;
5410
5411            let signature = Signature::now("test", "test@zed.dev").unwrap();
5412            let oid = repo.index().unwrap().write_tree().unwrap();
5413            let tree = repo.find_tree(oid).unwrap();
5414            if let Some(head) = repo.head().ok() {
5415                let parent_obj = head.peel(git2::ObjectType::Commit).unwrap();
5416
5417                let parent_commit = parent_obj.as_commit().unwrap();
5418
5419                repo.commit(
5420                    Some("HEAD"),
5421                    &signature,
5422                    &signature,
5423                    msg,
5424                    &tree,
5425                    &[parent_commit],
5426                )
5427                .expect("Failed to commit with parent");
5428            } else {
5429                repo.commit(Some("HEAD"), &signature, &signature, msg, &tree, &[])
5430                    .expect("Failed to commit");
5431            }
5432        }
5433
5434        #[track_caller]
5435        fn git_stash(repo: &mut git2::Repository) {
5436            use git2::Signature;
5437
5438            let signature = Signature::now("test", "test@zed.dev").unwrap();
5439            repo.stash_save(&signature, "N/A", None)
5440                .expect("Failed to stash");
5441        }
5442
5443        #[track_caller]
5444        fn git_reset(offset: usize, repo: &git2::Repository) {
5445            let head = repo.head().expect("Couldn't get repo head");
5446            let object = head.peel(git2::ObjectType::Commit).unwrap();
5447            let commit = object.as_commit().unwrap();
5448            let new_head = commit
5449                .parents()
5450                .inspect(|parnet| {
5451                    parnet.message();
5452                })
5453                .skip(offset)
5454                .next()
5455                .expect("Not enough history");
5456            repo.reset(&new_head.as_object(), git2::ResetType::Soft, None)
5457                .expect("Could not reset");
5458        }
5459
5460        #[allow(dead_code)]
5461        #[track_caller]
5462        fn git_status(repo: &git2::Repository) -> HashMap<String, git2::Status> {
5463            repo.statuses(None)
5464                .unwrap()
5465                .iter()
5466                .map(|status| (status.path().unwrap().to_string(), status.status()))
5467                .collect()
5468        }
5469    }
5470}