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