worktree.rs

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