worktree.rs

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