worktree.rs

   1use super::{
   2    fs::{self, Fs},
   3    ignore::IgnoreStack,
   4    DiagnosticSummary,
   5};
   6use crate::{copy_recursive, ProjectEntryId, RemoveOptions};
   7use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   8use anyhow::{anyhow, Context, Result};
   9use client::{proto, Client};
  10use clock::ReplicaId;
  11use collections::{HashMap, VecDeque};
  12use futures::{
  13    channel::{
  14        mpsc::{self, UnboundedSender},
  15        oneshot,
  16    },
  17    Stream, StreamExt,
  18};
  19use fuzzy::CharBag;
  20use git::repository::GitRepository;
  21use git::{DOT_GIT, GITIGNORE};
  22use gpui::{
  23    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  24    Task,
  25};
  26use language::{
  27    proto::{deserialize_version, serialize_line_ending, serialize_version},
  28    Buffer, DiagnosticEntry, LineEnding, PointUtf16, Rope,
  29};
  30use parking_lot::Mutex;
  31use postage::{
  32    prelude::{Sink as _, Stream as _},
  33    watch,
  34};
  35
  36use smol::channel::{self, Sender};
  37use std::{
  38    any::Any,
  39    cmp::{self, Ordering},
  40    convert::TryFrom,
  41    ffi::{OsStr, OsString},
  42    fmt,
  43    future::Future,
  44    mem,
  45    ops::{Deref, DerefMut},
  46    os::unix::prelude::{OsStrExt, OsStringExt},
  47    path::{Path, PathBuf},
  48    sync::{atomic::AtomicUsize, Arc},
  49    task::Poll,
  50    time::{Duration, SystemTime},
  51};
  52use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  53use util::{ResultExt, TryFutureExt};
  54
  55#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  56pub struct WorktreeId(usize);
  57
  58#[allow(clippy::large_enum_variant)]
  59pub enum Worktree {
  60    Local(LocalWorktree),
  61    Remote(RemoteWorktree),
  62}
  63
  64pub struct LocalWorktree {
  65    snapshot: LocalSnapshot,
  66    background_snapshot: Arc<Mutex<LocalSnapshot>>,
  67    last_scan_state_rx: watch::Receiver<ScanState>,
  68    _background_scanner_task: Option<Task<()>>,
  69    poll_task: Option<Task<()>>,
  70    share: Option<ShareState>,
  71    diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
  72    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  73    client: Arc<Client>,
  74    fs: Arc<dyn Fs>,
  75    visible: bool,
  76}
  77
  78pub struct RemoteWorktree {
  79    pub snapshot: Snapshot,
  80    pub(crate) background_snapshot: Arc<Mutex<Snapshot>>,
  81    project_id: u64,
  82    client: Arc<Client>,
  83    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
  84    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
  85    replica_id: ReplicaId,
  86    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  87    visible: bool,
  88}
  89
  90#[derive(Clone)]
  91pub struct Snapshot {
  92    id: WorktreeId,
  93    root_name: String,
  94    root_char_bag: CharBag,
  95    entries_by_path: SumTree<Entry>,
  96    entries_by_id: SumTree<PathEntry>,
  97    scan_id: usize,
  98    is_complete: bool,
  99}
 100
 101#[derive(Clone)]
 102pub struct GitRepositoryEntry {
 103    pub(crate) repo: Arc<Mutex<dyn GitRepository>>,
 104
 105    pub(crate) scan_id: usize,
 106    // Path to folder containing the .git file or directory
 107    pub(crate) content_path: Arc<Path>,
 108    // Path to the actual .git folder.
 109    // Note: if .git is a file, this points to the folder indicated by the .git file
 110    pub(crate) git_dir_path: Arc<Path>,
 111}
 112
 113impl std::fmt::Debug for GitRepositoryEntry {
 114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 115        f.debug_struct("GitRepositoryEntry")
 116            .field("content_path", &self.content_path)
 117            .field("git_dir_path", &self.git_dir_path)
 118            .field("libgit_repository", &"LibGitRepository")
 119            .finish()
 120    }
 121}
 122
 123pub struct LocalSnapshot {
 124    abs_path: Arc<Path>,
 125    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 126    git_repositories: Vec<GitRepositoryEntry>,
 127    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 128    next_entry_id: Arc<AtomicUsize>,
 129    snapshot: Snapshot,
 130    extension_counts: HashMap<OsString, usize>,
 131}
 132
 133impl Clone for LocalSnapshot {
 134    fn clone(&self) -> Self {
 135        Self {
 136            abs_path: self.abs_path.clone(),
 137            ignores_by_parent_abs_path: self.ignores_by_parent_abs_path.clone(),
 138            git_repositories: self.git_repositories.iter().cloned().collect(),
 139            removed_entry_ids: self.removed_entry_ids.clone(),
 140            next_entry_id: self.next_entry_id.clone(),
 141            snapshot: self.snapshot.clone(),
 142            extension_counts: self.extension_counts.clone(),
 143        }
 144    }
 145}
 146
 147impl Deref for LocalSnapshot {
 148    type Target = Snapshot;
 149
 150    fn deref(&self) -> &Self::Target {
 151        &self.snapshot
 152    }
 153}
 154
 155impl DerefMut for LocalSnapshot {
 156    fn deref_mut(&mut self) -> &mut Self::Target {
 157        &mut self.snapshot
 158    }
 159}
 160
 161#[derive(Clone, Debug)]
 162enum ScanState {
 163    Idle,
 164    /// The worktree is performing its initial scan of the filesystem.
 165    Initializing,
 166    /// The worktree is updating in response to filesystem events.
 167    Updating,
 168    Err(Arc<anyhow::Error>),
 169}
 170
 171struct ShareState {
 172    project_id: u64,
 173    snapshots_tx: watch::Sender<LocalSnapshot>,
 174    _maintain_remote_snapshot: Option<Task<Option<()>>>,
 175}
 176
 177pub enum Event {
 178    UpdatedEntries,
 179    UpdatedGitRepositories(Vec<GitRepositoryEntry>),
 180}
 181
 182impl Entity for Worktree {
 183    type Event = Event;
 184}
 185
 186impl Worktree {
 187    pub async fn local(
 188        client: Arc<Client>,
 189        path: impl Into<Arc<Path>>,
 190        visible: bool,
 191        fs: Arc<dyn Fs>,
 192        next_entry_id: Arc<AtomicUsize>,
 193        cx: &mut AsyncAppContext,
 194    ) -> Result<ModelHandle<Self>> {
 195        let (tree, scan_states_tx) =
 196            LocalWorktree::create(client, path, visible, fs.clone(), next_entry_id, cx).await?;
 197        tree.update(cx, |tree, cx| {
 198            let tree = tree.as_local_mut().unwrap();
 199            let abs_path = tree.abs_path().clone();
 200            let background_snapshot = tree.background_snapshot.clone();
 201            let background = cx.background().clone();
 202            tree._background_scanner_task = Some(cx.background().spawn(async move {
 203                let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 204                let scanner =
 205                    BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
 206                scanner.run(events).await;
 207            }));
 208        });
 209        Ok(tree)
 210    }
 211
 212    pub fn remote(
 213        project_remote_id: u64,
 214        replica_id: ReplicaId,
 215        worktree: proto::WorktreeMetadata,
 216        client: Arc<Client>,
 217        cx: &mut MutableAppContext,
 218    ) -> ModelHandle<Self> {
 219        let remote_id = worktree.id;
 220        let root_char_bag: CharBag = worktree
 221            .root_name
 222            .chars()
 223            .map(|c| c.to_ascii_lowercase())
 224            .collect();
 225        let root_name = worktree.root_name.clone();
 226        let visible = worktree.visible;
 227        let snapshot = Snapshot {
 228            id: WorktreeId(remote_id as usize),
 229            root_name,
 230            root_char_bag,
 231            entries_by_path: Default::default(),
 232            entries_by_id: Default::default(),
 233            scan_id: 0,
 234            is_complete: false,
 235        };
 236
 237        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 238        let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 239        let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 240        let worktree_handle = cx.add_model(|_: &mut ModelContext<Worktree>| {
 241            Worktree::Remote(RemoteWorktree {
 242                project_id: project_remote_id,
 243                replica_id,
 244                snapshot: snapshot.clone(),
 245                background_snapshot: background_snapshot.clone(),
 246                updates_tx: Some(updates_tx),
 247                snapshot_subscriptions: Default::default(),
 248                client: client.clone(),
 249                diagnostic_summaries: Default::default(),
 250                visible,
 251            })
 252        });
 253
 254        cx.background()
 255            .spawn(async move {
 256                while let Some(update) = updates_rx.next().await {
 257                    if let Err(error) = background_snapshot.lock().apply_remote_update(update) {
 258                        log::error!("error applying worktree update: {}", error);
 259                    }
 260                    snapshot_updated_tx.send(()).await.ok();
 261                }
 262            })
 263            .detach();
 264
 265        cx.spawn(|mut cx| {
 266            let this = worktree_handle.downgrade();
 267            async move {
 268                while (snapshot_updated_rx.recv().await).is_some() {
 269                    if let Some(this) = this.upgrade(&cx) {
 270                        this.update(&mut cx, |this, cx| {
 271                            this.poll_snapshot(cx);
 272                            let this = this.as_remote_mut().unwrap();
 273                            while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 274                                if this.observed_snapshot(*scan_id) {
 275                                    let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 276                                    let _ = tx.send(());
 277                                } else {
 278                                    break;
 279                                }
 280                            }
 281                        });
 282                    } else {
 283                        break;
 284                    }
 285                }
 286            }
 287        })
 288        .detach();
 289
 290        worktree_handle
 291    }
 292
 293    pub fn as_local(&self) -> Option<&LocalWorktree> {
 294        if let Worktree::Local(worktree) = self {
 295            Some(worktree)
 296        } else {
 297            None
 298        }
 299    }
 300
 301    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 302        if let Worktree::Remote(worktree) = self {
 303            Some(worktree)
 304        } else {
 305            None
 306        }
 307    }
 308
 309    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 310        if let Worktree::Local(worktree) = self {
 311            Some(worktree)
 312        } else {
 313            None
 314        }
 315    }
 316
 317    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 318        if let Worktree::Remote(worktree) = self {
 319            Some(worktree)
 320        } else {
 321            None
 322        }
 323    }
 324
 325    pub fn is_local(&self) -> bool {
 326        matches!(self, Worktree::Local(_))
 327    }
 328
 329    pub fn is_remote(&self) -> bool {
 330        !self.is_local()
 331    }
 332
 333    pub fn snapshot(&self) -> Snapshot {
 334        match self {
 335            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 336            Worktree::Remote(worktree) => worktree.snapshot(),
 337        }
 338    }
 339
 340    pub fn scan_id(&self) -> usize {
 341        match self {
 342            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 343            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 344        }
 345    }
 346
 347    pub fn is_visible(&self) -> bool {
 348        match self {
 349            Worktree::Local(worktree) => worktree.visible,
 350            Worktree::Remote(worktree) => worktree.visible,
 351        }
 352    }
 353
 354    pub fn replica_id(&self) -> ReplicaId {
 355        match self {
 356            Worktree::Local(_) => 0,
 357            Worktree::Remote(worktree) => worktree.replica_id,
 358        }
 359    }
 360
 361    pub fn diagnostic_summaries(
 362        &self,
 363    ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + '_ {
 364        match self {
 365            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 366            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 367        }
 368        .iter()
 369        .map(|(path, summary)| (path.0.clone(), *summary))
 370    }
 371
 372    fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
 373        match self {
 374            Self::Local(worktree) => worktree.poll_snapshot(false, cx),
 375            Self::Remote(worktree) => worktree.poll_snapshot(cx),
 376        };
 377    }
 378}
 379
 380impl LocalWorktree {
 381    async fn create(
 382        client: Arc<Client>,
 383        path: impl Into<Arc<Path>>,
 384        visible: bool,
 385        fs: Arc<dyn Fs>,
 386        next_entry_id: Arc<AtomicUsize>,
 387        cx: &mut AsyncAppContext,
 388    ) -> Result<(ModelHandle<Worktree>, UnboundedSender<ScanState>)> {
 389        let abs_path = path.into();
 390        let path: Arc<Path> = Arc::from(Path::new(""));
 391
 392        // After determining whether the root entry is a file or a directory, populate the
 393        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 394        let root_name = abs_path
 395            .file_name()
 396            .map_or(String::new(), |f| f.to_string_lossy().to_string());
 397        let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
 398        let metadata = fs
 399            .metadata(&abs_path)
 400            .await
 401            .context("failed to stat worktree path")?;
 402
 403        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 404        let (mut last_scan_state_tx, last_scan_state_rx) =
 405            watch::channel_with(ScanState::Initializing);
 406        let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 407            let mut snapshot = LocalSnapshot {
 408                abs_path,
 409                ignores_by_parent_abs_path: Default::default(),
 410                git_repositories: Default::default(),
 411                removed_entry_ids: Default::default(),
 412                next_entry_id,
 413                snapshot: Snapshot {
 414                    id: WorktreeId::from_usize(cx.model_id()),
 415                    root_name: root_name.clone(),
 416                    root_char_bag,
 417                    entries_by_path: Default::default(),
 418                    entries_by_id: Default::default(),
 419                    scan_id: 0,
 420                    is_complete: true,
 421                },
 422                extension_counts: Default::default(),
 423            };
 424            if let Some(metadata) = metadata {
 425                let entry = Entry::new(
 426                    path,
 427                    &metadata,
 428                    &snapshot.next_entry_id,
 429                    snapshot.root_char_bag,
 430                );
 431                snapshot.insert_entry(entry, fs.as_ref());
 432            }
 433
 434            let tree = Self {
 435                snapshot: snapshot.clone(),
 436                background_snapshot: Arc::new(Mutex::new(snapshot)),
 437                last_scan_state_rx,
 438                _background_scanner_task: None,
 439                share: None,
 440                poll_task: None,
 441                diagnostics: Default::default(),
 442                diagnostic_summaries: Default::default(),
 443                client,
 444                fs,
 445                visible,
 446            };
 447
 448            cx.spawn_weak(|this, mut cx| async move {
 449                while let Some(scan_state) = scan_states_rx.next().await {
 450                    if let Some(this) = this.upgrade(&cx) {
 451                        last_scan_state_tx.blocking_send(scan_state).ok();
 452                        this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 453                    } else {
 454                        break;
 455                    }
 456                }
 457            })
 458            .detach();
 459
 460            Worktree::Local(tree)
 461        });
 462
 463        Ok((tree, scan_states_tx))
 464    }
 465
 466    pub fn contains_abs_path(&self, path: &Path) -> bool {
 467        path.starts_with(&self.abs_path)
 468    }
 469
 470    fn absolutize(&self, path: &Path) -> PathBuf {
 471        if path.file_name().is_some() {
 472            self.abs_path.join(path)
 473        } else {
 474            self.abs_path.to_path_buf()
 475        }
 476    }
 477
 478    pub(crate) fn load_buffer(
 479        &mut self,
 480        path: &Path,
 481        cx: &mut ModelContext<Worktree>,
 482    ) -> Task<Result<ModelHandle<Buffer>>> {
 483        let path = Arc::from(path);
 484        cx.spawn(move |this, mut cx| async move {
 485            let (file, contents, diff_base) = this
 486                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 487                .await?;
 488            Ok(cx.add_model(|cx| {
 489                let mut buffer = Buffer::from_file(0, contents, diff_base, Arc::new(file), cx);
 490                buffer.git_diff_recalc(cx);
 491                buffer
 492            }))
 493        })
 494    }
 495
 496    pub fn diagnostics_for_path(&self, path: &Path) -> Option<Vec<DiagnosticEntry<PointUtf16>>> {
 497        self.diagnostics.get(path).cloned()
 498    }
 499
 500    pub fn update_diagnostics(
 501        &mut self,
 502        language_server_id: usize,
 503        worktree_path: Arc<Path>,
 504        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
 505        _: &mut ModelContext<Worktree>,
 506    ) -> Result<bool> {
 507        self.diagnostics.remove(&worktree_path);
 508        let old_summary = self
 509            .diagnostic_summaries
 510            .remove(&PathKey(worktree_path.clone()))
 511            .unwrap_or_default();
 512        let new_summary = DiagnosticSummary::new(language_server_id, &diagnostics);
 513        if !new_summary.is_empty() {
 514            self.diagnostic_summaries
 515                .insert(PathKey(worktree_path.clone()), new_summary);
 516            self.diagnostics.insert(worktree_path.clone(), diagnostics);
 517        }
 518
 519        let updated = !old_summary.is_empty() || !new_summary.is_empty();
 520        if updated {
 521            if let Some(share) = self.share.as_ref() {
 522                self.client
 523                    .send(proto::UpdateDiagnosticSummary {
 524                        project_id: share.project_id,
 525                        worktree_id: self.id().to_proto(),
 526                        summary: Some(proto::DiagnosticSummary {
 527                            path: worktree_path.to_string_lossy().to_string(),
 528                            language_server_id: language_server_id as u64,
 529                            error_count: new_summary.error_count as u32,
 530                            warning_count: new_summary.warning_count as u32,
 531                        }),
 532                    })
 533                    .log_err();
 534            }
 535        }
 536
 537        Ok(updated)
 538    }
 539
 540    fn poll_snapshot(&mut self, force: bool, cx: &mut ModelContext<Worktree>) {
 541        self.poll_task.take();
 542
 543        match self.scan_state() {
 544            ScanState::Idle => {
 545                let new_snapshot = self.background_snapshot.lock().clone();
 546                let updated_repos = Self::changed_repos(
 547                    &self.snapshot.git_repositories,
 548                    &new_snapshot.git_repositories,
 549                );
 550                self.snapshot = new_snapshot;
 551
 552                if let Some(share) = self.share.as_mut() {
 553                    *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
 554                }
 555
 556                cx.emit(Event::UpdatedEntries);
 557
 558                if !updated_repos.is_empty() {
 559                    cx.emit(Event::UpdatedGitRepositories(updated_repos));
 560                }
 561            }
 562
 563            ScanState::Initializing => {
 564                let is_fake_fs = self.fs.is_fake();
 565
 566                let new_snapshot = self.background_snapshot.lock().clone();
 567                let updated_repos = Self::changed_repos(
 568                    &self.snapshot.git_repositories,
 569                    &new_snapshot.git_repositories,
 570                );
 571                self.snapshot = new_snapshot;
 572
 573                self.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
 574                    if is_fake_fs {
 575                        #[cfg(any(test, feature = "test-support"))]
 576                        cx.background().simulate_random_delay().await;
 577                    } else {
 578                        smol::Timer::after(Duration::from_millis(100)).await;
 579                    }
 580                    if let Some(this) = this.upgrade(&cx) {
 581                        this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 582                    }
 583                }));
 584
 585                cx.emit(Event::UpdatedEntries);
 586
 587                if !updated_repos.is_empty() {
 588                    cx.emit(Event::UpdatedGitRepositories(updated_repos));
 589                }
 590            }
 591
 592            _ => {
 593                if force {
 594                    self.snapshot = self.background_snapshot.lock().clone();
 595                }
 596            }
 597        }
 598
 599        cx.notify();
 600    }
 601
 602    fn changed_repos(
 603        old_repos: &[GitRepositoryEntry],
 604        new_repos: &[GitRepositoryEntry],
 605    ) -> Vec<GitRepositoryEntry> {
 606        fn diff<'a>(
 607            a: &'a [GitRepositoryEntry],
 608            b: &'a [GitRepositoryEntry],
 609            updated: &mut HashMap<&'a Path, GitRepositoryEntry>,
 610        ) {
 611            for a_repo in a {
 612                let matched = b.iter().find(|b_repo| {
 613                    a_repo.git_dir_path == b_repo.git_dir_path && a_repo.scan_id == b_repo.scan_id
 614                });
 615
 616                if matched.is_none() {
 617                    updated.insert(a_repo.git_dir_path.as_ref(), a_repo.clone());
 618                }
 619            }
 620        }
 621
 622        let mut updated = HashMap::<&Path, GitRepositoryEntry>::default();
 623
 624        diff(old_repos, new_repos, &mut updated);
 625        diff(new_repos, old_repos, &mut updated);
 626
 627        updated.into_values().collect()
 628    }
 629
 630    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 631        let mut scan_state_rx = self.last_scan_state_rx.clone();
 632        async move {
 633            let mut scan_state = Some(scan_state_rx.borrow().clone());
 634            while let Some(ScanState::Initializing | ScanState::Updating) = scan_state {
 635                scan_state = scan_state_rx.recv().await;
 636            }
 637        }
 638    }
 639
 640    fn scan_state(&self) -> ScanState {
 641        self.last_scan_state_rx.borrow().clone()
 642    }
 643
 644    pub fn snapshot(&self) -> LocalSnapshot {
 645        self.snapshot.clone()
 646    }
 647
 648    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 649        proto::WorktreeMetadata {
 650            id: self.id().to_proto(),
 651            root_name: self.root_name().to_string(),
 652            visible: self.visible,
 653        }
 654    }
 655
 656    fn load(
 657        &self,
 658        path: &Path,
 659        cx: &mut ModelContext<Worktree>,
 660    ) -> Task<Result<(File, String, Option<String>)>> {
 661        let handle = cx.handle();
 662        let path = Arc::from(path);
 663        let abs_path = self.absolutize(&path);
 664        let fs = self.fs.clone();
 665        let snapshot = self.snapshot();
 666
 667        cx.spawn(|this, mut cx| async move {
 668            let text = fs.load(&abs_path).await?;
 669
 670            let diff_base = if let Some(repo) = snapshot.repo_for(&path) {
 671                if let Ok(repo_relative) = path.strip_prefix(repo.content_path) {
 672                    let repo_relative = repo_relative.to_owned();
 673                    cx.background()
 674                        .spawn(async move { repo.repo.lock().load_index_text(&repo_relative) })
 675                        .await
 676                } else {
 677                    None
 678                }
 679            } else {
 680                None
 681            };
 682
 683            // Eagerly populate the snapshot with an updated entry for the loaded file
 684            let entry = this
 685                .update(&mut cx, |this, cx| {
 686                    this.as_local()
 687                        .unwrap()
 688                        .refresh_entry(path, abs_path, None, cx)
 689                })
 690                .await?;
 691
 692            Ok((
 693                File {
 694                    entry_id: Some(entry.id),
 695                    worktree: handle,
 696                    path: entry.path,
 697                    mtime: entry.mtime,
 698                    is_local: true,
 699                },
 700                text,
 701                diff_base,
 702            ))
 703        })
 704    }
 705
 706    pub fn save_buffer_as(
 707        &self,
 708        buffer_handle: ModelHandle<Buffer>,
 709        path: impl Into<Arc<Path>>,
 710        cx: &mut ModelContext<Worktree>,
 711    ) -> Task<Result<()>> {
 712        let buffer = buffer_handle.read(cx);
 713        let text = buffer.as_rope().clone();
 714        let fingerprint = text.fingerprint();
 715        let version = buffer.version();
 716        let save = self.write_file(path, text, buffer.line_ending(), cx);
 717        let handle = cx.handle();
 718        cx.as_mut().spawn(|mut cx| async move {
 719            let entry = save.await?;
 720            let file = File {
 721                entry_id: Some(entry.id),
 722                worktree: handle,
 723                path: entry.path,
 724                mtime: entry.mtime,
 725                is_local: true,
 726            };
 727
 728            buffer_handle.update(&mut cx, |buffer, cx| {
 729                buffer.did_save(version, fingerprint, file.mtime, Some(Arc::new(file)), cx);
 730            });
 731
 732            Ok(())
 733        })
 734    }
 735
 736    pub fn create_entry(
 737        &self,
 738        path: impl Into<Arc<Path>>,
 739        is_dir: bool,
 740        cx: &mut ModelContext<Worktree>,
 741    ) -> Task<Result<Entry>> {
 742        self.write_entry_internal(
 743            path,
 744            if is_dir {
 745                None
 746            } else {
 747                Some(Default::default())
 748            },
 749            cx,
 750        )
 751    }
 752
 753    pub fn write_file(
 754        &self,
 755        path: impl Into<Arc<Path>>,
 756        text: Rope,
 757        line_ending: LineEnding,
 758        cx: &mut ModelContext<Worktree>,
 759    ) -> Task<Result<Entry>> {
 760        self.write_entry_internal(path, Some((text, line_ending)), cx)
 761    }
 762
 763    pub fn delete_entry(
 764        &self,
 765        entry_id: ProjectEntryId,
 766        cx: &mut ModelContext<Worktree>,
 767    ) -> Option<Task<Result<()>>> {
 768        let entry = self.entry_for_id(entry_id)?.clone();
 769        let abs_path = self.absolutize(&entry.path);
 770        let delete = cx.background().spawn({
 771            let fs = self.fs.clone();
 772            let abs_path = abs_path;
 773            async move {
 774                if entry.is_file() {
 775                    fs.remove_file(&abs_path, Default::default()).await
 776                } else {
 777                    fs.remove_dir(
 778                        &abs_path,
 779                        RemoveOptions {
 780                            recursive: true,
 781                            ignore_if_not_exists: false,
 782                        },
 783                    )
 784                    .await
 785                }
 786            }
 787        });
 788
 789        Some(cx.spawn(|this, mut cx| async move {
 790            delete.await?;
 791            this.update(&mut cx, |this, cx| {
 792                let this = this.as_local_mut().unwrap();
 793                {
 794                    let mut snapshot = this.background_snapshot.lock();
 795                    snapshot.delete_entry(entry_id);
 796                }
 797                this.poll_snapshot(true, cx);
 798            });
 799            Ok(())
 800        }))
 801    }
 802
 803    pub fn rename_entry(
 804        &self,
 805        entry_id: ProjectEntryId,
 806        new_path: impl Into<Arc<Path>>,
 807        cx: &mut ModelContext<Worktree>,
 808    ) -> Option<Task<Result<Entry>>> {
 809        let old_path = self.entry_for_id(entry_id)?.path.clone();
 810        let new_path = new_path.into();
 811        let abs_old_path = self.absolutize(&old_path);
 812        let abs_new_path = self.absolutize(&new_path);
 813        let rename = cx.background().spawn({
 814            let fs = self.fs.clone();
 815            let abs_new_path = abs_new_path.clone();
 816            async move {
 817                fs.rename(&abs_old_path, &abs_new_path, Default::default())
 818                    .await
 819            }
 820        });
 821
 822        Some(cx.spawn(|this, mut cx| async move {
 823            rename.await?;
 824            let entry = this
 825                .update(&mut cx, |this, cx| {
 826                    this.as_local_mut().unwrap().refresh_entry(
 827                        new_path.clone(),
 828                        abs_new_path,
 829                        Some(old_path),
 830                        cx,
 831                    )
 832                })
 833                .await?;
 834            Ok(entry)
 835        }))
 836    }
 837
 838    pub fn copy_entry(
 839        &self,
 840        entry_id: ProjectEntryId,
 841        new_path: impl Into<Arc<Path>>,
 842        cx: &mut ModelContext<Worktree>,
 843    ) -> Option<Task<Result<Entry>>> {
 844        let old_path = self.entry_for_id(entry_id)?.path.clone();
 845        let new_path = new_path.into();
 846        let abs_old_path = self.absolutize(&old_path);
 847        let abs_new_path = self.absolutize(&new_path);
 848        let copy = cx.background().spawn({
 849            let fs = self.fs.clone();
 850            let abs_new_path = abs_new_path.clone();
 851            async move {
 852                copy_recursive(
 853                    fs.as_ref(),
 854                    &abs_old_path,
 855                    &abs_new_path,
 856                    Default::default(),
 857                )
 858                .await
 859            }
 860        });
 861
 862        Some(cx.spawn(|this, mut cx| async move {
 863            copy.await?;
 864            let entry = this
 865                .update(&mut cx, |this, cx| {
 866                    this.as_local_mut().unwrap().refresh_entry(
 867                        new_path.clone(),
 868                        abs_new_path,
 869                        None,
 870                        cx,
 871                    )
 872                })
 873                .await?;
 874            Ok(entry)
 875        }))
 876    }
 877
 878    fn write_entry_internal(
 879        &self,
 880        path: impl Into<Arc<Path>>,
 881        text_if_file: Option<(Rope, LineEnding)>,
 882        cx: &mut ModelContext<Worktree>,
 883    ) -> Task<Result<Entry>> {
 884        let path = path.into();
 885        let abs_path = self.absolutize(&path);
 886        let write = cx.background().spawn({
 887            let fs = self.fs.clone();
 888            let abs_path = abs_path.clone();
 889            async move {
 890                if let Some((text, line_ending)) = text_if_file {
 891                    fs.save(&abs_path, &text, line_ending).await
 892                } else {
 893                    fs.create_dir(&abs_path).await
 894                }
 895            }
 896        });
 897
 898        cx.spawn(|this, mut cx| async move {
 899            write.await?;
 900            let entry = this
 901                .update(&mut cx, |this, cx| {
 902                    this.as_local_mut()
 903                        .unwrap()
 904                        .refresh_entry(path, abs_path, None, cx)
 905                })
 906                .await?;
 907            Ok(entry)
 908        })
 909    }
 910
 911    fn refresh_entry(
 912        &self,
 913        path: Arc<Path>,
 914        abs_path: PathBuf,
 915        old_path: Option<Arc<Path>>,
 916        cx: &mut ModelContext<Worktree>,
 917    ) -> Task<Result<Entry>> {
 918        let fs = self.fs.clone();
 919        let root_char_bag;
 920        let next_entry_id;
 921        {
 922            let snapshot = self.background_snapshot.lock();
 923            root_char_bag = snapshot.root_char_bag;
 924            next_entry_id = snapshot.next_entry_id.clone();
 925        }
 926        cx.spawn_weak(|this, mut cx| async move {
 927            let metadata = fs
 928                .metadata(&abs_path)
 929                .await?
 930                .ok_or_else(|| anyhow!("could not read saved file metadata"))?;
 931            let this = this
 932                .upgrade(&cx)
 933                .ok_or_else(|| anyhow!("worktree was dropped"))?;
 934            this.update(&mut cx, |this, cx| {
 935                let this = this.as_local_mut().unwrap();
 936                let inserted_entry;
 937                {
 938                    let mut snapshot = this.background_snapshot.lock();
 939                    let mut entry = Entry::new(path, &metadata, &next_entry_id, root_char_bag);
 940                    entry.is_ignored = snapshot
 941                        .ignore_stack_for_abs_path(&abs_path, entry.is_dir())
 942                        .is_abs_path_ignored(&abs_path, entry.is_dir());
 943                    if let Some(old_path) = old_path {
 944                        snapshot.remove_path(&old_path);
 945                    }
 946                    inserted_entry = snapshot.insert_entry(entry, fs.as_ref());
 947                    snapshot.scan_id += 1;
 948                }
 949                this.poll_snapshot(true, cx);
 950                Ok(inserted_entry)
 951            })
 952        })
 953    }
 954
 955    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 956        let (share_tx, share_rx) = oneshot::channel();
 957
 958        if self.share.is_some() {
 959            let _ = share_tx.send(Ok(()));
 960        } else {
 961            let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
 962            let rpc = self.client.clone();
 963            let worktree_id = cx.model_id() as u64;
 964            let maintain_remote_snapshot = cx.background().spawn({
 965                let rpc = rpc;
 966                let diagnostic_summaries = self.diagnostic_summaries.clone();
 967                async move {
 968                    let mut prev_snapshot = match snapshots_rx.recv().await {
 969                        Some(snapshot) => {
 970                            let update = proto::UpdateWorktree {
 971                                project_id,
 972                                worktree_id,
 973                                root_name: snapshot.root_name().to_string(),
 974                                updated_entries: snapshot
 975                                    .entries_by_path
 976                                    .iter()
 977                                    .map(Into::into)
 978                                    .collect(),
 979                                removed_entries: Default::default(),
 980                                scan_id: snapshot.scan_id as u64,
 981                                is_last_update: true,
 982                            };
 983                            if let Err(error) = send_worktree_update(&rpc, update).await {
 984                                let _ = share_tx.send(Err(error));
 985                                return Err(anyhow!("failed to send initial update worktree"));
 986                            } else {
 987                                let _ = share_tx.send(Ok(()));
 988                                snapshot
 989                            }
 990                        }
 991                        None => {
 992                            share_tx
 993                                .send(Err(anyhow!("worktree dropped before share completed")))
 994                                .ok();
 995                            return Err(anyhow!("failed to send initial update worktree"));
 996                        }
 997                    };
 998
 999                    for (path, summary) in diagnostic_summaries.iter() {
1000                        rpc.send(proto::UpdateDiagnosticSummary {
1001                            project_id,
1002                            worktree_id,
1003                            summary: Some(summary.to_proto(&path.0)),
1004                        })?;
1005                    }
1006
1007                    while let Some(snapshot) = snapshots_rx.recv().await {
1008                        send_worktree_update(
1009                            &rpc,
1010                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, true),
1011                        )
1012                        .await?;
1013                        prev_snapshot = snapshot;
1014                    }
1015
1016                    Ok::<_, anyhow::Error>(())
1017                }
1018                .log_err()
1019            });
1020            self.share = Some(ShareState {
1021                project_id,
1022                snapshots_tx,
1023                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
1024            });
1025        }
1026
1027        cx.foreground().spawn(async move {
1028            share_rx
1029                .await
1030                .unwrap_or_else(|_| Err(anyhow!("share ended")))
1031        })
1032    }
1033
1034    pub fn unshare(&mut self) {
1035        self.share.take();
1036    }
1037
1038    pub fn is_shared(&self) -> bool {
1039        self.share.is_some()
1040    }
1041
1042    pub fn send_extension_counts(&self, project_id: u64) {
1043        let mut extensions = Vec::new();
1044        let mut counts = Vec::new();
1045
1046        for (extension, count) in self.extension_counts() {
1047            extensions.push(extension.to_string_lossy().to_string());
1048            counts.push(*count as u32);
1049        }
1050
1051        self.client
1052            .send(proto::UpdateWorktreeExtensions {
1053                project_id,
1054                worktree_id: self.id().to_proto(),
1055                extensions,
1056                counts,
1057            })
1058            .log_err();
1059    }
1060}
1061
1062impl RemoteWorktree {
1063    fn snapshot(&self) -> Snapshot {
1064        self.snapshot.clone()
1065    }
1066
1067    fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
1068        self.snapshot = self.background_snapshot.lock().clone();
1069        cx.emit(Event::UpdatedEntries);
1070        cx.notify();
1071    }
1072
1073    pub fn disconnected_from_host(&mut self) {
1074        self.updates_tx.take();
1075        self.snapshot_subscriptions.clear();
1076    }
1077
1078    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1079        if let Some(updates_tx) = &self.updates_tx {
1080            updates_tx
1081                .unbounded_send(update)
1082                .expect("consumer runs to completion");
1083        }
1084    }
1085
1086    fn observed_snapshot(&self, scan_id: usize) -> bool {
1087        self.scan_id > scan_id || (self.scan_id == scan_id && self.is_complete)
1088    }
1089
1090    fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = ()> {
1091        let (tx, rx) = oneshot::channel();
1092        if self.observed_snapshot(scan_id) {
1093            let _ = tx.send(());
1094        } else {
1095            match self
1096                .snapshot_subscriptions
1097                .binary_search_by_key(&scan_id, |probe| probe.0)
1098            {
1099                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1100            }
1101        }
1102
1103        async move {
1104            let _ = rx.await;
1105        }
1106    }
1107
1108    pub fn update_diagnostic_summary(
1109        &mut self,
1110        path: Arc<Path>,
1111        summary: &proto::DiagnosticSummary,
1112    ) {
1113        let summary = DiagnosticSummary {
1114            language_server_id: summary.language_server_id as usize,
1115            error_count: summary.error_count as usize,
1116            warning_count: summary.warning_count as usize,
1117        };
1118        if summary.is_empty() {
1119            self.diagnostic_summaries.remove(&PathKey(path));
1120        } else {
1121            self.diagnostic_summaries.insert(PathKey(path), summary);
1122        }
1123    }
1124
1125    pub fn insert_entry(
1126        &mut self,
1127        entry: proto::Entry,
1128        scan_id: usize,
1129        cx: &mut ModelContext<Worktree>,
1130    ) -> Task<Result<Entry>> {
1131        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1132        cx.spawn(|this, mut cx| async move {
1133            wait_for_snapshot.await;
1134            this.update(&mut cx, |worktree, _| {
1135                let worktree = worktree.as_remote_mut().unwrap();
1136                let mut snapshot = worktree.background_snapshot.lock();
1137                let entry = snapshot.insert_entry(entry);
1138                worktree.snapshot = snapshot.clone();
1139                entry
1140            })
1141        })
1142    }
1143
1144    pub(crate) fn delete_entry(
1145        &mut self,
1146        id: ProjectEntryId,
1147        scan_id: usize,
1148        cx: &mut ModelContext<Worktree>,
1149    ) -> Task<Result<()>> {
1150        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1151        cx.spawn(|this, mut cx| async move {
1152            wait_for_snapshot.await;
1153            this.update(&mut cx, |worktree, _| {
1154                let worktree = worktree.as_remote_mut().unwrap();
1155                let mut snapshot = worktree.background_snapshot.lock();
1156                snapshot.delete_entry(id);
1157                worktree.snapshot = snapshot.clone();
1158            });
1159            Ok(())
1160        })
1161    }
1162}
1163
1164impl Snapshot {
1165    pub fn id(&self) -> WorktreeId {
1166        self.id
1167    }
1168
1169    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1170        self.entries_by_id.get(&entry_id, &()).is_some()
1171    }
1172
1173    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1174        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1175        let old_entry = self.entries_by_id.insert_or_replace(
1176            PathEntry {
1177                id: entry.id,
1178                path: entry.path.clone(),
1179                is_ignored: entry.is_ignored,
1180                scan_id: 0,
1181            },
1182            &(),
1183        );
1184        if let Some(old_entry) = old_entry {
1185            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1186        }
1187        self.entries_by_path.insert_or_replace(entry.clone(), &());
1188        Ok(entry)
1189    }
1190
1191    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1192        if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1193            self.entries_by_path = {
1194                let mut cursor = self.entries_by_path.cursor();
1195                let mut new_entries_by_path =
1196                    cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1197                while let Some(entry) = cursor.item() {
1198                    if entry.path.starts_with(&removed_entry.path) {
1199                        self.entries_by_id.remove(&entry.id, &());
1200                        cursor.next(&());
1201                    } else {
1202                        break;
1203                    }
1204                }
1205                new_entries_by_path.push_tree(cursor.suffix(&()), &());
1206                new_entries_by_path
1207            };
1208
1209            true
1210        } else {
1211            false
1212        }
1213    }
1214
1215    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1216        let mut entries_by_path_edits = Vec::new();
1217        let mut entries_by_id_edits = Vec::new();
1218        for entry_id in update.removed_entries {
1219            let entry = self
1220                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1221                .ok_or_else(|| anyhow!("unknown entry {}", entry_id))?;
1222            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1223            entries_by_id_edits.push(Edit::Remove(entry.id));
1224        }
1225
1226        for entry in update.updated_entries {
1227            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1228            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1229                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1230            }
1231            entries_by_id_edits.push(Edit::Insert(PathEntry {
1232                id: entry.id,
1233                path: entry.path.clone(),
1234                is_ignored: entry.is_ignored,
1235                scan_id: 0,
1236            }));
1237            entries_by_path_edits.push(Edit::Insert(entry));
1238        }
1239
1240        self.entries_by_path.edit(entries_by_path_edits, &());
1241        self.entries_by_id.edit(entries_by_id_edits, &());
1242        self.scan_id = update.scan_id as usize;
1243        self.is_complete = update.is_last_update;
1244
1245        Ok(())
1246    }
1247
1248    pub fn file_count(&self) -> usize {
1249        self.entries_by_path.summary().file_count
1250    }
1251
1252    pub fn visible_file_count(&self) -> usize {
1253        self.entries_by_path.summary().visible_file_count
1254    }
1255
1256    fn traverse_from_offset(
1257        &self,
1258        include_dirs: bool,
1259        include_ignored: bool,
1260        start_offset: usize,
1261    ) -> Traversal {
1262        let mut cursor = self.entries_by_path.cursor();
1263        cursor.seek(
1264            &TraversalTarget::Count {
1265                count: start_offset,
1266                include_dirs,
1267                include_ignored,
1268            },
1269            Bias::Right,
1270            &(),
1271        );
1272        Traversal {
1273            cursor,
1274            include_dirs,
1275            include_ignored,
1276        }
1277    }
1278
1279    fn traverse_from_path(
1280        &self,
1281        include_dirs: bool,
1282        include_ignored: bool,
1283        path: &Path,
1284    ) -> Traversal {
1285        let mut cursor = self.entries_by_path.cursor();
1286        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1287        Traversal {
1288            cursor,
1289            include_dirs,
1290            include_ignored,
1291        }
1292    }
1293
1294    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1295        self.traverse_from_offset(false, include_ignored, start)
1296    }
1297
1298    pub fn entries(&self, include_ignored: bool) -> Traversal {
1299        self.traverse_from_offset(true, include_ignored, 0)
1300    }
1301
1302    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1303        let empty_path = Path::new("");
1304        self.entries_by_path
1305            .cursor::<()>()
1306            .filter(move |entry| entry.path.as_ref() != empty_path)
1307            .map(|entry| &entry.path)
1308    }
1309
1310    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1311        let mut cursor = self.entries_by_path.cursor();
1312        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1313        let traversal = Traversal {
1314            cursor,
1315            include_dirs: true,
1316            include_ignored: true,
1317        };
1318        ChildEntriesIter {
1319            traversal,
1320            parent_path,
1321        }
1322    }
1323
1324    pub fn root_entry(&self) -> Option<&Entry> {
1325        self.entry_for_path("")
1326    }
1327
1328    pub fn root_name(&self) -> &str {
1329        &self.root_name
1330    }
1331
1332    pub fn scan_id(&self) -> usize {
1333        self.scan_id
1334    }
1335
1336    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1337        let path = path.as_ref();
1338        self.traverse_from_path(true, true, path)
1339            .entry()
1340            .and_then(|entry| {
1341                if entry.path.as_ref() == path {
1342                    Some(entry)
1343                } else {
1344                    None
1345                }
1346            })
1347    }
1348
1349    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1350        let entry = self.entries_by_id.get(&id, &())?;
1351        self.entry_for_path(&entry.path)
1352    }
1353
1354    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1355        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1356    }
1357}
1358
1359impl LocalSnapshot {
1360    pub fn abs_path(&self) -> &Arc<Path> {
1361        &self.abs_path
1362    }
1363
1364    pub fn extension_counts(&self) -> &HashMap<OsString, usize> {
1365        &self.extension_counts
1366    }
1367
1368    // Gives the most specific git repository for a given path
1369    pub(crate) fn repo_for(&self, path: &Path) -> Option<GitRepositoryEntry> {
1370        self.git_repositories
1371            .iter()
1372            .rev() //git_repository is ordered lexicographically
1373            .find(|repo| repo.manages(path))
1374            .cloned()
1375    }
1376
1377    pub(crate) fn in_dot_git(&mut self, path: &Path) -> Option<&mut GitRepositoryEntry> {
1378        // Git repositories cannot be nested, so we don't need to reverse the order
1379        self.git_repositories
1380            .iter_mut()
1381            .find(|repo| repo.in_dot_git(path))
1382    }
1383
1384    #[cfg(test)]
1385    pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1386        let root_name = self.root_name.clone();
1387        proto::UpdateWorktree {
1388            project_id,
1389            worktree_id: self.id().to_proto(),
1390            root_name,
1391            updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1392            removed_entries: Default::default(),
1393            scan_id: self.scan_id as u64,
1394            is_last_update: true,
1395        }
1396    }
1397
1398    pub(crate) fn build_update(
1399        &self,
1400        other: &Self,
1401        project_id: u64,
1402        worktree_id: u64,
1403        include_ignored: bool,
1404    ) -> proto::UpdateWorktree {
1405        let mut updated_entries = Vec::new();
1406        let mut removed_entries = Vec::new();
1407        let mut self_entries = self
1408            .entries_by_id
1409            .cursor::<()>()
1410            .filter(|e| include_ignored || !e.is_ignored)
1411            .peekable();
1412        let mut other_entries = other
1413            .entries_by_id
1414            .cursor::<()>()
1415            .filter(|e| include_ignored || !e.is_ignored)
1416            .peekable();
1417        loop {
1418            match (self_entries.peek(), other_entries.peek()) {
1419                (Some(self_entry), Some(other_entry)) => {
1420                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1421                        Ordering::Less => {
1422                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1423                            updated_entries.push(entry);
1424                            self_entries.next();
1425                        }
1426                        Ordering::Equal => {
1427                            if self_entry.scan_id != other_entry.scan_id {
1428                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1429                                updated_entries.push(entry);
1430                            }
1431
1432                            self_entries.next();
1433                            other_entries.next();
1434                        }
1435                        Ordering::Greater => {
1436                            removed_entries.push(other_entry.id.to_proto());
1437                            other_entries.next();
1438                        }
1439                    }
1440                }
1441                (Some(self_entry), None) => {
1442                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1443                    updated_entries.push(entry);
1444                    self_entries.next();
1445                }
1446                (None, Some(other_entry)) => {
1447                    removed_entries.push(other_entry.id.to_proto());
1448                    other_entries.next();
1449                }
1450                (None, None) => break,
1451            }
1452        }
1453
1454        proto::UpdateWorktree {
1455            project_id,
1456            worktree_id,
1457            root_name: self.root_name().to_string(),
1458            updated_entries,
1459            removed_entries,
1460            scan_id: self.scan_id as u64,
1461            is_last_update: true,
1462        }
1463    }
1464
1465    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1466        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1467            let abs_path = self.abs_path.join(&entry.path);
1468            match smol::block_on(build_gitignore(&abs_path, fs)) {
1469                Ok(ignore) => {
1470                    self.ignores_by_parent_abs_path.insert(
1471                        abs_path.parent().unwrap().into(),
1472                        (Arc::new(ignore), self.scan_id),
1473                    );
1474                }
1475                Err(error) => {
1476                    log::error!(
1477                        "error loading .gitignore file {:?} - {:?}",
1478                        &entry.path,
1479                        error
1480                    );
1481                }
1482            }
1483        }
1484
1485        self.reuse_entry_id(&mut entry);
1486
1487        if entry.kind == EntryKind::PendingDir {
1488            if let Some(existing_entry) =
1489                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1490            {
1491                entry.kind = existing_entry.kind;
1492            }
1493        }
1494
1495        self.entries_by_path.insert_or_replace(entry.clone(), &());
1496        let scan_id = self.scan_id;
1497        let removed_entry = self.entries_by_id.insert_or_replace(
1498            PathEntry {
1499                id: entry.id,
1500                path: entry.path.clone(),
1501                is_ignored: entry.is_ignored,
1502                scan_id,
1503            },
1504            &(),
1505        );
1506
1507        if let Some(removed_entry) = removed_entry {
1508            self.dec_extension_count(&removed_entry.path, removed_entry.is_ignored);
1509        }
1510        self.inc_extension_count(&entry.path, entry.is_ignored);
1511
1512        entry
1513    }
1514
1515    fn populate_dir(
1516        &mut self,
1517        parent_path: Arc<Path>,
1518        entries: impl IntoIterator<Item = Entry>,
1519        ignore: Option<Arc<Gitignore>>,
1520        fs: &dyn Fs,
1521    ) {
1522        let mut parent_entry = if let Some(parent_entry) =
1523            self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1524        {
1525            parent_entry.clone()
1526        } else {
1527            log::warn!(
1528                "populating a directory {:?} that has been removed",
1529                parent_path
1530            );
1531            return;
1532        };
1533
1534        if let Some(ignore) = ignore {
1535            self.ignores_by_parent_abs_path.insert(
1536                self.abs_path.join(&parent_path).into(),
1537                (ignore, self.scan_id),
1538            );
1539        }
1540        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1541            parent_entry.kind = EntryKind::Dir;
1542        } else {
1543            unreachable!();
1544        }
1545
1546        if parent_path.file_name() == Some(&DOT_GIT) {
1547            let abs_path = self.abs_path.join(&parent_path);
1548            let content_path: Arc<Path> = parent_path.parent().unwrap().into();
1549            if let Err(ix) = self
1550                .git_repositories
1551                .binary_search_by_key(&&content_path, |repo| &repo.content_path)
1552            {
1553                if let Some(repo) = fs.open_repo(abs_path.as_path()) {
1554                    self.git_repositories.insert(
1555                        ix,
1556                        GitRepositoryEntry {
1557                            repo,
1558                            scan_id: 0,
1559                            content_path,
1560                            git_dir_path: parent_path,
1561                        },
1562                    );
1563                }
1564            }
1565        }
1566
1567        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1568        let mut entries_by_id_edits = Vec::new();
1569
1570        for mut entry in entries {
1571            self.reuse_entry_id(&mut entry);
1572            self.inc_extension_count(&entry.path, entry.is_ignored);
1573            entries_by_id_edits.push(Edit::Insert(PathEntry {
1574                id: entry.id,
1575                path: entry.path.clone(),
1576                is_ignored: entry.is_ignored,
1577                scan_id: self.scan_id,
1578            }));
1579            entries_by_path_edits.push(Edit::Insert(entry));
1580        }
1581
1582        self.entries_by_path.edit(entries_by_path_edits, &());
1583        let removed_entries = self.entries_by_id.edit(entries_by_id_edits, &());
1584
1585        for removed_entry in removed_entries {
1586            self.dec_extension_count(&removed_entry.path, removed_entry.is_ignored);
1587        }
1588    }
1589
1590    fn inc_extension_count(&mut self, path: &Path, ignored: bool) {
1591        if !ignored {
1592            if let Some(extension) = path.extension() {
1593                if let Some(count) = self.extension_counts.get_mut(extension) {
1594                    *count += 1;
1595                } else {
1596                    self.extension_counts.insert(extension.into(), 1);
1597                }
1598            }
1599        }
1600    }
1601
1602    fn dec_extension_count(&mut self, path: &Path, ignored: bool) {
1603        if !ignored {
1604            if let Some(extension) = path.extension() {
1605                if let Some(count) = self.extension_counts.get_mut(extension) {
1606                    *count -= 1;
1607                }
1608            }
1609        }
1610    }
1611
1612    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1613        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1614            entry.id = removed_entry_id;
1615        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1616            entry.id = existing_entry.id;
1617        }
1618    }
1619
1620    fn remove_path(&mut self, path: &Path) {
1621        let mut new_entries;
1622        let removed_entries;
1623        {
1624            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1625            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1626            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1627            new_entries.push_tree(cursor.suffix(&()), &());
1628        }
1629        self.entries_by_path = new_entries;
1630
1631        let mut entries_by_id_edits = Vec::new();
1632        for entry in removed_entries.cursor::<()>() {
1633            let removed_entry_id = self
1634                .removed_entry_ids
1635                .entry(entry.inode)
1636                .or_insert(entry.id);
1637            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1638            entries_by_id_edits.push(Edit::Remove(entry.id));
1639            self.dec_extension_count(&entry.path, entry.is_ignored);
1640        }
1641        self.entries_by_id.edit(entries_by_id_edits, &());
1642
1643        if path.file_name() == Some(&GITIGNORE) {
1644            let abs_parent_path = self.abs_path.join(path.parent().unwrap());
1645            if let Some((_, scan_id)) = self
1646                .ignores_by_parent_abs_path
1647                .get_mut(abs_parent_path.as_path())
1648            {
1649                *scan_id = self.snapshot.scan_id;
1650            }
1651        } else if path.file_name() == Some(&DOT_GIT) {
1652            let parent_path = path.parent().unwrap();
1653            if let Ok(ix) = self
1654                .git_repositories
1655                .binary_search_by_key(&parent_path, |repo| repo.git_dir_path.as_ref())
1656            {
1657                self.git_repositories[ix].scan_id = self.snapshot.scan_id;
1658            }
1659        }
1660    }
1661
1662    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
1663        let mut inodes = TreeSet::default();
1664        for ancestor in path.ancestors().skip(1) {
1665            if let Some(entry) = self.entry_for_path(ancestor) {
1666                inodes.insert(entry.inode);
1667            }
1668        }
1669        inodes
1670    }
1671
1672    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1673        let mut new_ignores = Vec::new();
1674        for ancestor in abs_path.ancestors().skip(1) {
1675            if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
1676                new_ignores.push((ancestor, Some(ignore.clone())));
1677            } else {
1678                new_ignores.push((ancestor, None));
1679            }
1680        }
1681
1682        let mut ignore_stack = IgnoreStack::none();
1683        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
1684            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
1685                ignore_stack = IgnoreStack::all();
1686                break;
1687            } else if let Some(ignore) = ignore {
1688                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
1689            }
1690        }
1691
1692        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
1693            ignore_stack = IgnoreStack::all();
1694        }
1695
1696        ignore_stack
1697    }
1698
1699    pub fn git_repo_entries(&self) -> &[GitRepositoryEntry] {
1700        &self.git_repositories
1701    }
1702}
1703
1704impl GitRepositoryEntry {
1705    // Note that these paths should be relative to the worktree root.
1706    pub(crate) fn manages(&self, path: &Path) -> bool {
1707        path.starts_with(self.content_path.as_ref())
1708    }
1709
1710    // Note that theis path should be relative to the worktree root.
1711    pub(crate) fn in_dot_git(&self, path: &Path) -> bool {
1712        path.starts_with(self.git_dir_path.as_ref())
1713    }
1714}
1715
1716async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1717    let contents = fs.load(abs_path).await?;
1718    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
1719    let mut builder = GitignoreBuilder::new(parent);
1720    for line in contents.lines() {
1721        builder.add_line(Some(abs_path.into()), line)?;
1722    }
1723    Ok(builder.build()?)
1724}
1725
1726impl WorktreeId {
1727    pub fn from_usize(handle_id: usize) -> Self {
1728        Self(handle_id)
1729    }
1730
1731    pub(crate) fn from_proto(id: u64) -> Self {
1732        Self(id as usize)
1733    }
1734
1735    pub fn to_proto(&self) -> u64 {
1736        self.0 as u64
1737    }
1738
1739    pub fn to_usize(&self) -> usize {
1740        self.0
1741    }
1742}
1743
1744impl fmt::Display for WorktreeId {
1745    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746        self.0.fmt(f)
1747    }
1748}
1749
1750impl Deref for Worktree {
1751    type Target = Snapshot;
1752
1753    fn deref(&self) -> &Self::Target {
1754        match self {
1755            Worktree::Local(worktree) => &worktree.snapshot,
1756            Worktree::Remote(worktree) => &worktree.snapshot,
1757        }
1758    }
1759}
1760
1761impl Deref for LocalWorktree {
1762    type Target = LocalSnapshot;
1763
1764    fn deref(&self) -> &Self::Target {
1765        &self.snapshot
1766    }
1767}
1768
1769impl Deref for RemoteWorktree {
1770    type Target = Snapshot;
1771
1772    fn deref(&self) -> &Self::Target {
1773        &self.snapshot
1774    }
1775}
1776
1777impl fmt::Debug for LocalWorktree {
1778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1779        self.snapshot.fmt(f)
1780    }
1781}
1782
1783impl fmt::Debug for Snapshot {
1784    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1785        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1786        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1787
1788        impl<'a> fmt::Debug for EntriesByPath<'a> {
1789            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1790                f.debug_map()
1791                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1792                    .finish()
1793            }
1794        }
1795
1796        impl<'a> fmt::Debug for EntriesById<'a> {
1797            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1798                f.debug_list().entries(self.0.iter()).finish()
1799            }
1800        }
1801
1802        f.debug_struct("Snapshot")
1803            .field("id", &self.id)
1804            .field("root_name", &self.root_name)
1805            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1806            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1807            .finish()
1808    }
1809}
1810
1811#[derive(Clone, PartialEq)]
1812pub struct File {
1813    pub worktree: ModelHandle<Worktree>,
1814    pub path: Arc<Path>,
1815    pub mtime: SystemTime,
1816    pub(crate) entry_id: Option<ProjectEntryId>,
1817    pub(crate) is_local: bool,
1818}
1819
1820impl language::File for File {
1821    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1822        if self.is_local {
1823            Some(self)
1824        } else {
1825            None
1826        }
1827    }
1828
1829    fn mtime(&self) -> SystemTime {
1830        self.mtime
1831    }
1832
1833    fn path(&self) -> &Arc<Path> {
1834        &self.path
1835    }
1836
1837    fn full_path(&self, cx: &AppContext) -> PathBuf {
1838        let mut full_path = PathBuf::new();
1839        full_path.push(self.worktree.read(cx).root_name());
1840        if self.path.components().next().is_some() {
1841            full_path.push(&self.path);
1842        }
1843        full_path
1844    }
1845
1846    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1847    /// of its worktree, then this method will return the name of the worktree itself.
1848    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
1849        self.path
1850            .file_name()
1851            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
1852    }
1853
1854    fn is_deleted(&self) -> bool {
1855        self.entry_id.is_none()
1856    }
1857
1858    fn save(
1859        &self,
1860        buffer_id: u64,
1861        text: Rope,
1862        version: clock::Global,
1863        line_ending: LineEnding,
1864        cx: &mut MutableAppContext,
1865    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1866        self.worktree.update(cx, |worktree, cx| match worktree {
1867            Worktree::Local(worktree) => {
1868                let rpc = worktree.client.clone();
1869                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1870                let fingerprint = text.fingerprint();
1871                let save = worktree.write_file(self.path.clone(), text, line_ending, cx);
1872                cx.background().spawn(async move {
1873                    let entry = save.await?;
1874                    if let Some(project_id) = project_id {
1875                        rpc.send(proto::BufferSaved {
1876                            project_id,
1877                            buffer_id,
1878                            version: serialize_version(&version),
1879                            mtime: Some(entry.mtime.into()),
1880                            fingerprint: fingerprint.clone(),
1881                        })?;
1882                    }
1883                    Ok((version, fingerprint, entry.mtime))
1884                })
1885            }
1886            Worktree::Remote(worktree) => {
1887                let rpc = worktree.client.clone();
1888                let project_id = worktree.project_id;
1889                cx.foreground().spawn(async move {
1890                    let response = rpc
1891                        .request(proto::SaveBuffer {
1892                            project_id,
1893                            buffer_id,
1894                            version: serialize_version(&version),
1895                        })
1896                        .await?;
1897                    let version = deserialize_version(response.version);
1898                    let mtime = response
1899                        .mtime
1900                        .ok_or_else(|| anyhow!("missing mtime"))?
1901                        .into();
1902                    Ok((version, response.fingerprint, mtime))
1903                })
1904            }
1905        })
1906    }
1907
1908    fn as_any(&self) -> &dyn Any {
1909        self
1910    }
1911
1912    fn to_proto(&self) -> rpc::proto::File {
1913        rpc::proto::File {
1914            worktree_id: self.worktree.id() as u64,
1915            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1916            path: self.path.to_string_lossy().into(),
1917            mtime: Some(self.mtime.into()),
1918        }
1919    }
1920}
1921
1922impl language::LocalFile for File {
1923    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1924        self.worktree
1925            .read(cx)
1926            .as_local()
1927            .unwrap()
1928            .abs_path
1929            .join(&self.path)
1930    }
1931
1932    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1933        let worktree = self.worktree.read(cx).as_local().unwrap();
1934        let abs_path = worktree.absolutize(&self.path);
1935        let fs = worktree.fs.clone();
1936        cx.background()
1937            .spawn(async move { fs.load(&abs_path).await })
1938    }
1939
1940    fn buffer_reloaded(
1941        &self,
1942        buffer_id: u64,
1943        version: &clock::Global,
1944        fingerprint: String,
1945        line_ending: LineEnding,
1946        mtime: SystemTime,
1947        cx: &mut MutableAppContext,
1948    ) {
1949        let worktree = self.worktree.read(cx).as_local().unwrap();
1950        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1951            worktree
1952                .client
1953                .send(proto::BufferReloaded {
1954                    project_id,
1955                    buffer_id,
1956                    version: serialize_version(version),
1957                    mtime: Some(mtime.into()),
1958                    fingerprint,
1959                    line_ending: serialize_line_ending(line_ending) as i32,
1960                })
1961                .log_err();
1962        }
1963    }
1964}
1965
1966impl File {
1967    pub fn from_proto(
1968        proto: rpc::proto::File,
1969        worktree: ModelHandle<Worktree>,
1970        cx: &AppContext,
1971    ) -> Result<Self> {
1972        let worktree_id = worktree
1973            .read(cx)
1974            .as_remote()
1975            .ok_or_else(|| anyhow!("not remote"))?
1976            .id();
1977
1978        if worktree_id.to_proto() != proto.worktree_id {
1979            return Err(anyhow!("worktree id does not match file"));
1980        }
1981
1982        Ok(Self {
1983            worktree,
1984            path: Path::new(&proto.path).into(),
1985            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1986            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1987            is_local: false,
1988        })
1989    }
1990
1991    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1992        file.and_then(|f| f.as_any().downcast_ref())
1993    }
1994
1995    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1996        self.worktree.read(cx).id()
1997    }
1998
1999    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2000        self.entry_id
2001    }
2002}
2003
2004#[derive(Clone, Debug, PartialEq, Eq)]
2005pub struct Entry {
2006    pub id: ProjectEntryId,
2007    pub kind: EntryKind,
2008    pub path: Arc<Path>,
2009    pub inode: u64,
2010    pub mtime: SystemTime,
2011    pub is_symlink: bool,
2012    pub is_ignored: bool,
2013}
2014
2015#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2016pub enum EntryKind {
2017    PendingDir,
2018    Dir,
2019    File(CharBag),
2020}
2021
2022impl Entry {
2023    fn new(
2024        path: Arc<Path>,
2025        metadata: &fs::Metadata,
2026        next_entry_id: &AtomicUsize,
2027        root_char_bag: CharBag,
2028    ) -> Self {
2029        Self {
2030            id: ProjectEntryId::new(next_entry_id),
2031            kind: if metadata.is_dir {
2032                EntryKind::PendingDir
2033            } else {
2034                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2035            },
2036            path,
2037            inode: metadata.inode,
2038            mtime: metadata.mtime,
2039            is_symlink: metadata.is_symlink,
2040            is_ignored: false,
2041        }
2042    }
2043
2044    pub fn is_dir(&self) -> bool {
2045        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2046    }
2047
2048    pub fn is_file(&self) -> bool {
2049        matches!(self.kind, EntryKind::File(_))
2050    }
2051}
2052
2053impl sum_tree::Item for Entry {
2054    type Summary = EntrySummary;
2055
2056    fn summary(&self) -> Self::Summary {
2057        let visible_count = if self.is_ignored { 0 } else { 1 };
2058        let file_count;
2059        let visible_file_count;
2060        if self.is_file() {
2061            file_count = 1;
2062            visible_file_count = visible_count;
2063        } else {
2064            file_count = 0;
2065            visible_file_count = 0;
2066        }
2067
2068        EntrySummary {
2069            max_path: self.path.clone(),
2070            count: 1,
2071            visible_count,
2072            file_count,
2073            visible_file_count,
2074        }
2075    }
2076}
2077
2078impl sum_tree::KeyedItem for Entry {
2079    type Key = PathKey;
2080
2081    fn key(&self) -> Self::Key {
2082        PathKey(self.path.clone())
2083    }
2084}
2085
2086#[derive(Clone, Debug)]
2087pub struct EntrySummary {
2088    max_path: Arc<Path>,
2089    count: usize,
2090    visible_count: usize,
2091    file_count: usize,
2092    visible_file_count: usize,
2093}
2094
2095impl Default for EntrySummary {
2096    fn default() -> Self {
2097        Self {
2098            max_path: Arc::from(Path::new("")),
2099            count: 0,
2100            visible_count: 0,
2101            file_count: 0,
2102            visible_file_count: 0,
2103        }
2104    }
2105}
2106
2107impl sum_tree::Summary for EntrySummary {
2108    type Context = ();
2109
2110    fn add_summary(&mut self, rhs: &Self, _: &()) {
2111        self.max_path = rhs.max_path.clone();
2112        self.count += rhs.count;
2113        self.visible_count += rhs.visible_count;
2114        self.file_count += rhs.file_count;
2115        self.visible_file_count += rhs.visible_file_count;
2116    }
2117}
2118
2119#[derive(Clone, Debug)]
2120struct PathEntry {
2121    id: ProjectEntryId,
2122    path: Arc<Path>,
2123    is_ignored: bool,
2124    scan_id: usize,
2125}
2126
2127impl sum_tree::Item for PathEntry {
2128    type Summary = PathEntrySummary;
2129
2130    fn summary(&self) -> Self::Summary {
2131        PathEntrySummary { max_id: self.id }
2132    }
2133}
2134
2135impl sum_tree::KeyedItem for PathEntry {
2136    type Key = ProjectEntryId;
2137
2138    fn key(&self) -> Self::Key {
2139        self.id
2140    }
2141}
2142
2143#[derive(Clone, Debug, Default)]
2144struct PathEntrySummary {
2145    max_id: ProjectEntryId,
2146}
2147
2148impl sum_tree::Summary for PathEntrySummary {
2149    type Context = ();
2150
2151    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2152        self.max_id = summary.max_id;
2153    }
2154}
2155
2156impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2157    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2158        *self = summary.max_id;
2159    }
2160}
2161
2162#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2163pub struct PathKey(Arc<Path>);
2164
2165impl Default for PathKey {
2166    fn default() -> Self {
2167        Self(Path::new("").into())
2168    }
2169}
2170
2171impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2172    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2173        self.0 = summary.max_path.clone();
2174    }
2175}
2176
2177struct BackgroundScanner {
2178    fs: Arc<dyn Fs>,
2179    snapshot: Arc<Mutex<LocalSnapshot>>,
2180    notify: UnboundedSender<ScanState>,
2181    executor: Arc<executor::Background>,
2182}
2183
2184impl BackgroundScanner {
2185    fn new(
2186        snapshot: Arc<Mutex<LocalSnapshot>>,
2187        notify: UnboundedSender<ScanState>,
2188        fs: Arc<dyn Fs>,
2189        executor: Arc<executor::Background>,
2190    ) -> Self {
2191        Self {
2192            fs,
2193            snapshot,
2194            notify,
2195            executor,
2196        }
2197    }
2198
2199    fn abs_path(&self) -> Arc<Path> {
2200        self.snapshot.lock().abs_path.clone()
2201    }
2202
2203    fn snapshot(&self) -> LocalSnapshot {
2204        self.snapshot.lock().clone()
2205    }
2206
2207    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2208        if self.notify.unbounded_send(ScanState::Initializing).is_err() {
2209            return;
2210        }
2211
2212        if let Err(err) = self.scan_dirs().await {
2213            if self
2214                .notify
2215                .unbounded_send(ScanState::Err(Arc::new(err)))
2216                .is_err()
2217            {
2218                return;
2219            }
2220        }
2221
2222        if self.notify.unbounded_send(ScanState::Idle).is_err() {
2223            return;
2224        }
2225
2226        futures::pin_mut!(events_rx);
2227
2228        while let Some(mut events) = events_rx.next().await {
2229            while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2230                events.extend(additional_events);
2231            }
2232
2233            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2234                break;
2235            }
2236
2237            if !self.process_events(events).await {
2238                break;
2239            }
2240
2241            if self.notify.unbounded_send(ScanState::Idle).is_err() {
2242                break;
2243            }
2244        }
2245    }
2246
2247    async fn scan_dirs(&mut self) -> Result<()> {
2248        let root_char_bag;
2249        let root_abs_path;
2250        let root_inode;
2251        let is_dir;
2252        let next_entry_id;
2253        {
2254            let snapshot = self.snapshot.lock();
2255            root_char_bag = snapshot.root_char_bag;
2256            root_abs_path = snapshot.abs_path.clone();
2257            root_inode = snapshot.root_entry().map(|e| e.inode);
2258            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir());
2259            next_entry_id = snapshot.next_entry_id.clone();
2260        };
2261
2262        // Populate ignores above the root.
2263        for ancestor in root_abs_path.ancestors().skip(1) {
2264            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2265            {
2266                self.snapshot
2267                    .lock()
2268                    .ignores_by_parent_abs_path
2269                    .insert(ancestor.into(), (ignore.into(), 0));
2270            }
2271        }
2272
2273        let ignore_stack = {
2274            let mut snapshot = self.snapshot.lock();
2275            let ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2276            if ignore_stack.is_all() {
2277                if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2278                    root_entry.is_ignored = true;
2279                    snapshot.insert_entry(root_entry, self.fs.as_ref());
2280                }
2281            }
2282            ignore_stack
2283        };
2284
2285        if is_dir {
2286            let path: Arc<Path> = Arc::from(Path::new(""));
2287            let mut ancestor_inodes = TreeSet::default();
2288            if let Some(root_inode) = root_inode {
2289                ancestor_inodes.insert(root_inode);
2290            }
2291
2292            let (tx, rx) = channel::unbounded();
2293            self.executor
2294                .block(tx.send(ScanJob {
2295                    abs_path: root_abs_path.to_path_buf(),
2296                    path,
2297                    ignore_stack,
2298                    ancestor_inodes,
2299                    scan_queue: tx.clone(),
2300                }))
2301                .unwrap();
2302            drop(tx);
2303
2304            self.executor
2305                .scoped(|scope| {
2306                    for _ in 0..self.executor.num_cpus() {
2307                        scope.spawn(async {
2308                            while let Ok(job) = rx.recv().await {
2309                                if let Err(err) = self
2310                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2311                                    .await
2312                                {
2313                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2314                                }
2315                            }
2316                        });
2317                    }
2318                })
2319                .await;
2320        }
2321
2322        Ok(())
2323    }
2324
2325    async fn scan_dir(
2326        &self,
2327        root_char_bag: CharBag,
2328        next_entry_id: Arc<AtomicUsize>,
2329        job: &ScanJob,
2330    ) -> Result<()> {
2331        let mut new_entries: Vec<Entry> = Vec::new();
2332        let mut new_jobs: Vec<ScanJob> = Vec::new();
2333        let mut ignore_stack = job.ignore_stack.clone();
2334        let mut new_ignore = None;
2335
2336        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2337        while let Some(child_abs_path) = child_paths.next().await {
2338            let child_abs_path = match child_abs_path {
2339                Ok(child_abs_path) => child_abs_path,
2340                Err(error) => {
2341                    log::error!("error processing entry {:?}", error);
2342                    continue;
2343                }
2344            };
2345            let child_name = child_abs_path.file_name().unwrap();
2346            let child_path: Arc<Path> = job.path.join(child_name).into();
2347            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2348                Ok(Some(metadata)) => metadata,
2349                Ok(None) => continue,
2350                Err(err) => {
2351                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2352                    continue;
2353                }
2354            };
2355
2356            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2357            if child_name == *GITIGNORE {
2358                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2359                    Ok(ignore) => {
2360                        let ignore = Arc::new(ignore);
2361                        ignore_stack =
2362                            ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2363                        new_ignore = Some(ignore);
2364                    }
2365                    Err(error) => {
2366                        log::error!(
2367                            "error loading .gitignore file {:?} - {:?}",
2368                            child_name,
2369                            error
2370                        );
2371                    }
2372                }
2373
2374                // Update ignore status of any child entries we've already processed to reflect the
2375                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2376                // there should rarely be too numerous. Update the ignore stack associated with any
2377                // new jobs as well.
2378                let mut new_jobs = new_jobs.iter_mut();
2379                for entry in &mut new_entries {
2380                    let entry_abs_path = self.abs_path().join(&entry.path);
2381                    entry.is_ignored =
2382                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2383                    if entry.is_dir() {
2384                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2385                            IgnoreStack::all()
2386                        } else {
2387                            ignore_stack.clone()
2388                        };
2389                    }
2390                }
2391            }
2392
2393            let mut child_entry = Entry::new(
2394                child_path.clone(),
2395                &child_metadata,
2396                &next_entry_id,
2397                root_char_bag,
2398            );
2399
2400            if child_entry.is_dir() {
2401                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2402                child_entry.is_ignored = is_ignored;
2403
2404                if !job.ancestor_inodes.contains(&child_entry.inode) {
2405                    let mut ancestor_inodes = job.ancestor_inodes.clone();
2406                    ancestor_inodes.insert(child_entry.inode);
2407                    new_jobs.push(ScanJob {
2408                        abs_path: child_abs_path,
2409                        path: child_path,
2410                        ignore_stack: if is_ignored {
2411                            IgnoreStack::all()
2412                        } else {
2413                            ignore_stack.clone()
2414                        },
2415                        ancestor_inodes,
2416                        scan_queue: job.scan_queue.clone(),
2417                    });
2418                }
2419            } else {
2420                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2421            }
2422
2423            new_entries.push(child_entry);
2424        }
2425
2426        self.snapshot.lock().populate_dir(
2427            job.path.clone(),
2428            new_entries,
2429            new_ignore,
2430            self.fs.as_ref(),
2431        );
2432        for new_job in new_jobs {
2433            job.scan_queue.send(new_job).await.unwrap();
2434        }
2435
2436        Ok(())
2437    }
2438
2439    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2440        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2441        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2442
2443        let root_char_bag;
2444        let root_abs_path;
2445        let next_entry_id;
2446        {
2447            let snapshot = self.snapshot.lock();
2448            root_char_bag = snapshot.root_char_bag;
2449            root_abs_path = snapshot.abs_path.clone();
2450            next_entry_id = snapshot.next_entry_id.clone();
2451        }
2452
2453        let root_canonical_path = if let Ok(path) = self.fs.canonicalize(&root_abs_path).await {
2454            path
2455        } else {
2456            return false;
2457        };
2458        let metadata = futures::future::join_all(
2459            events
2460                .iter()
2461                .map(|event| self.fs.metadata(&event.path))
2462                .collect::<Vec<_>>(),
2463        )
2464        .await;
2465
2466        // Hold the snapshot lock while clearing and re-inserting the root entries
2467        // for each event. This way, the snapshot is not observable to the foreground
2468        // thread while this operation is in-progress.
2469        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2470        {
2471            let mut snapshot = self.snapshot.lock();
2472            snapshot.scan_id += 1;
2473            for event in &events {
2474                if let Ok(path) = event.path.strip_prefix(&root_canonical_path) {
2475                    snapshot.remove_path(path);
2476                }
2477            }
2478
2479            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2480                let path: Arc<Path> = match event.path.strip_prefix(&root_canonical_path) {
2481                    Ok(path) => Arc::from(path.to_path_buf()),
2482                    Err(_) => {
2483                        log::error!(
2484                            "unexpected event {:?} for root path {:?}",
2485                            event.path,
2486                            root_canonical_path
2487                        );
2488                        continue;
2489                    }
2490                };
2491                let abs_path = root_abs_path.join(&path);
2492
2493                match metadata {
2494                    Ok(Some(metadata)) => {
2495                        let ignore_stack =
2496                            snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2497                        let mut fs_entry = Entry::new(
2498                            path.clone(),
2499                            &metadata,
2500                            snapshot.next_entry_id.as_ref(),
2501                            snapshot.root_char_bag,
2502                        );
2503                        fs_entry.is_ignored = ignore_stack.is_all();
2504                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2505
2506                        let scan_id = snapshot.scan_id;
2507                        if let Some(repo) = snapshot.in_dot_git(&path) {
2508                            repo.repo.lock().reload_index();
2509                            repo.scan_id = scan_id;
2510                        }
2511
2512                        let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2513                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2514                            ancestor_inodes.insert(metadata.inode);
2515                            self.executor
2516                                .block(scan_queue_tx.send(ScanJob {
2517                                    abs_path,
2518                                    path,
2519                                    ignore_stack,
2520                                    ancestor_inodes,
2521                                    scan_queue: scan_queue_tx.clone(),
2522                                }))
2523                                .unwrap();
2524                        }
2525                    }
2526                    Ok(None) => {}
2527                    Err(err) => {
2528                        // TODO - create a special 'error' entry in the entries tree to mark this
2529                        log::error!("error reading file on event {:?}", err);
2530                    }
2531                }
2532            }
2533            drop(scan_queue_tx);
2534        }
2535
2536        // Scan any directories that were created as part of this event batch.
2537        self.executor
2538            .scoped(|scope| {
2539                for _ in 0..self.executor.num_cpus() {
2540                    scope.spawn(async {
2541                        while let Ok(job) = scan_queue_rx.recv().await {
2542                            if let Err(err) = self
2543                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2544                                .await
2545                            {
2546                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2547                            }
2548                        }
2549                    });
2550                }
2551            })
2552            .await;
2553
2554        // Attempt to detect renames only over a single batch of file-system events.
2555        self.snapshot.lock().removed_entry_ids.clear();
2556
2557        self.update_ignore_statuses().await;
2558        self.update_git_repositories();
2559        true
2560    }
2561
2562    async fn update_ignore_statuses(&self) {
2563        let mut snapshot = self.snapshot();
2564
2565        let mut ignores_to_update = Vec::new();
2566        let mut ignores_to_delete = Vec::new();
2567        for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2568            if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2569                if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2570                    ignores_to_update.push(parent_abs_path.clone());
2571                }
2572
2573                let ignore_path = parent_path.join(&*GITIGNORE);
2574                if snapshot.entry_for_path(ignore_path).is_none() {
2575                    ignores_to_delete.push(parent_abs_path.clone());
2576                }
2577            }
2578        }
2579
2580        for parent_abs_path in ignores_to_delete {
2581            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2582            self.snapshot
2583                .lock()
2584                .ignores_by_parent_abs_path
2585                .remove(&parent_abs_path);
2586        }
2587
2588        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2589        ignores_to_update.sort_unstable();
2590        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2591        while let Some(parent_abs_path) = ignores_to_update.next() {
2592            while ignores_to_update
2593                .peek()
2594                .map_or(false, |p| p.starts_with(&parent_abs_path))
2595            {
2596                ignores_to_update.next().unwrap();
2597            }
2598
2599            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2600            ignore_queue_tx
2601                .send(UpdateIgnoreStatusJob {
2602                    abs_path: parent_abs_path,
2603                    ignore_stack,
2604                    ignore_queue: ignore_queue_tx.clone(),
2605                })
2606                .await
2607                .unwrap();
2608        }
2609        drop(ignore_queue_tx);
2610
2611        self.executor
2612            .scoped(|scope| {
2613                for _ in 0..self.executor.num_cpus() {
2614                    scope.spawn(async {
2615                        while let Ok(job) = ignore_queue_rx.recv().await {
2616                            self.update_ignore_status(job, &snapshot).await;
2617                        }
2618                    });
2619                }
2620            })
2621            .await;
2622    }
2623
2624    fn update_git_repositories(&self) {
2625        let mut snapshot = self.snapshot.lock();
2626        let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2627        git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2628        snapshot.git_repositories = git_repositories;
2629    }
2630
2631    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2632        let mut ignore_stack = job.ignore_stack;
2633        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2634            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2635        }
2636
2637        let mut entries_by_id_edits = Vec::new();
2638        let mut entries_by_path_edits = Vec::new();
2639        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2640        for mut entry in snapshot.child_entries(path).cloned() {
2641            let was_ignored = entry.is_ignored;
2642            let abs_path = self.abs_path().join(&entry.path);
2643            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2644            if entry.is_dir() {
2645                let child_ignore_stack = if entry.is_ignored {
2646                    IgnoreStack::all()
2647                } else {
2648                    ignore_stack.clone()
2649                };
2650                job.ignore_queue
2651                    .send(UpdateIgnoreStatusJob {
2652                        abs_path: abs_path.into(),
2653                        ignore_stack: child_ignore_stack,
2654                        ignore_queue: job.ignore_queue.clone(),
2655                    })
2656                    .await
2657                    .unwrap();
2658            }
2659
2660            if entry.is_ignored != was_ignored {
2661                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2662                path_entry.scan_id = snapshot.scan_id;
2663                path_entry.is_ignored = entry.is_ignored;
2664                entries_by_id_edits.push(Edit::Insert(path_entry));
2665                entries_by_path_edits.push(Edit::Insert(entry));
2666            }
2667        }
2668
2669        let mut snapshot = self.snapshot.lock();
2670        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2671        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2672    }
2673}
2674
2675fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2676    let mut result = root_char_bag;
2677    result.extend(
2678        path.to_string_lossy()
2679            .chars()
2680            .map(|c| c.to_ascii_lowercase()),
2681    );
2682    result
2683}
2684
2685struct ScanJob {
2686    abs_path: PathBuf,
2687    path: Arc<Path>,
2688    ignore_stack: Arc<IgnoreStack>,
2689    scan_queue: Sender<ScanJob>,
2690    ancestor_inodes: TreeSet<u64>,
2691}
2692
2693struct UpdateIgnoreStatusJob {
2694    abs_path: Arc<Path>,
2695    ignore_stack: Arc<IgnoreStack>,
2696    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2697}
2698
2699pub trait WorktreeHandle {
2700    #[cfg(any(test, feature = "test-support"))]
2701    fn flush_fs_events<'a>(
2702        &self,
2703        cx: &'a gpui::TestAppContext,
2704    ) -> futures::future::LocalBoxFuture<'a, ()>;
2705}
2706
2707impl WorktreeHandle for ModelHandle<Worktree> {
2708    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2709    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2710    // extra directory scans, and emit extra scan-state notifications.
2711    //
2712    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2713    // to ensure that all redundant FS events have already been processed.
2714    #[cfg(any(test, feature = "test-support"))]
2715    fn flush_fs_events<'a>(
2716        &self,
2717        cx: &'a gpui::TestAppContext,
2718    ) -> futures::future::LocalBoxFuture<'a, ()> {
2719        use smol::future::FutureExt;
2720
2721        let filename = "fs-event-sentinel";
2722        let tree = self.clone();
2723        let (fs, root_path) = self.read_with(cx, |tree, _| {
2724            let tree = tree.as_local().unwrap();
2725            (tree.fs.clone(), tree.abs_path().clone())
2726        });
2727
2728        async move {
2729            fs.create_file(&root_path.join(filename), Default::default())
2730                .await
2731                .unwrap();
2732            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2733                .await;
2734
2735            fs.remove_file(&root_path.join(filename), Default::default())
2736                .await
2737                .unwrap();
2738            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2739                .await;
2740
2741            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2742                .await;
2743        }
2744        .boxed_local()
2745    }
2746}
2747
2748#[derive(Clone, Debug)]
2749struct TraversalProgress<'a> {
2750    max_path: &'a Path,
2751    count: usize,
2752    visible_count: usize,
2753    file_count: usize,
2754    visible_file_count: usize,
2755}
2756
2757impl<'a> TraversalProgress<'a> {
2758    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2759        match (include_ignored, include_dirs) {
2760            (true, true) => self.count,
2761            (true, false) => self.file_count,
2762            (false, true) => self.visible_count,
2763            (false, false) => self.visible_file_count,
2764        }
2765    }
2766}
2767
2768impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2769    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2770        self.max_path = summary.max_path.as_ref();
2771        self.count += summary.count;
2772        self.visible_count += summary.visible_count;
2773        self.file_count += summary.file_count;
2774        self.visible_file_count += summary.visible_file_count;
2775    }
2776}
2777
2778impl<'a> Default for TraversalProgress<'a> {
2779    fn default() -> Self {
2780        Self {
2781            max_path: Path::new(""),
2782            count: 0,
2783            visible_count: 0,
2784            file_count: 0,
2785            visible_file_count: 0,
2786        }
2787    }
2788}
2789
2790pub struct Traversal<'a> {
2791    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2792    include_ignored: bool,
2793    include_dirs: bool,
2794}
2795
2796impl<'a> Traversal<'a> {
2797    pub fn advance(&mut self) -> bool {
2798        self.advance_to_offset(self.offset() + 1)
2799    }
2800
2801    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2802        self.cursor.seek_forward(
2803            &TraversalTarget::Count {
2804                count: offset,
2805                include_dirs: self.include_dirs,
2806                include_ignored: self.include_ignored,
2807            },
2808            Bias::Right,
2809            &(),
2810        )
2811    }
2812
2813    pub fn advance_to_sibling(&mut self) -> bool {
2814        while let Some(entry) = self.cursor.item() {
2815            self.cursor.seek_forward(
2816                &TraversalTarget::PathSuccessor(&entry.path),
2817                Bias::Left,
2818                &(),
2819            );
2820            if let Some(entry) = self.cursor.item() {
2821                if (self.include_dirs || !entry.is_dir())
2822                    && (self.include_ignored || !entry.is_ignored)
2823                {
2824                    return true;
2825                }
2826            }
2827        }
2828        false
2829    }
2830
2831    pub fn entry(&self) -> Option<&'a Entry> {
2832        self.cursor.item()
2833    }
2834
2835    pub fn offset(&self) -> usize {
2836        self.cursor
2837            .start()
2838            .count(self.include_dirs, self.include_ignored)
2839    }
2840}
2841
2842impl<'a> Iterator for Traversal<'a> {
2843    type Item = &'a Entry;
2844
2845    fn next(&mut self) -> Option<Self::Item> {
2846        if let Some(item) = self.entry() {
2847            self.advance();
2848            Some(item)
2849        } else {
2850            None
2851        }
2852    }
2853}
2854
2855#[derive(Debug)]
2856enum TraversalTarget<'a> {
2857    Path(&'a Path),
2858    PathSuccessor(&'a Path),
2859    Count {
2860        count: usize,
2861        include_ignored: bool,
2862        include_dirs: bool,
2863    },
2864}
2865
2866impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2867    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2868        match self {
2869            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2870            TraversalTarget::PathSuccessor(path) => {
2871                if !cursor_location.max_path.starts_with(path) {
2872                    Ordering::Equal
2873                } else {
2874                    Ordering::Greater
2875                }
2876            }
2877            TraversalTarget::Count {
2878                count,
2879                include_dirs,
2880                include_ignored,
2881            } => Ord::cmp(
2882                count,
2883                &cursor_location.count(*include_dirs, *include_ignored),
2884            ),
2885        }
2886    }
2887}
2888
2889struct ChildEntriesIter<'a> {
2890    parent_path: &'a Path,
2891    traversal: Traversal<'a>,
2892}
2893
2894impl<'a> Iterator for ChildEntriesIter<'a> {
2895    type Item = &'a Entry;
2896
2897    fn next(&mut self) -> Option<Self::Item> {
2898        if let Some(item) = self.traversal.entry() {
2899            if item.path.starts_with(&self.parent_path) {
2900                self.traversal.advance_to_sibling();
2901                return Some(item);
2902            }
2903        }
2904        None
2905    }
2906}
2907
2908impl<'a> From<&'a Entry> for proto::Entry {
2909    fn from(entry: &'a Entry) -> Self {
2910        Self {
2911            id: entry.id.to_proto(),
2912            is_dir: entry.is_dir(),
2913            path: entry.path.as_os_str().as_bytes().to_vec(),
2914            inode: entry.inode,
2915            mtime: Some(entry.mtime.into()),
2916            is_symlink: entry.is_symlink,
2917            is_ignored: entry.is_ignored,
2918        }
2919    }
2920}
2921
2922impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2923    type Error = anyhow::Error;
2924
2925    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2926        if let Some(mtime) = entry.mtime {
2927            let kind = if entry.is_dir {
2928                EntryKind::Dir
2929            } else {
2930                let mut char_bag = *root_char_bag;
2931                char_bag.extend(
2932                    String::from_utf8_lossy(&entry.path)
2933                        .chars()
2934                        .map(|c| c.to_ascii_lowercase()),
2935                );
2936                EntryKind::File(char_bag)
2937            };
2938            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2939            Ok(Entry {
2940                id: ProjectEntryId::from_proto(entry.id),
2941                kind,
2942                path,
2943                inode: entry.inode,
2944                mtime: mtime.into(),
2945                is_symlink: entry.is_symlink,
2946                is_ignored: entry.is_ignored,
2947            })
2948        } else {
2949            Err(anyhow!(
2950                "missing mtime in remote worktree entry {:?}",
2951                entry.path
2952            ))
2953        }
2954    }
2955}
2956
2957async fn send_worktree_update(client: &Arc<Client>, update: proto::UpdateWorktree) -> Result<()> {
2958    #[cfg(any(test, feature = "test-support"))]
2959    const MAX_CHUNK_SIZE: usize = 2;
2960    #[cfg(not(any(test, feature = "test-support")))]
2961    const MAX_CHUNK_SIZE: usize = 256;
2962
2963    for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
2964        client.request(update).await?;
2965    }
2966
2967    Ok(())
2968}
2969
2970#[cfg(test)]
2971mod tests {
2972    use super::*;
2973    use crate::fs::FakeFs;
2974    use anyhow::Result;
2975    use client::test::FakeHttpClient;
2976    use fs::RealFs;
2977    use git::repository::FakeGitRepository;
2978    use gpui::{executor::Deterministic, TestAppContext};
2979    use rand::prelude::*;
2980    use serde_json::json;
2981    use std::{
2982        env,
2983        fmt::Write,
2984        time::{SystemTime, UNIX_EPOCH},
2985    };
2986
2987    use util::test::temp_tree;
2988
2989    #[gpui::test]
2990    async fn test_traversal(cx: &mut TestAppContext) {
2991        let fs = FakeFs::new(cx.background());
2992        fs.insert_tree(
2993            "/root",
2994            json!({
2995               ".gitignore": "a/b\n",
2996               "a": {
2997                   "b": "",
2998                   "c": "",
2999               }
3000            }),
3001        )
3002        .await;
3003
3004        let http_client = FakeHttpClient::with_404_response();
3005        let client = cx.read(|cx| Client::new(http_client, cx));
3006
3007        let tree = Worktree::local(
3008            client,
3009            Arc::from(Path::new("/root")),
3010            true,
3011            fs,
3012            Default::default(),
3013            &mut cx.to_async(),
3014        )
3015        .await
3016        .unwrap();
3017        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3018            .await;
3019
3020        tree.read_with(cx, |tree, _| {
3021            assert_eq!(
3022                tree.entries(false)
3023                    .map(|entry| entry.path.as_ref())
3024                    .collect::<Vec<_>>(),
3025                vec![
3026                    Path::new(""),
3027                    Path::new(".gitignore"),
3028                    Path::new("a"),
3029                    Path::new("a/c"),
3030                ]
3031            );
3032            assert_eq!(
3033                tree.entries(true)
3034                    .map(|entry| entry.path.as_ref())
3035                    .collect::<Vec<_>>(),
3036                vec![
3037                    Path::new(""),
3038                    Path::new(".gitignore"),
3039                    Path::new("a"),
3040                    Path::new("a/b"),
3041                    Path::new("a/c"),
3042                ]
3043            );
3044        })
3045    }
3046
3047    #[gpui::test(iterations = 10)]
3048    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3049        let fs = FakeFs::new(cx.background());
3050        fs.insert_tree(
3051            "/root",
3052            json!({
3053                "lib": {
3054                    "a": {
3055                        "a.txt": ""
3056                    },
3057                    "b": {
3058                        "b.txt": ""
3059                    }
3060                }
3061            }),
3062        )
3063        .await;
3064        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3065        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3066
3067        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3068        let tree = Worktree::local(
3069            client,
3070            Arc::from(Path::new("/root")),
3071            true,
3072            fs.clone(),
3073            Default::default(),
3074            &mut cx.to_async(),
3075        )
3076        .await
3077        .unwrap();
3078
3079        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3080            .await;
3081
3082        tree.read_with(cx, |tree, _| {
3083            assert_eq!(
3084                tree.entries(false)
3085                    .map(|entry| entry.path.as_ref())
3086                    .collect::<Vec<_>>(),
3087                vec![
3088                    Path::new(""),
3089                    Path::new("lib"),
3090                    Path::new("lib/a"),
3091                    Path::new("lib/a/a.txt"),
3092                    Path::new("lib/a/lib"),
3093                    Path::new("lib/b"),
3094                    Path::new("lib/b/b.txt"),
3095                    Path::new("lib/b/lib"),
3096                ]
3097            );
3098        });
3099
3100        fs.rename(
3101            Path::new("/root/lib/a/lib"),
3102            Path::new("/root/lib/a/lib-2"),
3103            Default::default(),
3104        )
3105        .await
3106        .unwrap();
3107        executor.run_until_parked();
3108        tree.read_with(cx, |tree, _| {
3109            assert_eq!(
3110                tree.entries(false)
3111                    .map(|entry| entry.path.as_ref())
3112                    .collect::<Vec<_>>(),
3113                vec![
3114                    Path::new(""),
3115                    Path::new("lib"),
3116                    Path::new("lib/a"),
3117                    Path::new("lib/a/a.txt"),
3118                    Path::new("lib/a/lib-2"),
3119                    Path::new("lib/b"),
3120                    Path::new("lib/b/b.txt"),
3121                    Path::new("lib/b/lib"),
3122                ]
3123            );
3124        });
3125    }
3126
3127    #[gpui::test]
3128    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3129        let parent_dir = temp_tree(json!({
3130            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3131            "tree": {
3132                ".git": {},
3133                ".gitignore": "ignored-dir\n",
3134                "tracked-dir": {
3135                    "tracked-file1": "",
3136                    "ancestor-ignored-file1": "",
3137                },
3138                "ignored-dir": {
3139                    "ignored-file1": ""
3140                }
3141            }
3142        }));
3143        let dir = parent_dir.path().join("tree");
3144
3145        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3146
3147        let tree = Worktree::local(
3148            client,
3149            dir.as_path(),
3150            true,
3151            Arc::new(RealFs),
3152            Default::default(),
3153            &mut cx.to_async(),
3154        )
3155        .await
3156        .unwrap();
3157        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3158            .await;
3159        tree.flush_fs_events(cx).await;
3160        cx.read(|cx| {
3161            let tree = tree.read(cx);
3162            assert!(
3163                !tree
3164                    .entry_for_path("tracked-dir/tracked-file1")
3165                    .unwrap()
3166                    .is_ignored
3167            );
3168            assert!(
3169                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3170                    .unwrap()
3171                    .is_ignored
3172            );
3173            assert!(
3174                tree.entry_for_path("ignored-dir/ignored-file1")
3175                    .unwrap()
3176                    .is_ignored
3177            );
3178        });
3179
3180        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3181        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3182        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3183        tree.flush_fs_events(cx).await;
3184        cx.read(|cx| {
3185            let tree = tree.read(cx);
3186            assert!(
3187                !tree
3188                    .entry_for_path("tracked-dir/tracked-file2")
3189                    .unwrap()
3190                    .is_ignored
3191            );
3192            assert!(
3193                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3194                    .unwrap()
3195                    .is_ignored
3196            );
3197            assert!(
3198                tree.entry_for_path("ignored-dir/ignored-file2")
3199                    .unwrap()
3200                    .is_ignored
3201            );
3202            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3203        });
3204    }
3205
3206    #[gpui::test]
3207    async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3208        let root = temp_tree(json!({
3209            "dir1": {
3210                ".git": {},
3211                "deps": {
3212                    "dep1": {
3213                        ".git": {},
3214                        "src": {
3215                            "a.txt": ""
3216                        }
3217                    }
3218                },
3219                "src": {
3220                    "b.txt": ""
3221                }
3222            },
3223            "c.txt": "",
3224
3225        }));
3226
3227        let http_client = FakeHttpClient::with_404_response();
3228        let client = cx.read(|cx| Client::new(http_client, cx));
3229        let tree = Worktree::local(
3230            client,
3231            root.path(),
3232            true,
3233            Arc::new(RealFs),
3234            Default::default(),
3235            &mut cx.to_async(),
3236        )
3237        .await
3238        .unwrap();
3239
3240        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3241            .await;
3242        tree.flush_fs_events(cx).await;
3243
3244        tree.read_with(cx, |tree, _cx| {
3245            let tree = tree.as_local().unwrap();
3246
3247            assert!(tree.repo_for("c.txt".as_ref()).is_none());
3248
3249            let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3250            assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3251            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3252
3253            let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3254            assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3255            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3256        });
3257
3258        let original_scan_id = tree.read_with(cx, |tree, _cx| {
3259            let tree = tree.as_local().unwrap();
3260            tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3261        });
3262
3263        std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3264        tree.flush_fs_events(cx).await;
3265
3266        tree.read_with(cx, |tree, _cx| {
3267            let tree = tree.as_local().unwrap();
3268            let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3269            assert_ne!(
3270                original_scan_id, new_scan_id,
3271                "original {original_scan_id}, new {new_scan_id}"
3272            );
3273        });
3274
3275        std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3276        tree.flush_fs_events(cx).await;
3277
3278        tree.read_with(cx, |tree, _cx| {
3279            let tree = tree.as_local().unwrap();
3280
3281            assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3282        });
3283    }
3284
3285    #[test]
3286    fn test_changed_repos() {
3287        fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3288            GitRepositoryEntry {
3289                repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3290                scan_id,
3291                content_path: git_dir_path.as_ref().parent().unwrap().into(),
3292                git_dir_path: git_dir_path.as_ref().into(),
3293            }
3294        }
3295
3296        let prev_repos: Vec<GitRepositoryEntry> = vec![
3297            fake_entry("/.git", 0),
3298            fake_entry("/a/.git", 0),
3299            fake_entry("/a/b/.git", 0),
3300        ];
3301
3302        let new_repos: Vec<GitRepositoryEntry> = vec![
3303            fake_entry("/a/.git", 1),
3304            fake_entry("/a/b/.git", 0),
3305            fake_entry("/a/c/.git", 0),
3306        ];
3307
3308        let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3309
3310        // Deletion retained
3311        assert!(res
3312            .iter()
3313            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3314            .is_some());
3315
3316        // Update retained
3317        assert!(res
3318            .iter()
3319            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3320            .is_some());
3321
3322        // Addition retained
3323        assert!(res
3324            .iter()
3325            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3326            .is_some());
3327
3328        // Nochange, not retained
3329        assert!(res
3330            .iter()
3331            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3332            .is_none());
3333    }
3334
3335    #[gpui::test]
3336    async fn test_write_file(cx: &mut TestAppContext) {
3337        let dir = temp_tree(json!({
3338            ".git": {},
3339            ".gitignore": "ignored-dir\n",
3340            "tracked-dir": {},
3341            "ignored-dir": {}
3342        }));
3343
3344        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3345
3346        let tree = Worktree::local(
3347            client,
3348            dir.path(),
3349            true,
3350            Arc::new(RealFs),
3351            Default::default(),
3352            &mut cx.to_async(),
3353        )
3354        .await
3355        .unwrap();
3356        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3357            .await;
3358        tree.flush_fs_events(cx).await;
3359
3360        tree.update(cx, |tree, cx| {
3361            tree.as_local().unwrap().write_file(
3362                Path::new("tracked-dir/file.txt"),
3363                "hello".into(),
3364                Default::default(),
3365                cx,
3366            )
3367        })
3368        .await
3369        .unwrap();
3370        tree.update(cx, |tree, cx| {
3371            tree.as_local().unwrap().write_file(
3372                Path::new("ignored-dir/file.txt"),
3373                "world".into(),
3374                Default::default(),
3375                cx,
3376            )
3377        })
3378        .await
3379        .unwrap();
3380
3381        tree.read_with(cx, |tree, _| {
3382            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3383            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3384            assert!(!tracked.is_ignored);
3385            assert!(ignored.is_ignored);
3386        });
3387    }
3388
3389    #[gpui::test(iterations = 30)]
3390    async fn test_create_directory(cx: &mut TestAppContext) {
3391        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3392
3393        let fs = FakeFs::new(cx.background());
3394        fs.insert_tree(
3395            "/a",
3396            json!({
3397                "b": {},
3398                "c": {},
3399                "d": {},
3400            }),
3401        )
3402        .await;
3403
3404        let tree = Worktree::local(
3405            client,
3406            "/a".as_ref(),
3407            true,
3408            fs,
3409            Default::default(),
3410            &mut cx.to_async(),
3411        )
3412        .await
3413        .unwrap();
3414
3415        let entry = tree
3416            .update(cx, |tree, cx| {
3417                tree.as_local_mut()
3418                    .unwrap()
3419                    .create_entry("a/e".as_ref(), true, cx)
3420            })
3421            .await
3422            .unwrap();
3423        assert!(entry.is_dir());
3424
3425        cx.foreground().run_until_parked();
3426        tree.read_with(cx, |tree, _| {
3427            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3428        });
3429    }
3430
3431    #[gpui::test(iterations = 100)]
3432    fn test_random(mut rng: StdRng) {
3433        let operations = env::var("OPERATIONS")
3434            .map(|o| o.parse().unwrap())
3435            .unwrap_or(40);
3436        let initial_entries = env::var("INITIAL_ENTRIES")
3437            .map(|o| o.parse().unwrap())
3438            .unwrap_or(20);
3439
3440        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
3441        for _ in 0..initial_entries {
3442            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
3443        }
3444        log::info!("Generated initial tree");
3445
3446        let (notify_tx, _notify_rx) = mpsc::unbounded();
3447        let fs = Arc::new(RealFs);
3448        let next_entry_id = Arc::new(AtomicUsize::new(0));
3449        let mut initial_snapshot = LocalSnapshot {
3450            abs_path: root_dir.path().into(),
3451            removed_entry_ids: Default::default(),
3452            ignores_by_parent_abs_path: Default::default(),
3453            git_repositories: Default::default(),
3454            next_entry_id: next_entry_id.clone(),
3455            snapshot: Snapshot {
3456                id: WorktreeId::from_usize(0),
3457                entries_by_path: Default::default(),
3458                entries_by_id: Default::default(),
3459                root_name: Default::default(),
3460                root_char_bag: Default::default(),
3461                scan_id: 0,
3462                is_complete: true,
3463            },
3464            extension_counts: Default::default(),
3465        };
3466        initial_snapshot.insert_entry(
3467            Entry::new(
3468                Path::new("").into(),
3469                &smol::block_on(fs.metadata(root_dir.path()))
3470                    .unwrap()
3471                    .unwrap(),
3472                &next_entry_id,
3473                Default::default(),
3474            ),
3475            fs.as_ref(),
3476        );
3477        let mut scanner = BackgroundScanner::new(
3478            Arc::new(Mutex::new(initial_snapshot.clone())),
3479            notify_tx,
3480            fs.clone(),
3481            Arc::new(gpui::executor::Background::new()),
3482        );
3483        smol::block_on(scanner.scan_dirs()).unwrap();
3484        scanner.snapshot().check_invariants();
3485
3486        let mut events = Vec::new();
3487        let mut snapshots = Vec::new();
3488        let mut mutations_len = operations;
3489        while mutations_len > 1 {
3490            if !events.is_empty() && rng.gen_bool(0.4) {
3491                let len = rng.gen_range(0..=events.len());
3492                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3493                log::info!("Delivering events: {:#?}", to_deliver);
3494                smol::block_on(scanner.process_events(to_deliver));
3495                scanner.snapshot().check_invariants();
3496            } else {
3497                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3498                mutations_len -= 1;
3499            }
3500
3501            if rng.gen_bool(0.2) {
3502                snapshots.push(scanner.snapshot());
3503            }
3504        }
3505        log::info!("Quiescing: {:#?}", events);
3506        smol::block_on(scanner.process_events(events));
3507        scanner.snapshot().check_invariants();
3508
3509        let (notify_tx, _notify_rx) = mpsc::unbounded();
3510        let mut new_scanner = BackgroundScanner::new(
3511            Arc::new(Mutex::new(initial_snapshot)),
3512            notify_tx,
3513            scanner.fs.clone(),
3514            scanner.executor.clone(),
3515        );
3516        smol::block_on(new_scanner.scan_dirs()).unwrap();
3517        assert_eq!(
3518            scanner.snapshot().to_vec(true),
3519            new_scanner.snapshot().to_vec(true)
3520        );
3521
3522        for mut prev_snapshot in snapshots {
3523            let include_ignored = rng.gen::<bool>();
3524            if !include_ignored {
3525                let mut entries_by_path_edits = Vec::new();
3526                let mut entries_by_id_edits = Vec::new();
3527                for entry in prev_snapshot
3528                    .entries_by_id
3529                    .cursor::<()>()
3530                    .filter(|e| e.is_ignored)
3531                {
3532                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3533                    entries_by_id_edits.push(Edit::Remove(entry.id));
3534                }
3535
3536                prev_snapshot
3537                    .entries_by_path
3538                    .edit(entries_by_path_edits, &());
3539                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3540            }
3541
3542            let update = scanner
3543                .snapshot()
3544                .build_update(&prev_snapshot, 0, 0, include_ignored);
3545            prev_snapshot.apply_remote_update(update).unwrap();
3546            assert_eq!(
3547                prev_snapshot.to_vec(true),
3548                scanner.snapshot().to_vec(include_ignored)
3549            );
3550        }
3551    }
3552
3553    fn randomly_mutate_tree(
3554        root_path: &Path,
3555        insertion_probability: f64,
3556        rng: &mut impl Rng,
3557    ) -> Result<Vec<fsevent::Event>> {
3558        let root_path = root_path.canonicalize().unwrap();
3559        let (dirs, files) = read_dir_recursive(root_path.clone());
3560
3561        let mut events = Vec::new();
3562        let mut record_event = |path: PathBuf| {
3563            events.push(fsevent::Event {
3564                event_id: SystemTime::now()
3565                    .duration_since(UNIX_EPOCH)
3566                    .unwrap()
3567                    .as_secs(),
3568                flags: fsevent::StreamFlags::empty(),
3569                path,
3570            });
3571        };
3572
3573        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3574            let path = dirs.choose(rng).unwrap();
3575            let new_path = path.join(gen_name(rng));
3576
3577            if rng.gen() {
3578                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3579                std::fs::create_dir(&new_path)?;
3580            } else {
3581                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3582                std::fs::write(&new_path, "")?;
3583            }
3584            record_event(new_path);
3585        } else if rng.gen_bool(0.05) {
3586            let ignore_dir_path = dirs.choose(rng).unwrap();
3587            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3588
3589            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3590            let files_to_ignore = {
3591                let len = rng.gen_range(0..=subfiles.len());
3592                subfiles.choose_multiple(rng, len)
3593            };
3594            let dirs_to_ignore = {
3595                let len = rng.gen_range(0..subdirs.len());
3596                subdirs.choose_multiple(rng, len)
3597            };
3598
3599            let mut ignore_contents = String::new();
3600            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3601                writeln!(
3602                    ignore_contents,
3603                    "{}",
3604                    path_to_ignore
3605                        .strip_prefix(&ignore_dir_path)?
3606                        .to_str()
3607                        .unwrap()
3608                )
3609                .unwrap();
3610            }
3611            log::info!(
3612                "Creating {:?} with contents:\n{}",
3613                ignore_path.strip_prefix(&root_path)?,
3614                ignore_contents
3615            );
3616            std::fs::write(&ignore_path, ignore_contents).unwrap();
3617            record_event(ignore_path);
3618        } else {
3619            let old_path = {
3620                let file_path = files.choose(rng);
3621                let dir_path = dirs[1..].choose(rng);
3622                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3623            };
3624
3625            let is_rename = rng.gen();
3626            if is_rename {
3627                let new_path_parent = dirs
3628                    .iter()
3629                    .filter(|d| !d.starts_with(old_path))
3630                    .choose(rng)
3631                    .unwrap();
3632
3633                let overwrite_existing_dir =
3634                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3635                let new_path = if overwrite_existing_dir {
3636                    std::fs::remove_dir_all(&new_path_parent).ok();
3637                    new_path_parent.to_path_buf()
3638                } else {
3639                    new_path_parent.join(gen_name(rng))
3640                };
3641
3642                log::info!(
3643                    "Renaming {:?} to {}{:?}",
3644                    old_path.strip_prefix(&root_path)?,
3645                    if overwrite_existing_dir {
3646                        "overwrite "
3647                    } else {
3648                        ""
3649                    },
3650                    new_path.strip_prefix(&root_path)?
3651                );
3652                std::fs::rename(&old_path, &new_path)?;
3653                record_event(old_path.clone());
3654                record_event(new_path);
3655            } else if old_path.is_dir() {
3656                let (dirs, files) = read_dir_recursive(old_path.clone());
3657
3658                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3659                std::fs::remove_dir_all(&old_path).unwrap();
3660                for file in files {
3661                    record_event(file);
3662                }
3663                for dir in dirs {
3664                    record_event(dir);
3665                }
3666            } else {
3667                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3668                std::fs::remove_file(old_path).unwrap();
3669                record_event(old_path.clone());
3670            }
3671        }
3672
3673        Ok(events)
3674    }
3675
3676    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3677        let child_entries = std::fs::read_dir(&path).unwrap();
3678        let mut dirs = vec![path];
3679        let mut files = Vec::new();
3680        for child_entry in child_entries {
3681            let child_path = child_entry.unwrap().path();
3682            if child_path.is_dir() {
3683                let (child_dirs, child_files) = read_dir_recursive(child_path);
3684                dirs.extend(child_dirs);
3685                files.extend(child_files);
3686            } else {
3687                files.push(child_path);
3688            }
3689        }
3690        (dirs, files)
3691    }
3692
3693    fn gen_name(rng: &mut impl Rng) -> String {
3694        (0..6)
3695            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3696            .map(char::from)
3697            .collect()
3698    }
3699
3700    impl LocalSnapshot {
3701        fn check_invariants(&self) {
3702            let mut files = self.files(true, 0);
3703            let mut visible_files = self.files(false, 0);
3704            for entry in self.entries_by_path.cursor::<()>() {
3705                if entry.is_file() {
3706                    assert_eq!(files.next().unwrap().inode, entry.inode);
3707                    if !entry.is_ignored {
3708                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3709                    }
3710                }
3711            }
3712            assert!(files.next().is_none());
3713            assert!(visible_files.next().is_none());
3714
3715            let mut bfs_paths = Vec::new();
3716            let mut stack = vec![Path::new("")];
3717            while let Some(path) = stack.pop() {
3718                bfs_paths.push(path);
3719                let ix = stack.len();
3720                for child_entry in self.child_entries(path) {
3721                    stack.insert(ix, &child_entry.path);
3722                }
3723            }
3724
3725            let dfs_paths_via_iter = self
3726                .entries_by_path
3727                .cursor::<()>()
3728                .map(|e| e.path.as_ref())
3729                .collect::<Vec<_>>();
3730            assert_eq!(bfs_paths, dfs_paths_via_iter);
3731
3732            let dfs_paths_via_traversal = self
3733                .entries(true)
3734                .map(|e| e.path.as_ref())
3735                .collect::<Vec<_>>();
3736            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3737
3738            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3739                let ignore_parent_path =
3740                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3741                assert!(self.entry_for_path(&ignore_parent_path).is_some());
3742                assert!(self
3743                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3744                    .is_some());
3745            }
3746
3747            // Ensure extension counts are correct.
3748            let mut expected_extension_counts = HashMap::default();
3749            for extension in self.entries(false).filter_map(|e| e.path.extension()) {
3750                *expected_extension_counts
3751                    .entry(extension.into())
3752                    .or_insert(0) += 1;
3753            }
3754            assert_eq!(self.extension_counts, expected_extension_counts);
3755        }
3756
3757        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3758            let mut paths = Vec::new();
3759            for entry in self.entries_by_path.cursor::<()>() {
3760                if include_ignored || !entry.is_ignored {
3761                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3762                }
3763            }
3764            paths.sort_by(|a, b| a.0.cmp(b.0));
3765            paths
3766        }
3767    }
3768}