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