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