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