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, UnboundedReceiver, UnboundedSender},
  13        oneshot,
  14    },
  15    select_biased, Stream, StreamExt,
  16};
  17use fuzzy::CharBag;
  18use git::{DOT_GIT, GITIGNORE};
  19use gpui::{
  20    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  21    Task,
  22};
  23use language::{
  24    proto::{
  25        deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
  26        serialize_version,
  27    },
  28    Buffer, DiagnosticEntry, File as _, PointUtf16, Rope, RopeFingerprint, Unclipped,
  29};
  30use parking_lot::Mutex;
  31use postage::{
  32    barrier,
  33    prelude::{Sink as _, Stream as _},
  34    watch,
  35};
  36use smol::channel::{self, Sender};
  37use std::{
  38    any::Any,
  39    cmp::{self, Ordering},
  40    convert::TryFrom,
  41    ffi::OsStr,
  42    fmt,
  43    future::Future,
  44    mem,
  45    ops::{Deref, DerefMut},
  46    path::{Path, PathBuf},
  47    sync::{atomic::AtomicUsize, Arc},
  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: mpsc::UnboundedSender<(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) = mpsc::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 MutableAppContext,
 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                    .unbounded_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.unbounded_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            let entry = self
1228                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1229                .ok_or_else(|| anyhow!("unknown entry {}", entry_id))?;
1230            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1231            entries_by_id_edits.push(Edit::Remove(entry.id));
1232        }
1233
1234        for entry in update.updated_entries {
1235            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1236            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1237                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1238            }
1239            entries_by_id_edits.push(Edit::Insert(PathEntry {
1240                id: entry.id,
1241                path: entry.path.clone(),
1242                is_ignored: entry.is_ignored,
1243                scan_id: 0,
1244            }));
1245            entries_by_path_edits.push(Edit::Insert(entry));
1246        }
1247
1248        self.entries_by_path.edit(entries_by_path_edits, &());
1249        self.entries_by_id.edit(entries_by_id_edits, &());
1250        self.scan_id = update.scan_id as usize;
1251        if update.is_last_update {
1252            self.completed_scan_id = update.scan_id as usize;
1253        }
1254
1255        Ok(())
1256    }
1257
1258    pub fn file_count(&self) -> usize {
1259        self.entries_by_path.summary().file_count
1260    }
1261
1262    pub fn visible_file_count(&self) -> usize {
1263        self.entries_by_path.summary().visible_file_count
1264    }
1265
1266    fn traverse_from_offset(
1267        &self,
1268        include_dirs: bool,
1269        include_ignored: bool,
1270        start_offset: usize,
1271    ) -> Traversal {
1272        let mut cursor = self.entries_by_path.cursor();
1273        cursor.seek(
1274            &TraversalTarget::Count {
1275                count: start_offset,
1276                include_dirs,
1277                include_ignored,
1278            },
1279            Bias::Right,
1280            &(),
1281        );
1282        Traversal {
1283            cursor,
1284            include_dirs,
1285            include_ignored,
1286        }
1287    }
1288
1289    fn traverse_from_path(
1290        &self,
1291        include_dirs: bool,
1292        include_ignored: bool,
1293        path: &Path,
1294    ) -> Traversal {
1295        let mut cursor = self.entries_by_path.cursor();
1296        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1297        Traversal {
1298            cursor,
1299            include_dirs,
1300            include_ignored,
1301        }
1302    }
1303
1304    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1305        self.traverse_from_offset(false, include_ignored, start)
1306    }
1307
1308    pub fn entries(&self, include_ignored: bool) -> Traversal {
1309        self.traverse_from_offset(true, include_ignored, 0)
1310    }
1311
1312    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1313        let empty_path = Path::new("");
1314        self.entries_by_path
1315            .cursor::<()>()
1316            .filter(move |entry| entry.path.as_ref() != empty_path)
1317            .map(|entry| &entry.path)
1318    }
1319
1320    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1321        let mut cursor = self.entries_by_path.cursor();
1322        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1323        let traversal = Traversal {
1324            cursor,
1325            include_dirs: true,
1326            include_ignored: true,
1327        };
1328        ChildEntriesIter {
1329            traversal,
1330            parent_path,
1331        }
1332    }
1333
1334    pub fn root_entry(&self) -> Option<&Entry> {
1335        self.entry_for_path("")
1336    }
1337
1338    pub fn root_name(&self) -> &str {
1339        &self.root_name
1340    }
1341
1342    pub fn scan_started(&mut self) {
1343        self.scan_id += 1;
1344    }
1345
1346    pub fn scan_completed(&mut self) {
1347        self.completed_scan_id = self.scan_id;
1348    }
1349
1350    pub fn scan_id(&self) -> usize {
1351        self.scan_id
1352    }
1353
1354    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1355        let path = path.as_ref();
1356        self.traverse_from_path(true, true, path)
1357            .entry()
1358            .and_then(|entry| {
1359                if entry.path.as_ref() == path {
1360                    Some(entry)
1361                } else {
1362                    None
1363                }
1364            })
1365    }
1366
1367    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1368        let entry = self.entries_by_id.get(&id, &())?;
1369        self.entry_for_path(&entry.path)
1370    }
1371
1372    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1373        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1374    }
1375}
1376
1377impl LocalSnapshot {
1378    // Gives the most specific git repository for a given path
1379    pub(crate) fn repo_for(&self, path: &Path) -> Option<GitRepositoryEntry> {
1380        self.git_repositories
1381            .iter()
1382            .rev() //git_repository is ordered lexicographically
1383            .find(|repo| repo.manages(path))
1384            .cloned()
1385    }
1386
1387    pub(crate) fn repo_with_dot_git_containing(
1388        &mut self,
1389        path: &Path,
1390    ) -> Option<&mut GitRepositoryEntry> {
1391        // Git repositories cannot be nested, so we don't need to reverse the order
1392        self.git_repositories
1393            .iter_mut()
1394            .find(|repo| repo.in_dot_git(path))
1395    }
1396
1397    #[cfg(test)]
1398    pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1399        let root_name = self.root_name.clone();
1400        proto::UpdateWorktree {
1401            project_id,
1402            worktree_id: self.id().to_proto(),
1403            abs_path: self.abs_path().to_string_lossy().into(),
1404            root_name,
1405            updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1406            removed_entries: Default::default(),
1407            scan_id: self.scan_id as u64,
1408            is_last_update: true,
1409        }
1410    }
1411
1412    pub(crate) fn build_update(
1413        &self,
1414        other: &Self,
1415        project_id: u64,
1416        worktree_id: u64,
1417        include_ignored: bool,
1418    ) -> proto::UpdateWorktree {
1419        let mut updated_entries = Vec::new();
1420        let mut removed_entries = Vec::new();
1421        let mut self_entries = self
1422            .entries_by_id
1423            .cursor::<()>()
1424            .filter(|e| include_ignored || !e.is_ignored)
1425            .peekable();
1426        let mut other_entries = other
1427            .entries_by_id
1428            .cursor::<()>()
1429            .filter(|e| include_ignored || !e.is_ignored)
1430            .peekable();
1431        loop {
1432            match (self_entries.peek(), other_entries.peek()) {
1433                (Some(self_entry), Some(other_entry)) => {
1434                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1435                        Ordering::Less => {
1436                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1437                            updated_entries.push(entry);
1438                            self_entries.next();
1439                        }
1440                        Ordering::Equal => {
1441                            if self_entry.scan_id != other_entry.scan_id {
1442                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1443                                updated_entries.push(entry);
1444                            }
1445
1446                            self_entries.next();
1447                            other_entries.next();
1448                        }
1449                        Ordering::Greater => {
1450                            removed_entries.push(other_entry.id.to_proto());
1451                            other_entries.next();
1452                        }
1453                    }
1454                }
1455                (Some(self_entry), None) => {
1456                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1457                    updated_entries.push(entry);
1458                    self_entries.next();
1459                }
1460                (None, Some(other_entry)) => {
1461                    removed_entries.push(other_entry.id.to_proto());
1462                    other_entries.next();
1463                }
1464                (None, None) => break,
1465            }
1466        }
1467
1468        proto::UpdateWorktree {
1469            project_id,
1470            worktree_id,
1471            abs_path: self.abs_path().to_string_lossy().into(),
1472            root_name: self.root_name().to_string(),
1473            updated_entries,
1474            removed_entries,
1475            scan_id: self.scan_id as u64,
1476            is_last_update: self.completed_scan_id == self.scan_id,
1477        }
1478    }
1479
1480    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1481        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1482            let abs_path = self.abs_path.join(&entry.path);
1483            match smol::block_on(build_gitignore(&abs_path, fs)) {
1484                Ok(ignore) => {
1485                    self.ignores_by_parent_abs_path.insert(
1486                        abs_path.parent().unwrap().into(),
1487                        (Arc::new(ignore), self.scan_id),
1488                    );
1489                }
1490                Err(error) => {
1491                    log::error!(
1492                        "error loading .gitignore file {:?} - {:?}",
1493                        &entry.path,
1494                        error
1495                    );
1496                }
1497            }
1498        }
1499
1500        self.reuse_entry_id(&mut entry);
1501
1502        if entry.kind == EntryKind::PendingDir {
1503            if let Some(existing_entry) =
1504                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1505            {
1506                entry.kind = existing_entry.kind;
1507            }
1508        }
1509
1510        let scan_id = self.scan_id;
1511        self.entries_by_path.insert_or_replace(entry.clone(), &());
1512        self.entries_by_id.insert_or_replace(
1513            PathEntry {
1514                id: entry.id,
1515                path: entry.path.clone(),
1516                is_ignored: entry.is_ignored,
1517                scan_id,
1518            },
1519            &(),
1520        );
1521
1522        entry
1523    }
1524
1525    fn populate_dir(
1526        &mut self,
1527        parent_path: Arc<Path>,
1528        entries: impl IntoIterator<Item = Entry>,
1529        ignore: Option<Arc<Gitignore>>,
1530        fs: &dyn Fs,
1531    ) {
1532        let mut parent_entry = if let Some(parent_entry) =
1533            self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1534        {
1535            parent_entry.clone()
1536        } else {
1537            log::warn!(
1538                "populating a directory {:?} that has been removed",
1539                parent_path
1540            );
1541            return;
1542        };
1543
1544        if let Some(ignore) = ignore {
1545            self.ignores_by_parent_abs_path.insert(
1546                self.abs_path.join(&parent_path).into(),
1547                (ignore, self.scan_id),
1548            );
1549        }
1550        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1551            parent_entry.kind = EntryKind::Dir;
1552        } else {
1553            unreachable!();
1554        }
1555
1556        if parent_path.file_name() == Some(&DOT_GIT) {
1557            let abs_path = self.abs_path.join(&parent_path);
1558            let content_path: Arc<Path> = parent_path.parent().unwrap().into();
1559            if let Err(ix) = self
1560                .git_repositories
1561                .binary_search_by_key(&&content_path, |repo| &repo.content_path)
1562            {
1563                if let Some(repo) = fs.open_repo(abs_path.as_path()) {
1564                    self.git_repositories.insert(
1565                        ix,
1566                        GitRepositoryEntry {
1567                            repo,
1568                            scan_id: 0,
1569                            content_path,
1570                            git_dir_path: parent_path,
1571                        },
1572                    );
1573                }
1574            }
1575        }
1576
1577        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1578        let mut entries_by_id_edits = Vec::new();
1579
1580        for mut entry in entries {
1581            self.reuse_entry_id(&mut entry);
1582            entries_by_id_edits.push(Edit::Insert(PathEntry {
1583                id: entry.id,
1584                path: entry.path.clone(),
1585                is_ignored: entry.is_ignored,
1586                scan_id: self.scan_id,
1587            }));
1588            entries_by_path_edits.push(Edit::Insert(entry));
1589        }
1590
1591        self.entries_by_path.edit(entries_by_path_edits, &());
1592        self.entries_by_id.edit(entries_by_id_edits, &());
1593    }
1594
1595    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1596        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1597            entry.id = removed_entry_id;
1598        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1599            entry.id = existing_entry.id;
1600        }
1601    }
1602
1603    fn remove_path(&mut self, path: &Path) {
1604        let mut new_entries;
1605        let removed_entries;
1606        {
1607            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1608            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1609            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1610            new_entries.push_tree(cursor.suffix(&()), &());
1611        }
1612        self.entries_by_path = new_entries;
1613
1614        let mut entries_by_id_edits = Vec::new();
1615        for entry in removed_entries.cursor::<()>() {
1616            let removed_entry_id = self
1617                .removed_entry_ids
1618                .entry(entry.inode)
1619                .or_insert(entry.id);
1620            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1621            entries_by_id_edits.push(Edit::Remove(entry.id));
1622        }
1623        self.entries_by_id.edit(entries_by_id_edits, &());
1624
1625        if path.file_name() == Some(&GITIGNORE) {
1626            let abs_parent_path = self.abs_path.join(path.parent().unwrap());
1627            if let Some((_, scan_id)) = self
1628                .ignores_by_parent_abs_path
1629                .get_mut(abs_parent_path.as_path())
1630            {
1631                *scan_id = self.snapshot.scan_id;
1632            }
1633        } else if path.file_name() == Some(&DOT_GIT) {
1634            let parent_path = path.parent().unwrap();
1635            if let Ok(ix) = self
1636                .git_repositories
1637                .binary_search_by_key(&parent_path, |repo| repo.git_dir_path.as_ref())
1638            {
1639                self.git_repositories[ix].scan_id = self.snapshot.scan_id;
1640            }
1641        }
1642    }
1643
1644    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
1645        let mut inodes = TreeSet::default();
1646        for ancestor in path.ancestors().skip(1) {
1647            if let Some(entry) = self.entry_for_path(ancestor) {
1648                inodes.insert(entry.inode);
1649            }
1650        }
1651        inodes
1652    }
1653
1654    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1655        let mut new_ignores = Vec::new();
1656        for ancestor in abs_path.ancestors().skip(1) {
1657            if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
1658                new_ignores.push((ancestor, Some(ignore.clone())));
1659            } else {
1660                new_ignores.push((ancestor, None));
1661            }
1662        }
1663
1664        let mut ignore_stack = IgnoreStack::none();
1665        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
1666            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
1667                ignore_stack = IgnoreStack::all();
1668                break;
1669            } else if let Some(ignore) = ignore {
1670                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
1671            }
1672        }
1673
1674        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
1675            ignore_stack = IgnoreStack::all();
1676        }
1677
1678        ignore_stack
1679    }
1680
1681    pub fn git_repo_entries(&self) -> &[GitRepositoryEntry] {
1682        &self.git_repositories
1683    }
1684}
1685
1686impl GitRepositoryEntry {
1687    // Note that these paths should be relative to the worktree root.
1688    pub(crate) fn manages(&self, path: &Path) -> bool {
1689        path.starts_with(self.content_path.as_ref())
1690    }
1691
1692    // Note that this path should be relative to the worktree root.
1693    pub(crate) fn in_dot_git(&self, path: &Path) -> bool {
1694        path.starts_with(self.git_dir_path.as_ref())
1695    }
1696}
1697
1698async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1699    let contents = fs.load(abs_path).await?;
1700    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
1701    let mut builder = GitignoreBuilder::new(parent);
1702    for line in contents.lines() {
1703        builder.add_line(Some(abs_path.into()), line)?;
1704    }
1705    Ok(builder.build()?)
1706}
1707
1708impl WorktreeId {
1709    pub fn from_usize(handle_id: usize) -> Self {
1710        Self(handle_id)
1711    }
1712
1713    pub(crate) fn from_proto(id: u64) -> Self {
1714        Self(id as usize)
1715    }
1716
1717    pub fn to_proto(&self) -> u64 {
1718        self.0 as u64
1719    }
1720
1721    pub fn to_usize(&self) -> usize {
1722        self.0
1723    }
1724}
1725
1726impl fmt::Display for WorktreeId {
1727    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1728        self.0.fmt(f)
1729    }
1730}
1731
1732impl Deref for Worktree {
1733    type Target = Snapshot;
1734
1735    fn deref(&self) -> &Self::Target {
1736        match self {
1737            Worktree::Local(worktree) => &worktree.snapshot,
1738            Worktree::Remote(worktree) => &worktree.snapshot,
1739        }
1740    }
1741}
1742
1743impl Deref for LocalWorktree {
1744    type Target = LocalSnapshot;
1745
1746    fn deref(&self) -> &Self::Target {
1747        &self.snapshot
1748    }
1749}
1750
1751impl Deref for RemoteWorktree {
1752    type Target = Snapshot;
1753
1754    fn deref(&self) -> &Self::Target {
1755        &self.snapshot
1756    }
1757}
1758
1759impl fmt::Debug for LocalWorktree {
1760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1761        self.snapshot.fmt(f)
1762    }
1763}
1764
1765impl fmt::Debug for Snapshot {
1766    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1767        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1768        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1769
1770        impl<'a> fmt::Debug for EntriesByPath<'a> {
1771            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1772                f.debug_map()
1773                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1774                    .finish()
1775            }
1776        }
1777
1778        impl<'a> fmt::Debug for EntriesById<'a> {
1779            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1780                f.debug_list().entries(self.0.iter()).finish()
1781            }
1782        }
1783
1784        f.debug_struct("Snapshot")
1785            .field("id", &self.id)
1786            .field("root_name", &self.root_name)
1787            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1788            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1789            .finish()
1790    }
1791}
1792
1793#[derive(Clone, PartialEq)]
1794pub struct File {
1795    pub worktree: ModelHandle<Worktree>,
1796    pub path: Arc<Path>,
1797    pub mtime: SystemTime,
1798    pub(crate) entry_id: ProjectEntryId,
1799    pub(crate) is_local: bool,
1800    pub(crate) is_deleted: bool,
1801}
1802
1803impl language::File for File {
1804    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1805        if self.is_local {
1806            Some(self)
1807        } else {
1808            None
1809        }
1810    }
1811
1812    fn mtime(&self) -> SystemTime {
1813        self.mtime
1814    }
1815
1816    fn path(&self) -> &Arc<Path> {
1817        &self.path
1818    }
1819
1820    fn full_path(&self, cx: &AppContext) -> PathBuf {
1821        let mut full_path = PathBuf::new();
1822        let worktree = self.worktree.read(cx);
1823
1824        if worktree.is_visible() {
1825            full_path.push(worktree.root_name());
1826        } else {
1827            let path = worktree.abs_path();
1828
1829            if worktree.is_local() && path.starts_with(HOME.as_path()) {
1830                full_path.push("~");
1831                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
1832            } else {
1833                full_path.push(path)
1834            }
1835        }
1836
1837        if self.path.components().next().is_some() {
1838            full_path.push(&self.path);
1839        }
1840
1841        full_path
1842    }
1843
1844    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1845    /// of its worktree, then this method will return the name of the worktree itself.
1846    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
1847        self.path
1848            .file_name()
1849            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
1850    }
1851
1852    fn is_deleted(&self) -> bool {
1853        self.is_deleted
1854    }
1855
1856    fn as_any(&self) -> &dyn Any {
1857        self
1858    }
1859
1860    fn to_proto(&self) -> rpc::proto::File {
1861        rpc::proto::File {
1862            worktree_id: self.worktree.id() as u64,
1863            entry_id: self.entry_id.to_proto(),
1864            path: self.path.to_string_lossy().into(),
1865            mtime: Some(self.mtime.into()),
1866            is_deleted: self.is_deleted,
1867        }
1868    }
1869}
1870
1871impl language::LocalFile for File {
1872    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1873        self.worktree
1874            .read(cx)
1875            .as_local()
1876            .unwrap()
1877            .abs_path
1878            .join(&self.path)
1879    }
1880
1881    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1882        let worktree = self.worktree.read(cx).as_local().unwrap();
1883        let abs_path = worktree.absolutize(&self.path);
1884        let fs = worktree.fs.clone();
1885        cx.background()
1886            .spawn(async move { fs.load(&abs_path).await })
1887    }
1888
1889    fn buffer_reloaded(
1890        &self,
1891        buffer_id: u64,
1892        version: &clock::Global,
1893        fingerprint: RopeFingerprint,
1894        line_ending: LineEnding,
1895        mtime: SystemTime,
1896        cx: &mut MutableAppContext,
1897    ) {
1898        let worktree = self.worktree.read(cx).as_local().unwrap();
1899        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1900            worktree
1901                .client
1902                .send(proto::BufferReloaded {
1903                    project_id,
1904                    buffer_id,
1905                    version: serialize_version(version),
1906                    mtime: Some(mtime.into()),
1907                    fingerprint: serialize_fingerprint(fingerprint),
1908                    line_ending: serialize_line_ending(line_ending) as i32,
1909                })
1910                .log_err();
1911        }
1912    }
1913}
1914
1915impl File {
1916    pub fn from_proto(
1917        proto: rpc::proto::File,
1918        worktree: ModelHandle<Worktree>,
1919        cx: &AppContext,
1920    ) -> Result<Self> {
1921        let worktree_id = worktree
1922            .read(cx)
1923            .as_remote()
1924            .ok_or_else(|| anyhow!("not remote"))?
1925            .id();
1926
1927        if worktree_id.to_proto() != proto.worktree_id {
1928            return Err(anyhow!("worktree id does not match file"));
1929        }
1930
1931        Ok(Self {
1932            worktree,
1933            path: Path::new(&proto.path).into(),
1934            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1935            entry_id: ProjectEntryId::from_proto(proto.entry_id),
1936            is_local: false,
1937            is_deleted: proto.is_deleted,
1938        })
1939    }
1940
1941    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
1942        file.and_then(|f| f.as_any().downcast_ref())
1943    }
1944
1945    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1946        self.worktree.read(cx).id()
1947    }
1948
1949    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1950        if self.is_deleted {
1951            None
1952        } else {
1953            Some(self.entry_id)
1954        }
1955    }
1956}
1957
1958#[derive(Clone, Debug, PartialEq, Eq)]
1959pub struct Entry {
1960    pub id: ProjectEntryId,
1961    pub kind: EntryKind,
1962    pub path: Arc<Path>,
1963    pub inode: u64,
1964    pub mtime: SystemTime,
1965    pub is_symlink: bool,
1966    pub is_ignored: bool,
1967}
1968
1969#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1970pub enum EntryKind {
1971    PendingDir,
1972    Dir,
1973    File(CharBag),
1974}
1975
1976#[derive(Clone, Copy, Debug)]
1977pub enum PathChange {
1978    Added,
1979    Removed,
1980    Updated,
1981    AddedOrUpdated,
1982}
1983
1984impl Entry {
1985    fn new(
1986        path: Arc<Path>,
1987        metadata: &fs::Metadata,
1988        next_entry_id: &AtomicUsize,
1989        root_char_bag: CharBag,
1990    ) -> Self {
1991        Self {
1992            id: ProjectEntryId::new(next_entry_id),
1993            kind: if metadata.is_dir {
1994                EntryKind::PendingDir
1995            } else {
1996                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1997            },
1998            path,
1999            inode: metadata.inode,
2000            mtime: metadata.mtime,
2001            is_symlink: metadata.is_symlink,
2002            is_ignored: false,
2003        }
2004    }
2005
2006    pub fn is_dir(&self) -> bool {
2007        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2008    }
2009
2010    pub fn is_file(&self) -> bool {
2011        matches!(self.kind, EntryKind::File(_))
2012    }
2013}
2014
2015impl sum_tree::Item for Entry {
2016    type Summary = EntrySummary;
2017
2018    fn summary(&self) -> Self::Summary {
2019        let visible_count = if self.is_ignored { 0 } else { 1 };
2020        let file_count;
2021        let visible_file_count;
2022        if self.is_file() {
2023            file_count = 1;
2024            visible_file_count = visible_count;
2025        } else {
2026            file_count = 0;
2027            visible_file_count = 0;
2028        }
2029
2030        EntrySummary {
2031            max_path: self.path.clone(),
2032            count: 1,
2033            visible_count,
2034            file_count,
2035            visible_file_count,
2036        }
2037    }
2038}
2039
2040impl sum_tree::KeyedItem for Entry {
2041    type Key = PathKey;
2042
2043    fn key(&self) -> Self::Key {
2044        PathKey(self.path.clone())
2045    }
2046}
2047
2048#[derive(Clone, Debug)]
2049pub struct EntrySummary {
2050    max_path: Arc<Path>,
2051    count: usize,
2052    visible_count: usize,
2053    file_count: usize,
2054    visible_file_count: usize,
2055}
2056
2057impl Default for EntrySummary {
2058    fn default() -> Self {
2059        Self {
2060            max_path: Arc::from(Path::new("")),
2061            count: 0,
2062            visible_count: 0,
2063            file_count: 0,
2064            visible_file_count: 0,
2065        }
2066    }
2067}
2068
2069impl sum_tree::Summary for EntrySummary {
2070    type Context = ();
2071
2072    fn add_summary(&mut self, rhs: &Self, _: &()) {
2073        self.max_path = rhs.max_path.clone();
2074        self.count += rhs.count;
2075        self.visible_count += rhs.visible_count;
2076        self.file_count += rhs.file_count;
2077        self.visible_file_count += rhs.visible_file_count;
2078    }
2079}
2080
2081#[derive(Clone, Debug)]
2082struct PathEntry {
2083    id: ProjectEntryId,
2084    path: Arc<Path>,
2085    is_ignored: bool,
2086    scan_id: usize,
2087}
2088
2089impl sum_tree::Item for PathEntry {
2090    type Summary = PathEntrySummary;
2091
2092    fn summary(&self) -> Self::Summary {
2093        PathEntrySummary { max_id: self.id }
2094    }
2095}
2096
2097impl sum_tree::KeyedItem for PathEntry {
2098    type Key = ProjectEntryId;
2099
2100    fn key(&self) -> Self::Key {
2101        self.id
2102    }
2103}
2104
2105#[derive(Clone, Debug, Default)]
2106struct PathEntrySummary {
2107    max_id: ProjectEntryId,
2108}
2109
2110impl sum_tree::Summary for PathEntrySummary {
2111    type Context = ();
2112
2113    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2114        self.max_id = summary.max_id;
2115    }
2116}
2117
2118impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2119    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2120        *self = summary.max_id;
2121    }
2122}
2123
2124#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2125pub struct PathKey(Arc<Path>);
2126
2127impl Default for PathKey {
2128    fn default() -> Self {
2129        Self(Path::new("").into())
2130    }
2131}
2132
2133impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2134    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2135        self.0 = summary.max_path.clone();
2136    }
2137}
2138
2139struct BackgroundScanner {
2140    fs: Arc<dyn Fs>,
2141    snapshot: Mutex<LocalSnapshot>,
2142    notify: UnboundedSender<ScanState>,
2143    executor: Arc<executor::Background>,
2144}
2145
2146impl BackgroundScanner {
2147    fn new(
2148        snapshot: LocalSnapshot,
2149        notify: UnboundedSender<ScanState>,
2150        fs: Arc<dyn Fs>,
2151        executor: Arc<executor::Background>,
2152    ) -> Self {
2153        Self {
2154            fs,
2155            snapshot: Mutex::new(snapshot),
2156            notify,
2157            executor,
2158        }
2159    }
2160
2161    fn abs_path(&self) -> Arc<Path> {
2162        self.snapshot.lock().abs_path.clone()
2163    }
2164
2165    async fn run(
2166        self,
2167        events_rx: impl Stream<Item = Vec<fsevent::Event>>,
2168        mut changed_paths: UnboundedReceiver<(Vec<PathBuf>, barrier::Sender)>,
2169    ) {
2170        use futures::FutureExt as _;
2171
2172        // Retrieve the basic properties of the root node.
2173        let root_char_bag;
2174        let root_abs_path;
2175        let root_inode;
2176        let root_is_dir;
2177        let next_entry_id;
2178        {
2179            let mut snapshot = self.snapshot.lock();
2180            snapshot.scan_started();
2181            root_char_bag = snapshot.root_char_bag;
2182            root_abs_path = snapshot.abs_path.clone();
2183            root_inode = snapshot.root_entry().map(|e| e.inode);
2184            root_is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir());
2185            next_entry_id = snapshot.next_entry_id.clone();
2186        }
2187
2188        // Populate ignores above the root.
2189        let ignore_stack;
2190        for ancestor in root_abs_path.ancestors().skip(1) {
2191            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2192            {
2193                self.snapshot
2194                    .lock()
2195                    .ignores_by_parent_abs_path
2196                    .insert(ancestor.into(), (ignore.into(), 0));
2197            }
2198        }
2199        {
2200            let mut snapshot = self.snapshot.lock();
2201            ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2202            if ignore_stack.is_all() {
2203                if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2204                    root_entry.is_ignored = true;
2205                    snapshot.insert_entry(root_entry, self.fs.as_ref());
2206                }
2207            }
2208        };
2209
2210        if root_is_dir {
2211            let mut ancestor_inodes = TreeSet::default();
2212            if let Some(root_inode) = root_inode {
2213                ancestor_inodes.insert(root_inode);
2214            }
2215
2216            let (tx, rx) = channel::unbounded();
2217            self.executor
2218                .block(tx.send(ScanJob {
2219                    abs_path: root_abs_path.to_path_buf(),
2220                    path: Arc::from(Path::new("")),
2221                    ignore_stack,
2222                    ancestor_inodes,
2223                    scan_queue: tx.clone(),
2224                }))
2225                .unwrap();
2226            drop(tx);
2227
2228            // Spawn a worker thread per logical CPU.
2229            self.executor
2230                .scoped(|scope| {
2231                    // One the first worker thread, listen for change requests from the worktree.
2232                    // For each change request, after refreshing the given paths, report
2233                    // a progress update for the snapshot.
2234                    scope.spawn(async {
2235                        let reporting_timer = self.delay().fuse();
2236                        futures::pin_mut!(reporting_timer);
2237
2238                        loop {
2239                            select_biased! {
2240                                job = changed_paths.next().fuse() => {
2241                                    let Some((abs_paths, barrier)) = job else { break };
2242                                    self.update_entries_for_paths(abs_paths, None).await;
2243                                    if self.notify.unbounded_send(ScanState::Initializing {
2244                                        snapshot: self.snapshot.lock().clone(),
2245                                        barrier: Some(barrier),
2246                                    }).is_err() {
2247                                        break;
2248                                    }
2249                                }
2250
2251                                _ = reporting_timer => {
2252                                    reporting_timer.set(self.delay().fuse());
2253                                    if self.notify.unbounded_send(ScanState::Initializing {
2254                                        snapshot: self.snapshot.lock().clone(),
2255                                        barrier: None,
2256                                    }).is_err() {
2257                                        break;
2258                                    }
2259                                }
2260
2261                                job = rx.recv().fuse() => {
2262                                    let Ok(job) = job else { break };
2263                                    if let Err(err) = self
2264                                        .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2265                                        .await
2266                                    {
2267                                        log::error!("error scanning {:?}: {}", job.abs_path, err);
2268                                    }
2269                                }
2270                            }
2271                        }
2272                    });
2273
2274                    // On all of the remaining worker threads, just scan directories.
2275                    for _ in 1..self.executor.num_cpus() {
2276                        scope.spawn(async {
2277                            while let Ok(job) = rx.recv().await {
2278                                if let Err(err) = self
2279                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2280                                    .await
2281                                {
2282                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2283                                }
2284                            }
2285                        });
2286                    }
2287                })
2288                .await;
2289        }
2290
2291        self.snapshot.lock().scan_completed();
2292
2293        if self
2294            .notify
2295            .unbounded_send(ScanState::Initialized {
2296                snapshot: self.snapshot.lock().clone(),
2297            })
2298            .is_err()
2299        {
2300            return;
2301        }
2302
2303        // Process any events that occurred while performing the initial scan. These
2304        // events can't be reported as precisely, because there is no snapshot of the
2305        // worktree before they occurred.
2306        futures::pin_mut!(events_rx);
2307        if let Poll::Ready(Some(mut events)) = futures::poll!(events_rx.next()) {
2308            while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2309                events.extend(additional_events);
2310            }
2311            let abs_paths = events.into_iter().map(|e| e.path).collect();
2312            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2313                return;
2314            }
2315            if let Some(changes) = self.process_events(abs_paths, true).await {
2316                if self
2317                    .notify
2318                    .unbounded_send(ScanState::Updated {
2319                        snapshot: self.snapshot.lock().clone(),
2320                        changes,
2321                        barrier: None,
2322                    })
2323                    .is_err()
2324                {
2325                    return;
2326                }
2327            } else {
2328                return;
2329            }
2330        }
2331
2332        // Continue processing events until the worktree is dropped.
2333        loop {
2334            let barrier;
2335            let abs_paths;
2336            select_biased! {
2337                request = changed_paths.next().fuse() => {
2338                    let Some((paths, b)) = request else { break };
2339                    abs_paths = paths;
2340                    barrier = Some(b);
2341                }
2342                events = events_rx.next().fuse() => {
2343                    let Some(events) = events else { break };
2344                    abs_paths = events.into_iter().map(|e| e.path).collect();
2345                    barrier = None;
2346                }
2347            }
2348
2349            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2350                return;
2351            }
2352            if let Some(changes) = self.process_events(abs_paths, false).await {
2353                if self
2354                    .notify
2355                    .unbounded_send(ScanState::Updated {
2356                        snapshot: self.snapshot.lock().clone(),
2357                        changes,
2358                        barrier,
2359                    })
2360                    .is_err()
2361                {
2362                    return;
2363                }
2364            } else {
2365                return;
2366            }
2367        }
2368    }
2369
2370    async fn delay(&self) {
2371        #[cfg(any(test, feature = "test-support"))]
2372        if self.fs.is_fake() {
2373            return self.executor.simulate_random_delay().await;
2374        }
2375        smol::Timer::after(Duration::from_millis(100)).await;
2376    }
2377
2378    async fn scan_dir(
2379        &self,
2380        root_char_bag: CharBag,
2381        next_entry_id: Arc<AtomicUsize>,
2382        job: &ScanJob,
2383    ) -> Result<()> {
2384        let mut new_entries: Vec<Entry> = Vec::new();
2385        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2386        let mut ignore_stack = job.ignore_stack.clone();
2387        let mut new_ignore = None;
2388
2389        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2390        while let Some(child_abs_path) = child_paths.next().await {
2391            let child_abs_path = match child_abs_path {
2392                Ok(child_abs_path) => child_abs_path,
2393                Err(error) => {
2394                    log::error!("error processing entry {:?}", error);
2395                    continue;
2396                }
2397            };
2398
2399            let child_name = child_abs_path.file_name().unwrap();
2400            let child_path: Arc<Path> = job.path.join(child_name).into();
2401            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2402                Ok(Some(metadata)) => metadata,
2403                Ok(None) => continue,
2404                Err(err) => {
2405                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2406                    continue;
2407                }
2408            };
2409
2410            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2411            if child_name == *GITIGNORE {
2412                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2413                    Ok(ignore) => {
2414                        let ignore = Arc::new(ignore);
2415                        ignore_stack =
2416                            ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2417                        new_ignore = Some(ignore);
2418                    }
2419                    Err(error) => {
2420                        log::error!(
2421                            "error loading .gitignore file {:?} - {:?}",
2422                            child_name,
2423                            error
2424                        );
2425                    }
2426                }
2427
2428                // Update ignore status of any child entries we've already processed to reflect the
2429                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2430                // there should rarely be too numerous. Update the ignore stack associated with any
2431                // new jobs as well.
2432                let mut new_jobs = new_jobs.iter_mut();
2433                for entry in &mut new_entries {
2434                    let entry_abs_path = self.abs_path().join(&entry.path);
2435                    entry.is_ignored =
2436                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2437
2438                    if entry.is_dir() {
2439                        if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
2440                            job.ignore_stack = if entry.is_ignored {
2441                                IgnoreStack::all()
2442                            } else {
2443                                ignore_stack.clone()
2444                            };
2445                        }
2446                    }
2447                }
2448            }
2449
2450            let mut child_entry = Entry::new(
2451                child_path.clone(),
2452                &child_metadata,
2453                &next_entry_id,
2454                root_char_bag,
2455            );
2456
2457            if child_entry.is_dir() {
2458                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2459                child_entry.is_ignored = is_ignored;
2460
2461                // Avoid recursing until crash in the case of a recursive symlink
2462                if !job.ancestor_inodes.contains(&child_entry.inode) {
2463                    let mut ancestor_inodes = job.ancestor_inodes.clone();
2464                    ancestor_inodes.insert(child_entry.inode);
2465
2466                    new_jobs.push(Some(ScanJob {
2467                        abs_path: child_abs_path,
2468                        path: child_path,
2469                        ignore_stack: if is_ignored {
2470                            IgnoreStack::all()
2471                        } else {
2472                            ignore_stack.clone()
2473                        },
2474                        ancestor_inodes,
2475                        scan_queue: job.scan_queue.clone(),
2476                    }));
2477                } else {
2478                    new_jobs.push(None);
2479                }
2480            } else {
2481                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2482            }
2483
2484            new_entries.push(child_entry);
2485        }
2486
2487        self.snapshot.lock().populate_dir(
2488            job.path.clone(),
2489            new_entries,
2490            new_ignore,
2491            self.fs.as_ref(),
2492        );
2493
2494        for new_job in new_jobs {
2495            if let Some(new_job) = new_job {
2496                job.scan_queue.send(new_job).await.unwrap();
2497            }
2498        }
2499
2500        Ok(())
2501    }
2502
2503    async fn process_events(
2504        &self,
2505        abs_paths: Vec<PathBuf>,
2506        received_before_initialized: bool,
2507    ) -> Option<HashMap<Arc<Path>, PathChange>> {
2508        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2509
2510        let prev_snapshot = {
2511            let mut snapshot = self.snapshot.lock();
2512            snapshot.scan_started();
2513            snapshot.clone()
2514        };
2515
2516        let event_paths = self
2517            .update_entries_for_paths(abs_paths, Some(scan_queue_tx))
2518            .await?;
2519
2520        // Scan any directories that were created as part of this event batch.
2521        self.executor
2522            .scoped(|scope| {
2523                for _ in 0..self.executor.num_cpus() {
2524                    scope.spawn(async {
2525                        while let Ok(job) = scan_queue_rx.recv().await {
2526                            if let Err(err) = self
2527                                .scan_dir(
2528                                    prev_snapshot.root_char_bag,
2529                                    prev_snapshot.next_entry_id.clone(),
2530                                    &job,
2531                                )
2532                                .await
2533                            {
2534                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2535                            }
2536                        }
2537                    });
2538                }
2539            })
2540            .await;
2541
2542        // Attempt to detect renames only over a single batch of file-system events.
2543        self.snapshot.lock().removed_entry_ids.clear();
2544
2545        self.update_ignore_statuses().await;
2546        self.update_git_repositories();
2547        let changes = self.build_change_set(
2548            prev_snapshot.snapshot,
2549            event_paths,
2550            received_before_initialized,
2551        );
2552        self.snapshot.lock().scan_completed();
2553        Some(changes)
2554    }
2555
2556    async fn update_entries_for_paths(
2557        &self,
2558        mut abs_paths: Vec<PathBuf>,
2559        scan_queue_tx: Option<Sender<ScanJob>>,
2560    ) -> Option<Vec<Arc<Path>>> {
2561        abs_paths.sort_unstable();
2562        abs_paths.dedup_by(|a, b| a.starts_with(&b));
2563
2564        let root_abs_path = self.snapshot.lock().abs_path.clone();
2565        let root_canonical_path = self.fs.canonicalize(&root_abs_path).await.ok()?;
2566        let metadata = futures::future::join_all(
2567            abs_paths
2568                .iter()
2569                .map(|abs_path| self.fs.metadata(&abs_path))
2570                .collect::<Vec<_>>(),
2571        )
2572        .await;
2573
2574        let mut snapshot = self.snapshot.lock();
2575        if scan_queue_tx.is_some() {
2576            for abs_path in &abs_paths {
2577                if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
2578                    snapshot.remove_path(path);
2579                }
2580            }
2581        }
2582
2583        let mut event_paths = Vec::with_capacity(abs_paths.len());
2584        for (abs_path, metadata) in abs_paths.into_iter().zip(metadata.into_iter()) {
2585            let path: Arc<Path> = match abs_path.strip_prefix(&root_canonical_path) {
2586                Ok(path) => Arc::from(path.to_path_buf()),
2587                Err(_) => {
2588                    log::error!(
2589                        "unexpected event {:?} for root path {:?}",
2590                        abs_path,
2591                        root_canonical_path
2592                    );
2593                    continue;
2594                }
2595            };
2596            event_paths.push(path.clone());
2597            let abs_path = root_abs_path.join(&path);
2598
2599            match metadata {
2600                Ok(Some(metadata)) => {
2601                    let ignore_stack =
2602                        snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2603                    let mut fs_entry = Entry::new(
2604                        path.clone(),
2605                        &metadata,
2606                        snapshot.next_entry_id.as_ref(),
2607                        snapshot.root_char_bag,
2608                    );
2609                    fs_entry.is_ignored = ignore_stack.is_all();
2610                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
2611
2612                    let scan_id = snapshot.scan_id;
2613                    if let Some(repo) = snapshot.repo_with_dot_git_containing(&path) {
2614                        repo.repo.lock().reload_index();
2615                        repo.scan_id = scan_id;
2616                    }
2617
2618                    if let Some(scan_queue_tx) = &scan_queue_tx {
2619                        let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2620                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2621                            ancestor_inodes.insert(metadata.inode);
2622                            self.executor
2623                                .block(scan_queue_tx.send(ScanJob {
2624                                    abs_path,
2625                                    path,
2626                                    ignore_stack,
2627                                    ancestor_inodes,
2628                                    scan_queue: scan_queue_tx.clone(),
2629                                }))
2630                                .unwrap();
2631                        }
2632                    }
2633                }
2634                Ok(None) => {}
2635                Err(err) => {
2636                    // TODO - create a special 'error' entry in the entries tree to mark this
2637                    log::error!("error reading file on event {:?}", err);
2638                }
2639            }
2640        }
2641
2642        Some(event_paths)
2643    }
2644
2645    async fn update_ignore_statuses(&self) {
2646        let mut snapshot = self.snapshot.lock().clone();
2647        let mut ignores_to_update = Vec::new();
2648        let mut ignores_to_delete = Vec::new();
2649        for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2650            if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2651                if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2652                    ignores_to_update.push(parent_abs_path.clone());
2653                }
2654
2655                let ignore_path = parent_path.join(&*GITIGNORE);
2656                if snapshot.entry_for_path(ignore_path).is_none() {
2657                    ignores_to_delete.push(parent_abs_path.clone());
2658                }
2659            }
2660        }
2661
2662        for parent_abs_path in ignores_to_delete {
2663            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2664            self.snapshot
2665                .lock()
2666                .ignores_by_parent_abs_path
2667                .remove(&parent_abs_path);
2668        }
2669
2670        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2671        ignores_to_update.sort_unstable();
2672        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2673        while let Some(parent_abs_path) = ignores_to_update.next() {
2674            while ignores_to_update
2675                .peek()
2676                .map_or(false, |p| p.starts_with(&parent_abs_path))
2677            {
2678                ignores_to_update.next().unwrap();
2679            }
2680
2681            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2682            ignore_queue_tx
2683                .send(UpdateIgnoreStatusJob {
2684                    abs_path: parent_abs_path,
2685                    ignore_stack,
2686                    ignore_queue: ignore_queue_tx.clone(),
2687                })
2688                .await
2689                .unwrap();
2690        }
2691        drop(ignore_queue_tx);
2692
2693        self.executor
2694            .scoped(|scope| {
2695                for _ in 0..self.executor.num_cpus() {
2696                    scope.spawn(async {
2697                        while let Ok(job) = ignore_queue_rx.recv().await {
2698                            self.update_ignore_status(job, &snapshot).await;
2699                        }
2700                    });
2701                }
2702            })
2703            .await;
2704    }
2705
2706    fn update_git_repositories(&self) {
2707        let mut snapshot = self.snapshot.lock();
2708        let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2709        git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2710        snapshot.git_repositories = git_repositories;
2711    }
2712
2713    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2714        let mut ignore_stack = job.ignore_stack;
2715        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2716            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2717        }
2718
2719        let mut entries_by_id_edits = Vec::new();
2720        let mut entries_by_path_edits = Vec::new();
2721        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2722        for mut entry in snapshot.child_entries(path).cloned() {
2723            let was_ignored = entry.is_ignored;
2724            let abs_path = self.abs_path().join(&entry.path);
2725            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2726            if entry.is_dir() {
2727                let child_ignore_stack = if entry.is_ignored {
2728                    IgnoreStack::all()
2729                } else {
2730                    ignore_stack.clone()
2731                };
2732                job.ignore_queue
2733                    .send(UpdateIgnoreStatusJob {
2734                        abs_path: abs_path.into(),
2735                        ignore_stack: child_ignore_stack,
2736                        ignore_queue: job.ignore_queue.clone(),
2737                    })
2738                    .await
2739                    .unwrap();
2740            }
2741
2742            if entry.is_ignored != was_ignored {
2743                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2744                path_entry.scan_id = snapshot.scan_id;
2745                path_entry.is_ignored = entry.is_ignored;
2746                entries_by_id_edits.push(Edit::Insert(path_entry));
2747                entries_by_path_edits.push(Edit::Insert(entry));
2748            }
2749        }
2750
2751        let mut snapshot = self.snapshot.lock();
2752        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2753        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2754    }
2755
2756    fn build_change_set(
2757        &self,
2758        old_snapshot: Snapshot,
2759        event_paths: Vec<Arc<Path>>,
2760        received_before_initialized: bool,
2761    ) -> HashMap<Arc<Path>, PathChange> {
2762        use PathChange::{Added, AddedOrUpdated, Removed, Updated};
2763
2764        let new_snapshot = self.snapshot.lock();
2765        let mut changes = HashMap::default();
2766        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
2767        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
2768
2769        for path in event_paths {
2770            let path = PathKey(path);
2771            old_paths.seek(&path, Bias::Left, &());
2772            new_paths.seek(&path, Bias::Left, &());
2773
2774            loop {
2775                match (old_paths.item(), new_paths.item()) {
2776                    (Some(old_entry), Some(new_entry)) => {
2777                        if old_entry.path > path.0
2778                            && new_entry.path > path.0
2779                            && !old_entry.path.starts_with(&path.0)
2780                            && !new_entry.path.starts_with(&path.0)
2781                        {
2782                            break;
2783                        }
2784
2785                        match Ord::cmp(&old_entry.path, &new_entry.path) {
2786                            Ordering::Less => {
2787                                changes.insert(old_entry.path.clone(), Removed);
2788                                old_paths.next(&());
2789                            }
2790                            Ordering::Equal => {
2791                                if received_before_initialized {
2792                                    // If the worktree was not fully initialized when this event was generated,
2793                                    // we can't know whether this entry was added during the scan or whether
2794                                    // it was merely updated.
2795                                    changes.insert(old_entry.path.clone(), AddedOrUpdated);
2796                                } else if old_entry.mtime != new_entry.mtime {
2797                                    changes.insert(old_entry.path.clone(), Updated);
2798                                }
2799                                old_paths.next(&());
2800                                new_paths.next(&());
2801                            }
2802                            Ordering::Greater => {
2803                                changes.insert(new_entry.path.clone(), Added);
2804                                new_paths.next(&());
2805                            }
2806                        }
2807                    }
2808                    (Some(old_entry), None) => {
2809                        changes.insert(old_entry.path.clone(), Removed);
2810                        old_paths.next(&());
2811                    }
2812                    (None, Some(new_entry)) => {
2813                        changes.insert(new_entry.path.clone(), Added);
2814                        new_paths.next(&());
2815                    }
2816                    (None, None) => break,
2817                }
2818            }
2819        }
2820        changes
2821    }
2822}
2823
2824fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2825    let mut result = root_char_bag;
2826    result.extend(
2827        path.to_string_lossy()
2828            .chars()
2829            .map(|c| c.to_ascii_lowercase()),
2830    );
2831    result
2832}
2833
2834struct ScanJob {
2835    abs_path: PathBuf,
2836    path: Arc<Path>,
2837    ignore_stack: Arc<IgnoreStack>,
2838    scan_queue: Sender<ScanJob>,
2839    ancestor_inodes: TreeSet<u64>,
2840}
2841
2842struct UpdateIgnoreStatusJob {
2843    abs_path: Arc<Path>,
2844    ignore_stack: Arc<IgnoreStack>,
2845    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2846}
2847
2848pub trait WorktreeHandle {
2849    #[cfg(any(test, feature = "test-support"))]
2850    fn flush_fs_events<'a>(
2851        &self,
2852        cx: &'a gpui::TestAppContext,
2853    ) -> futures::future::LocalBoxFuture<'a, ()>;
2854}
2855
2856impl WorktreeHandle for ModelHandle<Worktree> {
2857    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2858    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2859    // extra directory scans, and emit extra scan-state notifications.
2860    //
2861    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2862    // to ensure that all redundant FS events have already been processed.
2863    #[cfg(any(test, feature = "test-support"))]
2864    fn flush_fs_events<'a>(
2865        &self,
2866        cx: &'a gpui::TestAppContext,
2867    ) -> futures::future::LocalBoxFuture<'a, ()> {
2868        use smol::future::FutureExt;
2869
2870        let filename = "fs-event-sentinel";
2871        let tree = self.clone();
2872        let (fs, root_path) = self.read_with(cx, |tree, _| {
2873            let tree = tree.as_local().unwrap();
2874            (tree.fs.clone(), tree.abs_path().clone())
2875        });
2876
2877        async move {
2878            fs.create_file(&root_path.join(filename), Default::default())
2879                .await
2880                .unwrap();
2881            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2882                .await;
2883
2884            fs.remove_file(&root_path.join(filename), Default::default())
2885                .await
2886                .unwrap();
2887            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2888                .await;
2889
2890            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2891                .await;
2892        }
2893        .boxed_local()
2894    }
2895}
2896
2897#[derive(Clone, Debug)]
2898struct TraversalProgress<'a> {
2899    max_path: &'a Path,
2900    count: usize,
2901    visible_count: usize,
2902    file_count: usize,
2903    visible_file_count: usize,
2904}
2905
2906impl<'a> TraversalProgress<'a> {
2907    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2908        match (include_ignored, include_dirs) {
2909            (true, true) => self.count,
2910            (true, false) => self.file_count,
2911            (false, true) => self.visible_count,
2912            (false, false) => self.visible_file_count,
2913        }
2914    }
2915}
2916
2917impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2918    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2919        self.max_path = summary.max_path.as_ref();
2920        self.count += summary.count;
2921        self.visible_count += summary.visible_count;
2922        self.file_count += summary.file_count;
2923        self.visible_file_count += summary.visible_file_count;
2924    }
2925}
2926
2927impl<'a> Default for TraversalProgress<'a> {
2928    fn default() -> Self {
2929        Self {
2930            max_path: Path::new(""),
2931            count: 0,
2932            visible_count: 0,
2933            file_count: 0,
2934            visible_file_count: 0,
2935        }
2936    }
2937}
2938
2939pub struct Traversal<'a> {
2940    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2941    include_ignored: bool,
2942    include_dirs: bool,
2943}
2944
2945impl<'a> Traversal<'a> {
2946    pub fn advance(&mut self) -> bool {
2947        self.advance_to_offset(self.offset() + 1)
2948    }
2949
2950    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2951        self.cursor.seek_forward(
2952            &TraversalTarget::Count {
2953                count: offset,
2954                include_dirs: self.include_dirs,
2955                include_ignored: self.include_ignored,
2956            },
2957            Bias::Right,
2958            &(),
2959        )
2960    }
2961
2962    pub fn advance_to_sibling(&mut self) -> bool {
2963        while let Some(entry) = self.cursor.item() {
2964            self.cursor.seek_forward(
2965                &TraversalTarget::PathSuccessor(&entry.path),
2966                Bias::Left,
2967                &(),
2968            );
2969            if let Some(entry) = self.cursor.item() {
2970                if (self.include_dirs || !entry.is_dir())
2971                    && (self.include_ignored || !entry.is_ignored)
2972                {
2973                    return true;
2974                }
2975            }
2976        }
2977        false
2978    }
2979
2980    pub fn entry(&self) -> Option<&'a Entry> {
2981        self.cursor.item()
2982    }
2983
2984    pub fn offset(&self) -> usize {
2985        self.cursor
2986            .start()
2987            .count(self.include_dirs, self.include_ignored)
2988    }
2989}
2990
2991impl<'a> Iterator for Traversal<'a> {
2992    type Item = &'a Entry;
2993
2994    fn next(&mut self) -> Option<Self::Item> {
2995        if let Some(item) = self.entry() {
2996            self.advance();
2997            Some(item)
2998        } else {
2999            None
3000        }
3001    }
3002}
3003
3004#[derive(Debug)]
3005enum TraversalTarget<'a> {
3006    Path(&'a Path),
3007    PathSuccessor(&'a Path),
3008    Count {
3009        count: usize,
3010        include_ignored: bool,
3011        include_dirs: bool,
3012    },
3013}
3014
3015impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3016    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3017        match self {
3018            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3019            TraversalTarget::PathSuccessor(path) => {
3020                if !cursor_location.max_path.starts_with(path) {
3021                    Ordering::Equal
3022                } else {
3023                    Ordering::Greater
3024                }
3025            }
3026            TraversalTarget::Count {
3027                count,
3028                include_dirs,
3029                include_ignored,
3030            } => Ord::cmp(
3031                count,
3032                &cursor_location.count(*include_dirs, *include_ignored),
3033            ),
3034        }
3035    }
3036}
3037
3038struct ChildEntriesIter<'a> {
3039    parent_path: &'a Path,
3040    traversal: Traversal<'a>,
3041}
3042
3043impl<'a> Iterator for ChildEntriesIter<'a> {
3044    type Item = &'a Entry;
3045
3046    fn next(&mut self) -> Option<Self::Item> {
3047        if let Some(item) = self.traversal.entry() {
3048            if item.path.starts_with(&self.parent_path) {
3049                self.traversal.advance_to_sibling();
3050                return Some(item);
3051            }
3052        }
3053        None
3054    }
3055}
3056
3057impl<'a> From<&'a Entry> for proto::Entry {
3058    fn from(entry: &'a Entry) -> Self {
3059        Self {
3060            id: entry.id.to_proto(),
3061            is_dir: entry.is_dir(),
3062            path: entry.path.to_string_lossy().into(),
3063            inode: entry.inode,
3064            mtime: Some(entry.mtime.into()),
3065            is_symlink: entry.is_symlink,
3066            is_ignored: entry.is_ignored,
3067        }
3068    }
3069}
3070
3071impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3072    type Error = anyhow::Error;
3073
3074    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3075        if let Some(mtime) = entry.mtime {
3076            let kind = if entry.is_dir {
3077                EntryKind::Dir
3078            } else {
3079                let mut char_bag = *root_char_bag;
3080                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3081                EntryKind::File(char_bag)
3082            };
3083            let path: Arc<Path> = PathBuf::from(entry.path).into();
3084            Ok(Entry {
3085                id: ProjectEntryId::from_proto(entry.id),
3086                kind,
3087                path,
3088                inode: entry.inode,
3089                mtime: mtime.into(),
3090                is_symlink: entry.is_symlink,
3091                is_ignored: entry.is_ignored,
3092            })
3093        } else {
3094            Err(anyhow!(
3095                "missing mtime in remote worktree entry {:?}",
3096                entry.path
3097            ))
3098        }
3099    }
3100}
3101
3102#[cfg(test)]
3103mod tests {
3104    use super::*;
3105    use client::test::FakeHttpClient;
3106    use fs::repository::FakeGitRepository;
3107    use fs::{FakeFs, RealFs};
3108    use gpui::{executor::Deterministic, TestAppContext};
3109    use rand::prelude::*;
3110    use serde_json::json;
3111    use std::{env, fmt::Write};
3112    use util::test::temp_tree;
3113
3114    #[gpui::test]
3115    async fn test_traversal(cx: &mut TestAppContext) {
3116        let fs = FakeFs::new(cx.background());
3117        fs.insert_tree(
3118            "/root",
3119            json!({
3120               ".gitignore": "a/b\n",
3121               "a": {
3122                   "b": "",
3123                   "c": "",
3124               }
3125            }),
3126        )
3127        .await;
3128
3129        let http_client = FakeHttpClient::with_404_response();
3130        let client = cx.read(|cx| Client::new(http_client, cx));
3131
3132        let tree = Worktree::local(
3133            client,
3134            Path::new("/root"),
3135            true,
3136            fs,
3137            Default::default(),
3138            &mut cx.to_async(),
3139        )
3140        .await
3141        .unwrap();
3142        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3143            .await;
3144
3145        tree.read_with(cx, |tree, _| {
3146            assert_eq!(
3147                tree.entries(false)
3148                    .map(|entry| entry.path.as_ref())
3149                    .collect::<Vec<_>>(),
3150                vec![
3151                    Path::new(""),
3152                    Path::new(".gitignore"),
3153                    Path::new("a"),
3154                    Path::new("a/c"),
3155                ]
3156            );
3157            assert_eq!(
3158                tree.entries(true)
3159                    .map(|entry| entry.path.as_ref())
3160                    .collect::<Vec<_>>(),
3161                vec![
3162                    Path::new(""),
3163                    Path::new(".gitignore"),
3164                    Path::new("a"),
3165                    Path::new("a/b"),
3166                    Path::new("a/c"),
3167                ]
3168            );
3169        })
3170    }
3171
3172    #[gpui::test(iterations = 10)]
3173    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3174        let fs = FakeFs::new(cx.background());
3175        fs.insert_tree(
3176            "/root",
3177            json!({
3178                "lib": {
3179                    "a": {
3180                        "a.txt": ""
3181                    },
3182                    "b": {
3183                        "b.txt": ""
3184                    }
3185                }
3186            }),
3187        )
3188        .await;
3189        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3190        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3191
3192        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3193        let tree = Worktree::local(
3194            client,
3195            Path::new("/root"),
3196            true,
3197            fs.clone(),
3198            Default::default(),
3199            &mut cx.to_async(),
3200        )
3201        .await
3202        .unwrap();
3203
3204        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3205            .await;
3206
3207        tree.read_with(cx, |tree, _| {
3208            assert_eq!(
3209                tree.entries(false)
3210                    .map(|entry| entry.path.as_ref())
3211                    .collect::<Vec<_>>(),
3212                vec![
3213                    Path::new(""),
3214                    Path::new("lib"),
3215                    Path::new("lib/a"),
3216                    Path::new("lib/a/a.txt"),
3217                    Path::new("lib/a/lib"),
3218                    Path::new("lib/b"),
3219                    Path::new("lib/b/b.txt"),
3220                    Path::new("lib/b/lib"),
3221                ]
3222            );
3223        });
3224
3225        fs.rename(
3226            Path::new("/root/lib/a/lib"),
3227            Path::new("/root/lib/a/lib-2"),
3228            Default::default(),
3229        )
3230        .await
3231        .unwrap();
3232        executor.run_until_parked();
3233        tree.read_with(cx, |tree, _| {
3234            assert_eq!(
3235                tree.entries(false)
3236                    .map(|entry| entry.path.as_ref())
3237                    .collect::<Vec<_>>(),
3238                vec![
3239                    Path::new(""),
3240                    Path::new("lib"),
3241                    Path::new("lib/a"),
3242                    Path::new("lib/a/a.txt"),
3243                    Path::new("lib/a/lib-2"),
3244                    Path::new("lib/b"),
3245                    Path::new("lib/b/b.txt"),
3246                    Path::new("lib/b/lib"),
3247                ]
3248            );
3249        });
3250    }
3251
3252    #[gpui::test]
3253    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3254        let parent_dir = temp_tree(json!({
3255            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3256            "tree": {
3257                ".git": {},
3258                ".gitignore": "ignored-dir\n",
3259                "tracked-dir": {
3260                    "tracked-file1": "",
3261                    "ancestor-ignored-file1": "",
3262                },
3263                "ignored-dir": {
3264                    "ignored-file1": ""
3265                }
3266            }
3267        }));
3268        let dir = parent_dir.path().join("tree");
3269
3270        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3271
3272        let tree = Worktree::local(
3273            client,
3274            dir.as_path(),
3275            true,
3276            Arc::new(RealFs),
3277            Default::default(),
3278            &mut cx.to_async(),
3279        )
3280        .await
3281        .unwrap();
3282        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3283            .await;
3284        tree.flush_fs_events(cx).await;
3285        cx.read(|cx| {
3286            let tree = tree.read(cx);
3287            assert!(
3288                !tree
3289                    .entry_for_path("tracked-dir/tracked-file1")
3290                    .unwrap()
3291                    .is_ignored
3292            );
3293            assert!(
3294                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3295                    .unwrap()
3296                    .is_ignored
3297            );
3298            assert!(
3299                tree.entry_for_path("ignored-dir/ignored-file1")
3300                    .unwrap()
3301                    .is_ignored
3302            );
3303        });
3304
3305        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3306        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3307        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3308        tree.flush_fs_events(cx).await;
3309        cx.read(|cx| {
3310            let tree = tree.read(cx);
3311            assert!(
3312                !tree
3313                    .entry_for_path("tracked-dir/tracked-file2")
3314                    .unwrap()
3315                    .is_ignored
3316            );
3317            assert!(
3318                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3319                    .unwrap()
3320                    .is_ignored
3321            );
3322            assert!(
3323                tree.entry_for_path("ignored-dir/ignored-file2")
3324                    .unwrap()
3325                    .is_ignored
3326            );
3327            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3328        });
3329    }
3330
3331    #[gpui::test]
3332    async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3333        let root = temp_tree(json!({
3334            "dir1": {
3335                ".git": {},
3336                "deps": {
3337                    "dep1": {
3338                        ".git": {},
3339                        "src": {
3340                            "a.txt": ""
3341                        }
3342                    }
3343                },
3344                "src": {
3345                    "b.txt": ""
3346                }
3347            },
3348            "c.txt": "",
3349        }));
3350
3351        let http_client = FakeHttpClient::with_404_response();
3352        let client = cx.read(|cx| Client::new(http_client, cx));
3353        let tree = Worktree::local(
3354            client,
3355            root.path(),
3356            true,
3357            Arc::new(RealFs),
3358            Default::default(),
3359            &mut cx.to_async(),
3360        )
3361        .await
3362        .unwrap();
3363
3364        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3365            .await;
3366        tree.flush_fs_events(cx).await;
3367
3368        tree.read_with(cx, |tree, _cx| {
3369            let tree = tree.as_local().unwrap();
3370
3371            assert!(tree.repo_for("c.txt".as_ref()).is_none());
3372
3373            let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3374            assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3375            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3376
3377            let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3378            assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3379            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3380        });
3381
3382        let original_scan_id = tree.read_with(cx, |tree, _cx| {
3383            let tree = tree.as_local().unwrap();
3384            tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3385        });
3386
3387        std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3388        tree.flush_fs_events(cx).await;
3389
3390        tree.read_with(cx, |tree, _cx| {
3391            let tree = tree.as_local().unwrap();
3392            let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3393            assert_ne!(
3394                original_scan_id, new_scan_id,
3395                "original {original_scan_id}, new {new_scan_id}"
3396            );
3397        });
3398
3399        std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3400        tree.flush_fs_events(cx).await;
3401
3402        tree.read_with(cx, |tree, _cx| {
3403            let tree = tree.as_local().unwrap();
3404
3405            assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3406        });
3407    }
3408
3409    #[test]
3410    fn test_changed_repos() {
3411        fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3412            GitRepositoryEntry {
3413                repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3414                scan_id,
3415                content_path: git_dir_path.as_ref().parent().unwrap().into(),
3416                git_dir_path: git_dir_path.as_ref().into(),
3417            }
3418        }
3419
3420        let prev_repos: Vec<GitRepositoryEntry> = vec![
3421            fake_entry("/.git", 0),
3422            fake_entry("/a/.git", 0),
3423            fake_entry("/a/b/.git", 0),
3424        ];
3425
3426        let new_repos: Vec<GitRepositoryEntry> = vec![
3427            fake_entry("/a/.git", 1),
3428            fake_entry("/a/b/.git", 0),
3429            fake_entry("/a/c/.git", 0),
3430        ];
3431
3432        let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3433
3434        // Deletion retained
3435        assert!(res
3436            .iter()
3437            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3438            .is_some());
3439
3440        // Update retained
3441        assert!(res
3442            .iter()
3443            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3444            .is_some());
3445
3446        // Addition retained
3447        assert!(res
3448            .iter()
3449            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3450            .is_some());
3451
3452        // Nochange, not retained
3453        assert!(res
3454            .iter()
3455            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3456            .is_none());
3457    }
3458
3459    #[gpui::test]
3460    async fn test_write_file(cx: &mut TestAppContext) {
3461        let dir = temp_tree(json!({
3462            ".git": {},
3463            ".gitignore": "ignored-dir\n",
3464            "tracked-dir": {},
3465            "ignored-dir": {}
3466        }));
3467
3468        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3469
3470        let tree = Worktree::local(
3471            client,
3472            dir.path(),
3473            true,
3474            Arc::new(RealFs),
3475            Default::default(),
3476            &mut cx.to_async(),
3477        )
3478        .await
3479        .unwrap();
3480        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3481            .await;
3482        tree.flush_fs_events(cx).await;
3483
3484        tree.update(cx, |tree, cx| {
3485            tree.as_local().unwrap().write_file(
3486                Path::new("tracked-dir/file.txt"),
3487                "hello".into(),
3488                Default::default(),
3489                cx,
3490            )
3491        })
3492        .await
3493        .unwrap();
3494        tree.update(cx, |tree, cx| {
3495            tree.as_local().unwrap().write_file(
3496                Path::new("ignored-dir/file.txt"),
3497                "world".into(),
3498                Default::default(),
3499                cx,
3500            )
3501        })
3502        .await
3503        .unwrap();
3504
3505        tree.read_with(cx, |tree, _| {
3506            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3507            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3508            assert!(!tracked.is_ignored);
3509            assert!(ignored.is_ignored);
3510        });
3511    }
3512
3513    #[gpui::test(iterations = 30)]
3514    async fn test_create_directory(cx: &mut TestAppContext) {
3515        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3516
3517        let fs = FakeFs::new(cx.background());
3518        fs.insert_tree(
3519            "/a",
3520            json!({
3521                "b": {},
3522                "c": {},
3523                "d": {},
3524            }),
3525        )
3526        .await;
3527
3528        let tree = Worktree::local(
3529            client,
3530            "/a".as_ref(),
3531            true,
3532            fs,
3533            Default::default(),
3534            &mut cx.to_async(),
3535        )
3536        .await
3537        .unwrap();
3538
3539        let entry = tree
3540            .update(cx, |tree, cx| {
3541                tree.as_local_mut()
3542                    .unwrap()
3543                    .create_entry("a/e".as_ref(), true, cx)
3544            })
3545            .await
3546            .unwrap();
3547        assert!(entry.is_dir());
3548
3549        cx.foreground().run_until_parked();
3550        tree.read_with(cx, |tree, _| {
3551            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3552        });
3553    }
3554
3555    #[gpui::test(iterations = 100)]
3556    async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
3557        let operations = env::var("OPERATIONS")
3558            .map(|o| o.parse().unwrap())
3559            .unwrap_or(40);
3560        let initial_entries = env::var("INITIAL_ENTRIES")
3561            .map(|o| o.parse().unwrap())
3562            .unwrap_or(20);
3563
3564        let root_dir = Path::new("/test");
3565        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
3566        fs.as_fake().insert_tree(root_dir, json!({})).await;
3567        for _ in 0..initial_entries {
3568            randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3569        }
3570        log::info!("generated initial tree");
3571
3572        let next_entry_id = Arc::new(AtomicUsize::default());
3573        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3574        let worktree = Worktree::local(
3575            client.clone(),
3576            root_dir,
3577            true,
3578            fs.clone(),
3579            next_entry_id.clone(),
3580            &mut cx.to_async(),
3581        )
3582        .await
3583        .unwrap();
3584
3585        worktree
3586            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3587            .await;
3588
3589        // After the initial scan is complete, the `UpdatedEntries` event can
3590        // be used to follow along with all changes to the worktree's snapshot.
3591        worktree.update(cx, |tree, cx| {
3592            let mut paths = tree
3593                .as_local()
3594                .unwrap()
3595                .paths()
3596                .cloned()
3597                .collect::<Vec<_>>();
3598
3599            cx.subscribe(&worktree, move |tree, _, event, _| {
3600                if let Event::UpdatedEntries(changes) = event {
3601                    for (path, change_type) in changes.iter() {
3602                        let path = path.clone();
3603                        let ix = match paths.binary_search(&path) {
3604                            Ok(ix) | Err(ix) => ix,
3605                        };
3606                        match change_type {
3607                            PathChange::Added => {
3608                                assert_ne!(paths.get(ix), Some(&path));
3609                                paths.insert(ix, path);
3610                            }
3611                            PathChange::Removed => {
3612                                assert_eq!(paths.get(ix), Some(&path));
3613                                paths.remove(ix);
3614                            }
3615                            PathChange::Updated => {
3616                                assert_eq!(paths.get(ix), Some(&path));
3617                            }
3618                            PathChange::AddedOrUpdated => {
3619                                if paths[ix] != path {
3620                                    paths.insert(ix, path);
3621                                }
3622                            }
3623                        }
3624                    }
3625                    let new_paths = tree.paths().cloned().collect::<Vec<_>>();
3626                    assert_eq!(paths, new_paths, "incorrect changes: {:?}", changes);
3627                }
3628            })
3629            .detach();
3630        });
3631
3632        let mut snapshots = Vec::new();
3633        let mut mutations_len = operations;
3634        while mutations_len > 1 {
3635            randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3636            let buffered_event_count = fs.as_fake().buffered_event_count().await;
3637            if buffered_event_count > 0 && rng.gen_bool(0.3) {
3638                let len = rng.gen_range(0..=buffered_event_count);
3639                log::info!("flushing {} events", len);
3640                fs.as_fake().flush_events(len).await;
3641            } else {
3642                randomly_mutate_tree(&fs, root_dir, 0.6, &mut rng).await;
3643                mutations_len -= 1;
3644            }
3645
3646            cx.foreground().run_until_parked();
3647            if rng.gen_bool(0.2) {
3648                log::info!("storing snapshot {}", snapshots.len());
3649                let snapshot =
3650                    worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3651                snapshots.push(snapshot);
3652            }
3653        }
3654
3655        log::info!("quiescing");
3656        fs.as_fake().flush_events(usize::MAX).await;
3657        cx.foreground().run_until_parked();
3658        let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3659        snapshot.check_invariants();
3660
3661        {
3662            let new_worktree = Worktree::local(
3663                client.clone(),
3664                root_dir,
3665                true,
3666                fs.clone(),
3667                next_entry_id,
3668                &mut cx.to_async(),
3669            )
3670            .await
3671            .unwrap();
3672            new_worktree
3673                .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3674                .await;
3675            let new_snapshot =
3676                new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3677            assert_eq!(snapshot.to_vec(true), new_snapshot.to_vec(true));
3678        }
3679
3680        for (i, mut prev_snapshot) in snapshots.into_iter().enumerate() {
3681            let include_ignored = rng.gen::<bool>();
3682            if !include_ignored {
3683                let mut entries_by_path_edits = Vec::new();
3684                let mut entries_by_id_edits = Vec::new();
3685                for entry in prev_snapshot
3686                    .entries_by_id
3687                    .cursor::<()>()
3688                    .filter(|e| e.is_ignored)
3689                {
3690                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3691                    entries_by_id_edits.push(Edit::Remove(entry.id));
3692                }
3693
3694                prev_snapshot
3695                    .entries_by_path
3696                    .edit(entries_by_path_edits, &());
3697                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3698            }
3699
3700            let update = snapshot.build_update(&prev_snapshot, 0, 0, include_ignored);
3701            prev_snapshot.apply_remote_update(update.clone()).unwrap();
3702            assert_eq!(
3703                prev_snapshot.to_vec(include_ignored),
3704                snapshot.to_vec(include_ignored),
3705                "wrong update for snapshot {i}. update: {:?}",
3706                update
3707            );
3708        }
3709    }
3710
3711    async fn randomly_mutate_tree(
3712        fs: &Arc<dyn Fs>,
3713        root_path: &Path,
3714        insertion_probability: f64,
3715        rng: &mut impl Rng,
3716    ) {
3717        let mut files = Vec::new();
3718        let mut dirs = Vec::new();
3719        for path in fs.as_fake().paths().await {
3720            if path.starts_with(root_path) {
3721                if fs.is_file(&path).await {
3722                    files.push(path);
3723                } else {
3724                    dirs.push(path);
3725                }
3726            }
3727        }
3728
3729        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3730            let path = dirs.choose(rng).unwrap();
3731            let new_path = path.join(gen_name(rng));
3732
3733            if rng.gen() {
3734                log::info!(
3735                    "creating dir {:?}",
3736                    new_path.strip_prefix(root_path).unwrap()
3737                );
3738                fs.create_dir(&new_path).await.unwrap();
3739            } else {
3740                log::info!(
3741                    "creating file {:?}",
3742                    new_path.strip_prefix(root_path).unwrap()
3743                );
3744                fs.create_file(&new_path, Default::default()).await.unwrap();
3745            }
3746        } else if rng.gen_bool(0.05) {
3747            let ignore_dir_path = dirs.choose(rng).unwrap();
3748            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3749
3750            let subdirs = dirs
3751                .iter()
3752                .filter(|d| d.starts_with(&ignore_dir_path))
3753                .cloned()
3754                .collect::<Vec<_>>();
3755            let subfiles = files
3756                .iter()
3757                .filter(|d| d.starts_with(&ignore_dir_path))
3758                .cloned()
3759                .collect::<Vec<_>>();
3760            let files_to_ignore = {
3761                let len = rng.gen_range(0..=subfiles.len());
3762                subfiles.choose_multiple(rng, len)
3763            };
3764            let dirs_to_ignore = {
3765                let len = rng.gen_range(0..subdirs.len());
3766                subdirs.choose_multiple(rng, len)
3767            };
3768
3769            let mut ignore_contents = String::new();
3770            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3771                writeln!(
3772                    ignore_contents,
3773                    "{}",
3774                    path_to_ignore
3775                        .strip_prefix(&ignore_dir_path)
3776                        .unwrap()
3777                        .to_str()
3778                        .unwrap()
3779                )
3780                .unwrap();
3781            }
3782            log::info!(
3783                "creating gitignore {:?} with contents:\n{}",
3784                ignore_path.strip_prefix(&root_path).unwrap(),
3785                ignore_contents
3786            );
3787            fs.save(
3788                &ignore_path,
3789                &ignore_contents.as_str().into(),
3790                Default::default(),
3791            )
3792            .await
3793            .unwrap();
3794        } else {
3795            let old_path = {
3796                let file_path = files.choose(rng);
3797                let dir_path = dirs[1..].choose(rng);
3798                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3799            };
3800
3801            let is_rename = rng.gen();
3802            if is_rename {
3803                let new_path_parent = dirs
3804                    .iter()
3805                    .filter(|d| !d.starts_with(old_path))
3806                    .choose(rng)
3807                    .unwrap();
3808
3809                let overwrite_existing_dir =
3810                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3811                let new_path = if overwrite_existing_dir {
3812                    fs.remove_dir(
3813                        &new_path_parent,
3814                        RemoveOptions {
3815                            recursive: true,
3816                            ignore_if_not_exists: true,
3817                        },
3818                    )
3819                    .await
3820                    .unwrap();
3821                    new_path_parent.to_path_buf()
3822                } else {
3823                    new_path_parent.join(gen_name(rng))
3824                };
3825
3826                log::info!(
3827                    "renaming {:?} to {}{:?}",
3828                    old_path.strip_prefix(&root_path).unwrap(),
3829                    if overwrite_existing_dir {
3830                        "overwrite "
3831                    } else {
3832                        ""
3833                    },
3834                    new_path.strip_prefix(&root_path).unwrap()
3835                );
3836                fs.rename(
3837                    &old_path,
3838                    &new_path,
3839                    fs::RenameOptions {
3840                        overwrite: true,
3841                        ignore_if_exists: true,
3842                    },
3843                )
3844                .await
3845                .unwrap();
3846            } else if fs.is_file(&old_path).await {
3847                log::info!(
3848                    "deleting file {:?}",
3849                    old_path.strip_prefix(&root_path).unwrap()
3850                );
3851                fs.remove_file(old_path, Default::default()).await.unwrap();
3852            } else {
3853                log::info!(
3854                    "deleting dir {:?}",
3855                    old_path.strip_prefix(&root_path).unwrap()
3856                );
3857                fs.remove_dir(
3858                    &old_path,
3859                    RemoveOptions {
3860                        recursive: true,
3861                        ignore_if_not_exists: true,
3862                    },
3863                )
3864                .await
3865                .unwrap();
3866            }
3867        }
3868    }
3869
3870    fn gen_name(rng: &mut impl Rng) -> String {
3871        (0..6)
3872            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3873            .map(char::from)
3874            .collect()
3875    }
3876
3877    impl LocalSnapshot {
3878        fn check_invariants(&self) {
3879            let mut files = self.files(true, 0);
3880            let mut visible_files = self.files(false, 0);
3881            for entry in self.entries_by_path.cursor::<()>() {
3882                if entry.is_file() {
3883                    assert_eq!(files.next().unwrap().inode, entry.inode);
3884                    if !entry.is_ignored {
3885                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3886                    }
3887                }
3888            }
3889            assert!(files.next().is_none());
3890            assert!(visible_files.next().is_none());
3891
3892            let mut bfs_paths = Vec::new();
3893            let mut stack = vec![Path::new("")];
3894            while let Some(path) = stack.pop() {
3895                bfs_paths.push(path);
3896                let ix = stack.len();
3897                for child_entry in self.child_entries(path) {
3898                    stack.insert(ix, &child_entry.path);
3899                }
3900            }
3901
3902            let dfs_paths_via_iter = self
3903                .entries_by_path
3904                .cursor::<()>()
3905                .map(|e| e.path.as_ref())
3906                .collect::<Vec<_>>();
3907            assert_eq!(bfs_paths, dfs_paths_via_iter);
3908
3909            let dfs_paths_via_traversal = self
3910                .entries(true)
3911                .map(|e| e.path.as_ref())
3912                .collect::<Vec<_>>();
3913            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3914
3915            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3916                let ignore_parent_path =
3917                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3918                assert!(self.entry_for_path(&ignore_parent_path).is_some());
3919                assert!(self
3920                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3921                    .is_some());
3922            }
3923        }
3924
3925        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3926            let mut paths = Vec::new();
3927            for entry in self.entries_by_path.cursor::<()>() {
3928                if include_ignored || !entry.is_ignored {
3929                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3930                }
3931            }
3932            paths.sort_by(|a, b| a.0.cmp(b.0));
3933            paths
3934        }
3935    }
3936}