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