worktree.rs

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