worktree.rs

   1use crate::{
   2    copy_recursive, ignore::IgnoreStack, DiagnosticSummary, ProjectEntryId, RemoveOptions,
   3};
   4use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   5use anyhow::{anyhow, Context, Result};
   6use client::{proto, Client};
   7use clock::ReplicaId;
   8use collections::{HashMap, VecDeque};
   9use fs::{repository::GitRepository, Fs, LineEnding};
  10use futures::{
  11    channel::{
  12        mpsc::{self, UnboundedSender},
  13        oneshot,
  14    },
  15    select_biased, Stream, StreamExt,
  16};
  17use fuzzy::CharBag;
  18use git::{DOT_GIT, GITIGNORE};
  19use gpui::{executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task};
  20use language::{
  21    proto::{
  22        deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
  23        serialize_version,
  24    },
  25    Buffer, DiagnosticEntry, File as _, PointUtf16, Rope, RopeFingerprint, Unclipped,
  26};
  27use parking_lot::Mutex;
  28use postage::{
  29    barrier,
  30    prelude::{Sink as _, Stream as _},
  31    watch,
  32};
  33use smol::channel::{self, Sender};
  34use std::{
  35    any::Any,
  36    cmp::{self, Ordering},
  37    convert::TryFrom,
  38    ffi::OsStr,
  39    fmt,
  40    future::Future,
  41    mem,
  42    ops::{Deref, DerefMut},
  43    path::{Path, PathBuf},
  44    sync::{
  45        atomic::{AtomicUsize, Ordering::SeqCst},
  46        Arc,
  47    },
  48    task::Poll,
  49    time::{Duration, SystemTime},
  50};
  51use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  52use util::{paths::HOME, ResultExt, TryFutureExt};
  53
  54#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  55pub struct WorktreeId(usize);
  56
  57pub enum Worktree {
  58    Local(LocalWorktree),
  59    Remote(RemoteWorktree),
  60}
  61
  62pub struct LocalWorktree {
  63    snapshot: LocalSnapshot,
  64    path_changes_tx: channel::Sender<(Vec<PathBuf>, barrier::Sender)>,
  65    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
  66    _background_scanner_task: Task<()>,
  67    share: Option<ShareState>,
  68    diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<Unclipped<PointUtf16>>>>,
  69    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  70    client: Arc<Client>,
  71    fs: Arc<dyn Fs>,
  72    visible: bool,
  73}
  74
  75pub struct RemoteWorktree {
  76    snapshot: Snapshot,
  77    background_snapshot: Arc<Mutex<Snapshot>>,
  78    project_id: u64,
  79    client: Arc<Client>,
  80    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
  81    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
  82    replica_id: ReplicaId,
  83    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  84    visible: bool,
  85    disconnected: bool,
  86}
  87
  88#[derive(Clone)]
  89pub struct Snapshot {
  90    id: WorktreeId,
  91    abs_path: Arc<Path>,
  92    root_name: String,
  93    root_char_bag: CharBag,
  94    entries_by_path: SumTree<Entry>,
  95    entries_by_id: SumTree<PathEntry>,
  96    scan_id: usize,
  97    completed_scan_id: usize,
  98}
  99
 100#[derive(Clone)]
 101pub struct GitRepositoryEntry {
 102    pub(crate) repo: Arc<Mutex<dyn GitRepository>>,
 103
 104    pub(crate) scan_id: usize,
 105    // Path to folder containing the .git file or directory
 106    pub(crate) content_path: Arc<Path>,
 107    // Path to the actual .git folder.
 108    // Note: if .git is a file, this points to the folder indicated by the .git file
 109    pub(crate) git_dir_path: Arc<Path>,
 110}
 111
 112impl std::fmt::Debug for GitRepositoryEntry {
 113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 114        f.debug_struct("GitRepositoryEntry")
 115            .field("content_path", &self.content_path)
 116            .field("git_dir_path", &self.git_dir_path)
 117            .finish()
 118    }
 119}
 120
 121#[derive(Debug)]
 122pub struct LocalSnapshot {
 123    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 124    git_repositories: Vec<GitRepositoryEntry>,
 125    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 126    next_entry_id: Arc<AtomicUsize>,
 127    snapshot: Snapshot,
 128}
 129
 130impl Clone for LocalSnapshot {
 131    fn clone(&self) -> Self {
 132        Self {
 133            ignores_by_parent_abs_path: self.ignores_by_parent_abs_path.clone(),
 134            git_repositories: self.git_repositories.iter().cloned().collect(),
 135            removed_entry_ids: self.removed_entry_ids.clone(),
 136            next_entry_id: self.next_entry_id.clone(),
 137            snapshot: self.snapshot.clone(),
 138        }
 139    }
 140}
 141
 142impl Deref for LocalSnapshot {
 143    type Target = Snapshot;
 144
 145    fn deref(&self) -> &Self::Target {
 146        &self.snapshot
 147    }
 148}
 149
 150impl DerefMut for LocalSnapshot {
 151    fn deref_mut(&mut self) -> &mut Self::Target {
 152        &mut self.snapshot
 153    }
 154}
 155
 156enum ScanState {
 157    /// The worktree is performing its initial scan of the filesystem.
 158    Initializing {
 159        snapshot: LocalSnapshot,
 160        barrier: Option<barrier::Sender>,
 161    },
 162    Initialized {
 163        snapshot: LocalSnapshot,
 164    },
 165    /// The worktree is updating in response to filesystem events.
 166    Updating,
 167    Updated {
 168        snapshot: LocalSnapshot,
 169        changes: HashMap<Arc<Path>, PathChange>,
 170        barrier: Option<barrier::Sender>,
 171    },
 172}
 173
 174struct ShareState {
 175    project_id: u64,
 176    snapshots_tx: watch::Sender<LocalSnapshot>,
 177    resume_updates: watch::Sender<()>,
 178    _maintain_remote_snapshot: Task<Option<()>>,
 179}
 180
 181pub enum Event {
 182    UpdatedEntries(HashMap<Arc<Path>, PathChange>),
 183    UpdatedGitRepositories(Vec<GitRepositoryEntry>),
 184}
 185
 186impl Entity for Worktree {
 187    type Event = Event;
 188}
 189
 190impl Worktree {
 191    pub async fn local(
 192        client: Arc<Client>,
 193        path: impl Into<Arc<Path>>,
 194        visible: bool,
 195        fs: Arc<dyn Fs>,
 196        next_entry_id: Arc<AtomicUsize>,
 197        cx: &mut AsyncAppContext,
 198    ) -> Result<ModelHandle<Self>> {
 199        // After determining whether the root entry is a file or a directory, populate the
 200        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 201        let abs_path = path.into();
 202        let metadata = fs
 203            .metadata(&abs_path)
 204            .await
 205            .context("failed to stat worktree path")?;
 206
 207        Ok(cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 208            let root_name = abs_path
 209                .file_name()
 210                .map_or(String::new(), |f| f.to_string_lossy().to_string());
 211
 212            let mut snapshot = LocalSnapshot {
 213                ignores_by_parent_abs_path: Default::default(),
 214                git_repositories: Default::default(),
 215                removed_entry_ids: Default::default(),
 216                next_entry_id,
 217                snapshot: Snapshot {
 218                    id: WorktreeId::from_usize(cx.model_id()),
 219                    abs_path: abs_path.clone(),
 220                    root_name: root_name.clone(),
 221                    root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
 222                    entries_by_path: Default::default(),
 223                    entries_by_id: Default::default(),
 224                    scan_id: 0,
 225                    completed_scan_id: 0,
 226                },
 227            };
 228
 229            if let Some(metadata) = metadata {
 230                snapshot.insert_entry(
 231                    Entry::new(
 232                        Arc::from(Path::new("")),
 233                        &metadata,
 234                        &snapshot.next_entry_id,
 235                        snapshot.root_char_bag,
 236                    ),
 237                    fs.as_ref(),
 238                );
 239            }
 240
 241            let (path_changes_tx, path_changes_rx) = channel::unbounded();
 242            let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 243
 244            cx.spawn_weak(|this, mut cx| async move {
 245                while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade(&cx)) {
 246                    this.update(&mut cx, |this, cx| {
 247                        this.as_local_mut()
 248                            .unwrap()
 249                            .background_scanner_updated(state, cx);
 250                    });
 251                }
 252            })
 253            .detach();
 254
 255            let background_scanner_task = cx.background().spawn({
 256                let fs = fs.clone();
 257                let snapshot = snapshot.clone();
 258                let background = cx.background().clone();
 259                async move {
 260                    let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 261                    BackgroundScanner::new(snapshot, scan_states_tx, fs, background)
 262                        .run(events, path_changes_rx)
 263                        .await;
 264                }
 265            });
 266
 267            Worktree::Local(LocalWorktree {
 268                snapshot,
 269                is_scanning: watch::channel_with(true),
 270                share: None,
 271                path_changes_tx,
 272                _background_scanner_task: background_scanner_task,
 273                diagnostics: Default::default(),
 274                diagnostic_summaries: Default::default(),
 275                client,
 276                fs,
 277                visible,
 278            })
 279        }))
 280    }
 281
 282    pub fn remote(
 283        project_remote_id: u64,
 284        replica_id: ReplicaId,
 285        worktree: proto::WorktreeMetadata,
 286        client: Arc<Client>,
 287        cx: &mut AppContext,
 288    ) -> ModelHandle<Self> {
 289        cx.add_model(|cx: &mut ModelContext<Self>| {
 290            let snapshot = Snapshot {
 291                id: WorktreeId(worktree.id as usize),
 292                abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
 293                root_name: worktree.root_name.clone(),
 294                root_char_bag: worktree
 295                    .root_name
 296                    .chars()
 297                    .map(|c| c.to_ascii_lowercase())
 298                    .collect(),
 299                entries_by_path: Default::default(),
 300                entries_by_id: Default::default(),
 301                scan_id: 0,
 302                completed_scan_id: 0,
 303            };
 304
 305            let (updates_tx, mut updates_rx) = mpsc::unbounded();
 306            let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 307            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 308
 309            cx.background()
 310                .spawn({
 311                    let background_snapshot = background_snapshot.clone();
 312                    async move {
 313                        while let Some(update) = updates_rx.next().await {
 314                            if let Err(error) =
 315                                background_snapshot.lock().apply_remote_update(update)
 316                            {
 317                                log::error!("error applying worktree update: {}", error);
 318                            }
 319                            snapshot_updated_tx.send(()).await.ok();
 320                        }
 321                    }
 322                })
 323                .detach();
 324
 325            cx.spawn_weak(|this, mut cx| async move {
 326                while (snapshot_updated_rx.recv().await).is_some() {
 327                    if let Some(this) = this.upgrade(&cx) {
 328                        this.update(&mut cx, |this, cx| {
 329                            let this = this.as_remote_mut().unwrap();
 330                            this.snapshot = this.background_snapshot.lock().clone();
 331                            cx.emit(Event::UpdatedEntries(Default::default()));
 332                            cx.notify();
 333                            while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 334                                if this.observed_snapshot(*scan_id) {
 335                                    let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 336                                    let _ = tx.send(());
 337                                } else {
 338                                    break;
 339                                }
 340                            }
 341                        });
 342                    } else {
 343                        break;
 344                    }
 345                }
 346            })
 347            .detach();
 348
 349            Worktree::Remote(RemoteWorktree {
 350                project_id: project_remote_id,
 351                replica_id,
 352                snapshot: snapshot.clone(),
 353                background_snapshot,
 354                updates_tx: Some(updates_tx),
 355                snapshot_subscriptions: Default::default(),
 356                client: client.clone(),
 357                diagnostic_summaries: Default::default(),
 358                visible: worktree.visible,
 359                disconnected: false,
 360            })
 361        })
 362    }
 363
 364    pub fn as_local(&self) -> Option<&LocalWorktree> {
 365        if let Worktree::Local(worktree) = self {
 366            Some(worktree)
 367        } else {
 368            None
 369        }
 370    }
 371
 372    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 373        if let Worktree::Remote(worktree) = self {
 374            Some(worktree)
 375        } else {
 376            None
 377        }
 378    }
 379
 380    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 381        if let Worktree::Local(worktree) = self {
 382            Some(worktree)
 383        } else {
 384            None
 385        }
 386    }
 387
 388    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 389        if let Worktree::Remote(worktree) = self {
 390            Some(worktree)
 391        } else {
 392            None
 393        }
 394    }
 395
 396    pub fn is_local(&self) -> bool {
 397        matches!(self, Worktree::Local(_))
 398    }
 399
 400    pub fn is_remote(&self) -> bool {
 401        !self.is_local()
 402    }
 403
 404    pub fn snapshot(&self) -> Snapshot {
 405        match self {
 406            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 407            Worktree::Remote(worktree) => worktree.snapshot(),
 408        }
 409    }
 410
 411    pub fn scan_id(&self) -> usize {
 412        match self {
 413            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 414            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 415        }
 416    }
 417
 418    pub fn completed_scan_id(&self) -> usize {
 419        match self {
 420            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 421            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 422        }
 423    }
 424
 425    pub fn is_visible(&self) -> bool {
 426        match self {
 427            Worktree::Local(worktree) => worktree.visible,
 428            Worktree::Remote(worktree) => worktree.visible,
 429        }
 430    }
 431
 432    pub fn replica_id(&self) -> ReplicaId {
 433        match self {
 434            Worktree::Local(_) => 0,
 435            Worktree::Remote(worktree) => worktree.replica_id,
 436        }
 437    }
 438
 439    pub fn diagnostic_summaries(
 440        &self,
 441    ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + '_ {
 442        match self {
 443            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 444            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 445        }
 446        .iter()
 447        .map(|(path, summary)| (path.0.clone(), *summary))
 448    }
 449
 450    pub fn abs_path(&self) -> Arc<Path> {
 451        match self {
 452            Worktree::Local(worktree) => worktree.abs_path.clone(),
 453            Worktree::Remote(worktree) => worktree.abs_path.clone(),
 454        }
 455    }
 456}
 457
 458impl LocalWorktree {
 459    pub fn contains_abs_path(&self, path: &Path) -> bool {
 460        path.starts_with(&self.abs_path)
 461    }
 462
 463    fn absolutize(&self, path: &Path) -> PathBuf {
 464        if path.file_name().is_some() {
 465            self.abs_path.join(path)
 466        } else {
 467            self.abs_path.to_path_buf()
 468        }
 469    }
 470
 471    pub(crate) fn load_buffer(
 472        &mut self,
 473        path: &Path,
 474        cx: &mut ModelContext<Worktree>,
 475    ) -> Task<Result<ModelHandle<Buffer>>> {
 476        let path = Arc::from(path);
 477        cx.spawn(move |this, mut cx| async move {
 478            let (file, contents, diff_base) = this
 479                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 480                .await?;
 481            Ok(cx.add_model(|cx| {
 482                let mut buffer = Buffer::from_file(0, contents, diff_base, Arc::new(file), cx);
 483                buffer.git_diff_recalc(cx);
 484                buffer
 485            }))
 486        })
 487    }
 488
 489    pub fn diagnostics_for_path(
 490        &self,
 491        path: &Path,
 492    ) -> Option<Vec<DiagnosticEntry<Unclipped<PointUtf16>>>> {
 493        self.diagnostics.get(path).cloned()
 494    }
 495
 496    pub fn update_diagnostics(
 497        &mut self,
 498        language_server_id: usize,
 499        worktree_path: Arc<Path>,
 500        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 501        _: &mut ModelContext<Worktree>,
 502    ) -> Result<bool> {
 503        self.diagnostics.remove(&worktree_path);
 504        let old_summary = self
 505            .diagnostic_summaries
 506            .remove(&PathKey(worktree_path.clone()))
 507            .unwrap_or_default();
 508        let new_summary = DiagnosticSummary::new(language_server_id, &diagnostics);
 509        if !new_summary.is_empty() {
 510            self.diagnostic_summaries
 511                .insert(PathKey(worktree_path.clone()), new_summary);
 512            self.diagnostics.insert(worktree_path.clone(), diagnostics);
 513        }
 514
 515        let updated = !old_summary.is_empty() || !new_summary.is_empty();
 516        if updated {
 517            if let Some(share) = self.share.as_ref() {
 518                self.client
 519                    .send(proto::UpdateDiagnosticSummary {
 520                        project_id: share.project_id,
 521                        worktree_id: self.id().to_proto(),
 522                        summary: Some(proto::DiagnosticSummary {
 523                            path: worktree_path.to_string_lossy().to_string(),
 524                            language_server_id: language_server_id as u64,
 525                            error_count: new_summary.error_count as u32,
 526                            warning_count: new_summary.warning_count as u32,
 527                        }),
 528                    })
 529                    .log_err();
 530            }
 531        }
 532
 533        Ok(updated)
 534    }
 535
 536    fn background_scanner_updated(
 537        &mut self,
 538        scan_state: ScanState,
 539        cx: &mut ModelContext<Worktree>,
 540    ) {
 541        match scan_state {
 542            ScanState::Initializing { snapshot, barrier } => {
 543                *self.is_scanning.0.borrow_mut() = true;
 544                self.set_snapshot(snapshot, cx);
 545                drop(barrier);
 546            }
 547            ScanState::Initialized { snapshot } => {
 548                *self.is_scanning.0.borrow_mut() = false;
 549                self.set_snapshot(snapshot, cx);
 550            }
 551            ScanState::Updating => {
 552                *self.is_scanning.0.borrow_mut() = true;
 553            }
 554            ScanState::Updated {
 555                snapshot,
 556                changes,
 557                barrier,
 558            } => {
 559                *self.is_scanning.0.borrow_mut() = false;
 560                cx.emit(Event::UpdatedEntries(changes));
 561                self.set_snapshot(snapshot, cx);
 562                drop(barrier);
 563            }
 564        }
 565        cx.notify();
 566    }
 567
 568    fn set_snapshot(&mut self, new_snapshot: LocalSnapshot, cx: &mut ModelContext<Worktree>) {
 569        let updated_repos = Self::changed_repos(
 570            &self.snapshot.git_repositories,
 571            &new_snapshot.git_repositories,
 572        );
 573        self.snapshot = new_snapshot;
 574
 575        if let Some(share) = self.share.as_mut() {
 576            *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
 577        }
 578
 579        if !updated_repos.is_empty() {
 580            cx.emit(Event::UpdatedGitRepositories(updated_repos));
 581        }
 582    }
 583
 584    fn changed_repos(
 585        old_repos: &[GitRepositoryEntry],
 586        new_repos: &[GitRepositoryEntry],
 587    ) -> Vec<GitRepositoryEntry> {
 588        fn diff<'a>(
 589            a: &'a [GitRepositoryEntry],
 590            b: &'a [GitRepositoryEntry],
 591            updated: &mut HashMap<&'a Path, GitRepositoryEntry>,
 592        ) {
 593            for a_repo in a {
 594                let matched = b.iter().find(|b_repo| {
 595                    a_repo.git_dir_path == b_repo.git_dir_path && a_repo.scan_id == b_repo.scan_id
 596                });
 597
 598                if matched.is_none() {
 599                    updated.insert(a_repo.git_dir_path.as_ref(), a_repo.clone());
 600                }
 601            }
 602        }
 603
 604        let mut updated = HashMap::<&Path, GitRepositoryEntry>::default();
 605
 606        diff(old_repos, new_repos, &mut updated);
 607        diff(new_repos, old_repos, &mut updated);
 608
 609        updated.into_values().collect()
 610    }
 611
 612    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 613        let mut is_scanning_rx = self.is_scanning.1.clone();
 614        async move {
 615            let mut is_scanning = is_scanning_rx.borrow().clone();
 616            while is_scanning {
 617                if let Some(value) = is_scanning_rx.recv().await {
 618                    is_scanning = value;
 619                } else {
 620                    break;
 621                }
 622            }
 623        }
 624    }
 625
 626    pub fn snapshot(&self) -> LocalSnapshot {
 627        self.snapshot.clone()
 628    }
 629
 630    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 631        proto::WorktreeMetadata {
 632            id: self.id().to_proto(),
 633            root_name: self.root_name().to_string(),
 634            visible: self.visible,
 635            abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
 636        }
 637    }
 638
 639    fn load(
 640        &self,
 641        path: &Path,
 642        cx: &mut ModelContext<Worktree>,
 643    ) -> Task<Result<(File, String, Option<String>)>> {
 644        let handle = cx.handle();
 645        let path = Arc::from(path);
 646        let abs_path = self.absolutize(&path);
 647        let fs = self.fs.clone();
 648        let snapshot = self.snapshot();
 649
 650        cx.spawn(|this, mut cx| async move {
 651            let text = fs.load(&abs_path).await?;
 652
 653            let diff_base = if let Some(repo) = snapshot.repo_for(&path) {
 654                if let Ok(repo_relative) = path.strip_prefix(repo.content_path) {
 655                    let repo_relative = repo_relative.to_owned();
 656                    cx.background()
 657                        .spawn(async move { repo.repo.lock().load_index_text(&repo_relative) })
 658                        .await
 659                } else {
 660                    None
 661                }
 662            } else {
 663                None
 664            };
 665
 666            // Eagerly populate the snapshot with an updated entry for the loaded file
 667            let entry = this
 668                .update(&mut cx, |this, cx| {
 669                    this.as_local().unwrap().refresh_entry(path, None, cx)
 670                })
 671                .await?;
 672
 673            Ok((
 674                File {
 675                    entry_id: entry.id,
 676                    worktree: handle,
 677                    path: entry.path,
 678                    mtime: entry.mtime,
 679                    is_local: true,
 680                    is_deleted: false,
 681                },
 682                text,
 683                diff_base,
 684            ))
 685        })
 686    }
 687
 688    pub fn save_buffer(
 689        &self,
 690        buffer_handle: ModelHandle<Buffer>,
 691        path: Arc<Path>,
 692        has_changed_file: bool,
 693        cx: &mut ModelContext<Worktree>,
 694    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
 695        let handle = cx.handle();
 696        let buffer = buffer_handle.read(cx);
 697
 698        let rpc = self.client.clone();
 699        let buffer_id = buffer.remote_id();
 700        let project_id = self.share.as_ref().map(|share| share.project_id);
 701
 702        let text = buffer.as_rope().clone();
 703        let fingerprint = text.fingerprint();
 704        let version = buffer.version();
 705        let save = self.write_file(path, text, buffer.line_ending(), cx);
 706
 707        cx.as_mut().spawn(|mut cx| async move {
 708            let entry = save.await?;
 709
 710            if has_changed_file {
 711                let new_file = Arc::new(File {
 712                    entry_id: entry.id,
 713                    worktree: handle,
 714                    path: entry.path,
 715                    mtime: entry.mtime,
 716                    is_local: true,
 717                    is_deleted: false,
 718                });
 719
 720                if let Some(project_id) = project_id {
 721                    rpc.send(proto::UpdateBufferFile {
 722                        project_id,
 723                        buffer_id,
 724                        file: Some(new_file.to_proto()),
 725                    })
 726                    .log_err();
 727                }
 728
 729                buffer_handle.update(&mut cx, |buffer, cx| {
 730                    if has_changed_file {
 731                        buffer.file_updated(new_file, cx).detach();
 732                    }
 733                });
 734            }
 735
 736            if let Some(project_id) = project_id {
 737                rpc.send(proto::BufferSaved {
 738                    project_id,
 739                    buffer_id,
 740                    version: serialize_version(&version),
 741                    mtime: Some(entry.mtime.into()),
 742                    fingerprint: serialize_fingerprint(fingerprint),
 743                })?;
 744            }
 745
 746            buffer_handle.update(&mut cx, |buffer, cx| {
 747                buffer.did_save(version.clone(), fingerprint, entry.mtime, cx);
 748            });
 749
 750            Ok((version, fingerprint, entry.mtime))
 751        })
 752    }
 753
 754    pub fn create_entry(
 755        &self,
 756        path: impl Into<Arc<Path>>,
 757        is_dir: bool,
 758        cx: &mut ModelContext<Worktree>,
 759    ) -> Task<Result<Entry>> {
 760        let path = path.into();
 761        let abs_path = self.absolutize(&path);
 762        let fs = self.fs.clone();
 763        let write = cx.background().spawn(async move {
 764            if is_dir {
 765                fs.create_dir(&abs_path).await
 766            } else {
 767                fs.save(&abs_path, &Default::default(), Default::default())
 768                    .await
 769            }
 770        });
 771
 772        cx.spawn(|this, mut cx| async move {
 773            write.await?;
 774            this.update(&mut cx, |this, cx| {
 775                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
 776            })
 777            .await
 778        })
 779    }
 780
 781    pub fn write_file(
 782        &self,
 783        path: impl Into<Arc<Path>>,
 784        text: Rope,
 785        line_ending: LineEnding,
 786        cx: &mut ModelContext<Worktree>,
 787    ) -> Task<Result<Entry>> {
 788        let path = path.into();
 789        let abs_path = self.absolutize(&path);
 790        let fs = self.fs.clone();
 791        let write = cx
 792            .background()
 793            .spawn(async move { fs.save(&abs_path, &text, line_ending).await });
 794
 795        cx.spawn(|this, mut cx| async move {
 796            write.await?;
 797            this.update(&mut cx, |this, cx| {
 798                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
 799            })
 800            .await
 801        })
 802    }
 803
 804    pub fn delete_entry(
 805        &self,
 806        entry_id: ProjectEntryId,
 807        cx: &mut ModelContext<Worktree>,
 808    ) -> Option<Task<Result<()>>> {
 809        let entry = self.entry_for_id(entry_id)?.clone();
 810        let abs_path = self.abs_path.clone();
 811        let fs = self.fs.clone();
 812
 813        let delete = cx.background().spawn(async move {
 814            let mut abs_path = fs.canonicalize(&abs_path).await?;
 815            if entry.path.file_name().is_some() {
 816                abs_path = abs_path.join(&entry.path);
 817            }
 818            if entry.is_file() {
 819                fs.remove_file(&abs_path, Default::default()).await?;
 820            } else {
 821                fs.remove_dir(
 822                    &abs_path,
 823                    RemoveOptions {
 824                        recursive: true,
 825                        ignore_if_not_exists: false,
 826                    },
 827                )
 828                .await?;
 829            }
 830            anyhow::Ok(abs_path)
 831        });
 832
 833        Some(cx.spawn(|this, mut cx| async move {
 834            let abs_path = delete.await?;
 835            let (tx, mut rx) = barrier::channel();
 836            this.update(&mut cx, |this, _| {
 837                this.as_local_mut()
 838                    .unwrap()
 839                    .path_changes_tx
 840                    .try_send((vec![abs_path], tx))
 841                    .unwrap();
 842            });
 843            rx.recv().await;
 844            Ok(())
 845        }))
 846    }
 847
 848    pub fn rename_entry(
 849        &self,
 850        entry_id: ProjectEntryId,
 851        new_path: impl Into<Arc<Path>>,
 852        cx: &mut ModelContext<Worktree>,
 853    ) -> Option<Task<Result<Entry>>> {
 854        let old_path = self.entry_for_id(entry_id)?.path.clone();
 855        let new_path = new_path.into();
 856        let abs_old_path = self.absolutize(&old_path);
 857        let abs_new_path = self.absolutize(&new_path);
 858        let fs = self.fs.clone();
 859        let rename = cx.background().spawn(async move {
 860            fs.rename(&abs_old_path, &abs_new_path, Default::default())
 861                .await
 862        });
 863
 864        Some(cx.spawn(|this, mut cx| async move {
 865            rename.await?;
 866            this.update(&mut cx, |this, cx| {
 867                this.as_local_mut()
 868                    .unwrap()
 869                    .refresh_entry(new_path.clone(), Some(old_path), cx)
 870            })
 871            .await
 872        }))
 873    }
 874
 875    pub fn copy_entry(
 876        &self,
 877        entry_id: ProjectEntryId,
 878        new_path: impl Into<Arc<Path>>,
 879        cx: &mut ModelContext<Worktree>,
 880    ) -> Option<Task<Result<Entry>>> {
 881        let old_path = self.entry_for_id(entry_id)?.path.clone();
 882        let new_path = new_path.into();
 883        let abs_old_path = self.absolutize(&old_path);
 884        let abs_new_path = self.absolutize(&new_path);
 885        let fs = self.fs.clone();
 886        let copy = cx.background().spawn(async move {
 887            copy_recursive(
 888                fs.as_ref(),
 889                &abs_old_path,
 890                &abs_new_path,
 891                Default::default(),
 892            )
 893            .await
 894        });
 895
 896        Some(cx.spawn(|this, mut cx| async move {
 897            copy.await?;
 898            this.update(&mut cx, |this, cx| {
 899                this.as_local_mut()
 900                    .unwrap()
 901                    .refresh_entry(new_path.clone(), None, cx)
 902            })
 903            .await
 904        }))
 905    }
 906
 907    fn refresh_entry(
 908        &self,
 909        path: Arc<Path>,
 910        old_path: Option<Arc<Path>>,
 911        cx: &mut ModelContext<Worktree>,
 912    ) -> Task<Result<Entry>> {
 913        let fs = self.fs.clone();
 914        let abs_root_path = self.abs_path.clone();
 915        let path_changes_tx = self.path_changes_tx.clone();
 916        cx.spawn_weak(move |this, mut cx| async move {
 917            let abs_path = fs.canonicalize(&abs_root_path).await?;
 918            let mut paths = Vec::with_capacity(2);
 919            paths.push(if path.file_name().is_some() {
 920                abs_path.join(&path)
 921            } else {
 922                abs_path.clone()
 923            });
 924            if let Some(old_path) = old_path {
 925                paths.push(if old_path.file_name().is_some() {
 926                    abs_path.join(&old_path)
 927                } else {
 928                    abs_path.clone()
 929                });
 930            }
 931
 932            let (tx, mut rx) = barrier::channel();
 933            path_changes_tx.try_send((paths, tx)).unwrap();
 934            rx.recv().await;
 935            this.upgrade(&cx)
 936                .ok_or_else(|| anyhow!("worktree was dropped"))?
 937                .update(&mut cx, |this, _| {
 938                    this.entry_for_path(path)
 939                        .cloned()
 940                        .ok_or_else(|| anyhow!("failed to read path after update"))
 941                })
 942        })
 943    }
 944
 945    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 946        let (share_tx, share_rx) = oneshot::channel();
 947
 948        if let Some(share) = self.share.as_mut() {
 949            let _ = share_tx.send(());
 950            *share.resume_updates.borrow_mut() = ();
 951        } else {
 952            let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
 953            let (resume_updates_tx, mut resume_updates_rx) = watch::channel();
 954            let worktree_id = cx.model_id() as u64;
 955
 956            for (path, summary) in self.diagnostic_summaries.iter() {
 957                if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
 958                    project_id,
 959                    worktree_id,
 960                    summary: Some(summary.to_proto(&path.0)),
 961                }) {
 962                    return Task::ready(Err(e));
 963                }
 964            }
 965
 966            let _maintain_remote_snapshot = cx.background().spawn({
 967                let client = self.client.clone();
 968                async move {
 969                    let mut share_tx = Some(share_tx);
 970                    let mut prev_snapshot = LocalSnapshot {
 971                        ignores_by_parent_abs_path: Default::default(),
 972                        git_repositories: Default::default(),
 973                        removed_entry_ids: Default::default(),
 974                        next_entry_id: Default::default(),
 975                        snapshot: Snapshot {
 976                            id: WorktreeId(worktree_id as usize),
 977                            abs_path: Path::new("").into(),
 978                            root_name: Default::default(),
 979                            root_char_bag: Default::default(),
 980                            entries_by_path: Default::default(),
 981                            entries_by_id: Default::default(),
 982                            scan_id: 0,
 983                            completed_scan_id: 0,
 984                        },
 985                    };
 986                    while let Some(snapshot) = snapshots_rx.recv().await {
 987                        #[cfg(any(test, feature = "test-support"))]
 988                        const MAX_CHUNK_SIZE: usize = 2;
 989                        #[cfg(not(any(test, feature = "test-support")))]
 990                        const MAX_CHUNK_SIZE: usize = 256;
 991
 992                        let update =
 993                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, true);
 994                        for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
 995                            let _ = resume_updates_rx.try_recv();
 996                            while let Err(error) = client.request(update.clone()).await {
 997                                log::error!("failed to send worktree update: {}", error);
 998                                log::info!("waiting to resume updates");
 999                                if resume_updates_rx.next().await.is_none() {
1000                                    return Ok(());
1001                                }
1002                            }
1003                        }
1004
1005                        if let Some(share_tx) = share_tx.take() {
1006                            let _ = share_tx.send(());
1007                        }
1008
1009                        prev_snapshot = snapshot;
1010                    }
1011
1012                    Ok::<_, anyhow::Error>(())
1013                }
1014                .log_err()
1015            });
1016
1017            self.share = Some(ShareState {
1018                project_id,
1019                snapshots_tx,
1020                resume_updates: resume_updates_tx,
1021                _maintain_remote_snapshot,
1022            });
1023        }
1024
1025        cx.foreground()
1026            .spawn(async move { share_rx.await.map_err(|_| anyhow!("share ended")) })
1027    }
1028
1029    pub fn unshare(&mut self) {
1030        self.share.take();
1031    }
1032
1033    pub fn is_shared(&self) -> bool {
1034        self.share.is_some()
1035    }
1036}
1037
1038impl RemoteWorktree {
1039    fn snapshot(&self) -> Snapshot {
1040        self.snapshot.clone()
1041    }
1042
1043    pub fn disconnected_from_host(&mut self) {
1044        self.updates_tx.take();
1045        self.snapshot_subscriptions.clear();
1046        self.disconnected = true;
1047    }
1048
1049    pub fn save_buffer(
1050        &self,
1051        buffer_handle: ModelHandle<Buffer>,
1052        cx: &mut ModelContext<Worktree>,
1053    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1054        let buffer = buffer_handle.read(cx);
1055        let buffer_id = buffer.remote_id();
1056        let version = buffer.version();
1057        let rpc = self.client.clone();
1058        let project_id = self.project_id;
1059        cx.as_mut().spawn(|mut cx| async move {
1060            let response = rpc
1061                .request(proto::SaveBuffer {
1062                    project_id,
1063                    buffer_id,
1064                    version: serialize_version(&version),
1065                })
1066                .await?;
1067            let version = deserialize_version(response.version);
1068            let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1069            let mtime = response
1070                .mtime
1071                .ok_or_else(|| anyhow!("missing mtime"))?
1072                .into();
1073
1074            buffer_handle.update(&mut cx, |buffer, cx| {
1075                buffer.did_save(version.clone(), fingerprint, mtime, cx);
1076            });
1077
1078            Ok((version, fingerprint, mtime))
1079        })
1080    }
1081
1082    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1083        if let Some(updates_tx) = &self.updates_tx {
1084            updates_tx
1085                .unbounded_send(update)
1086                .expect("consumer runs to completion");
1087        }
1088    }
1089
1090    fn observed_snapshot(&self, scan_id: usize) -> bool {
1091        self.completed_scan_id >= scan_id
1092    }
1093
1094    fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1095        let (tx, rx) = oneshot::channel();
1096        if self.observed_snapshot(scan_id) {
1097            let _ = tx.send(());
1098        } else if self.disconnected {
1099            drop(tx);
1100        } else {
1101            match self
1102                .snapshot_subscriptions
1103                .binary_search_by_key(&scan_id, |probe| probe.0)
1104            {
1105                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1106            }
1107        }
1108
1109        async move {
1110            rx.await?;
1111            Ok(())
1112        }
1113    }
1114
1115    pub fn update_diagnostic_summary(
1116        &mut self,
1117        path: Arc<Path>,
1118        summary: &proto::DiagnosticSummary,
1119    ) {
1120        let summary = DiagnosticSummary {
1121            language_server_id: summary.language_server_id as usize,
1122            error_count: summary.error_count as usize,
1123            warning_count: summary.warning_count as usize,
1124        };
1125        if summary.is_empty() {
1126            self.diagnostic_summaries.remove(&PathKey(path));
1127        } else {
1128            self.diagnostic_summaries.insert(PathKey(path), summary);
1129        }
1130    }
1131
1132    pub fn insert_entry(
1133        &mut self,
1134        entry: proto::Entry,
1135        scan_id: usize,
1136        cx: &mut ModelContext<Worktree>,
1137    ) -> Task<Result<Entry>> {
1138        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1139        cx.spawn(|this, mut cx| async move {
1140            wait_for_snapshot.await?;
1141            this.update(&mut cx, |worktree, _| {
1142                let worktree = worktree.as_remote_mut().unwrap();
1143                let mut snapshot = worktree.background_snapshot.lock();
1144                let entry = snapshot.insert_entry(entry);
1145                worktree.snapshot = snapshot.clone();
1146                entry
1147            })
1148        })
1149    }
1150
1151    pub(crate) fn delete_entry(
1152        &mut self,
1153        id: ProjectEntryId,
1154        scan_id: usize,
1155        cx: &mut ModelContext<Worktree>,
1156    ) -> Task<Result<()>> {
1157        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1158        cx.spawn(|this, mut cx| async move {
1159            wait_for_snapshot.await?;
1160            this.update(&mut cx, |worktree, _| {
1161                let worktree = worktree.as_remote_mut().unwrap();
1162                let mut snapshot = worktree.background_snapshot.lock();
1163                snapshot.delete_entry(id);
1164                worktree.snapshot = snapshot.clone();
1165            });
1166            Ok(())
1167        })
1168    }
1169}
1170
1171impl Snapshot {
1172    pub fn id(&self) -> WorktreeId {
1173        self.id
1174    }
1175
1176    pub fn abs_path(&self) -> &Arc<Path> {
1177        &self.abs_path
1178    }
1179
1180    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1181        self.entries_by_id.get(&entry_id, &()).is_some()
1182    }
1183
1184    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1185        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1186        let old_entry = self.entries_by_id.insert_or_replace(
1187            PathEntry {
1188                id: entry.id,
1189                path: entry.path.clone(),
1190                is_ignored: entry.is_ignored,
1191                scan_id: 0,
1192            },
1193            &(),
1194        );
1195        if let Some(old_entry) = old_entry {
1196            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1197        }
1198        self.entries_by_path.insert_or_replace(entry.clone(), &());
1199        Ok(entry)
1200    }
1201
1202    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1203        let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1204        self.entries_by_path = {
1205            let mut cursor = self.entries_by_path.cursor();
1206            let mut new_entries_by_path =
1207                cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1208            while let Some(entry) = cursor.item() {
1209                if entry.path.starts_with(&removed_entry.path) {
1210                    self.entries_by_id.remove(&entry.id, &());
1211                    cursor.next(&());
1212                } else {
1213                    break;
1214                }
1215            }
1216            new_entries_by_path.push_tree(cursor.suffix(&()), &());
1217            new_entries_by_path
1218        };
1219
1220        Some(removed_entry.path)
1221    }
1222
1223    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1224        let mut entries_by_path_edits = Vec::new();
1225        let mut entries_by_id_edits = Vec::new();
1226        for entry_id in update.removed_entries {
1227            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 AppContext,
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: channel::Receiver<(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            let progress_update_count = AtomicUsize::new(0);
2229            self.executor
2230                .scoped(|scope| {
2231                    for _ in 0..self.executor.num_cpus() {
2232                        scope.spawn(async {
2233                            let mut last_progress_update_count = 0;
2234                            let progress_update_timer = self.pause_between_progress_updates().fuse();
2235                            futures::pin_mut!(progress_update_timer);
2236                            loop {
2237                                select_biased! {
2238                                    // Send periodic progress updates to the worktree. Use an atomic counter
2239                                    // to ensure that only one of the workers sends a progress update after
2240                                    // the update interval elapses.
2241                                    _ = progress_update_timer => {
2242                                        match progress_update_count.compare_exchange(
2243                                            last_progress_update_count,
2244                                            last_progress_update_count + 1,
2245                                            SeqCst,
2246                                            SeqCst
2247                                        ) {
2248                                            Ok(_) => {
2249                                                last_progress_update_count += 1;
2250                                                if self
2251                                                    .notify
2252                                                    .unbounded_send(ScanState::Initializing {
2253                                                        snapshot: self.snapshot.lock().clone(),
2254                                                        barrier: None,
2255                                                    })
2256                                                    .is_err()
2257                                                {
2258                                                    break;
2259                                                }
2260                                            }
2261                                            Err(current_count) => last_progress_update_count = current_count,
2262                                        }
2263                                        progress_update_timer.set(self.pause_between_progress_updates().fuse());
2264                                    }
2265
2266                                    // Refresh any paths requested by the main thread.
2267                                    job = changed_paths.recv().fuse() => {
2268                                        let Ok((abs_paths, barrier)) = job else { break };
2269                                        self.update_entries_for_paths(abs_paths, None).await;
2270                                        if self
2271                                            .notify
2272                                            .unbounded_send(ScanState::Initializing {
2273                                                snapshot: self.snapshot.lock().clone(),
2274                                                barrier: Some(barrier),
2275                                            })
2276                                            .is_err()
2277                                        {
2278                                            break;
2279                                        }
2280                                    }
2281
2282                                    // Recursively load directories from the file system.
2283                                    job = rx.recv().fuse() => {
2284                                        let Ok(job) = job else { break };
2285                                        if let Err(err) = self
2286                                            .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2287                                            .await
2288                                        {
2289                                            log::error!("error scanning {:?}: {}", job.abs_path, err);
2290                                        }
2291                                    }
2292                                }
2293                            }
2294                        });
2295                    }
2296                })
2297                .await;
2298        }
2299
2300        self.snapshot.lock().scan_completed();
2301
2302        if self
2303            .notify
2304            .unbounded_send(ScanState::Initialized {
2305                snapshot: self.snapshot.lock().clone(),
2306            })
2307            .is_err()
2308        {
2309            return;
2310        }
2311
2312        // Process any events that occurred while performing the initial scan. These
2313        // events can't be reported as precisely, because there is no snapshot of the
2314        // worktree before they occurred.
2315        futures::pin_mut!(events_rx);
2316        if let Poll::Ready(Some(mut events)) = futures::poll!(events_rx.next()) {
2317            while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
2318                events.extend(additional_events);
2319            }
2320            let abs_paths = events.into_iter().map(|e| e.path).collect();
2321            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2322                return;
2323            }
2324            if let Some(changes) = self.process_events(abs_paths, true).await {
2325                if self
2326                    .notify
2327                    .unbounded_send(ScanState::Updated {
2328                        snapshot: self.snapshot.lock().clone(),
2329                        changes,
2330                        barrier: None,
2331                    })
2332                    .is_err()
2333                {
2334                    return;
2335                }
2336            } else {
2337                return;
2338            }
2339        }
2340
2341        // Continue processing events until the worktree is dropped.
2342        loop {
2343            let barrier;
2344            let abs_paths;
2345            select_biased! {
2346                request = changed_paths.next().fuse() => {
2347                    let Some((paths, b)) = request else { break };
2348                    abs_paths = paths;
2349                    barrier = Some(b);
2350                }
2351                events = events_rx.next().fuse() => {
2352                    let Some(events) = events else { break };
2353                    abs_paths = events.into_iter().map(|e| e.path).collect();
2354                    barrier = None;
2355                }
2356            }
2357
2358            if self.notify.unbounded_send(ScanState::Updating).is_err() {
2359                return;
2360            }
2361            if let Some(changes) = self.process_events(abs_paths, false).await {
2362                if self
2363                    .notify
2364                    .unbounded_send(ScanState::Updated {
2365                        snapshot: self.snapshot.lock().clone(),
2366                        changes,
2367                        barrier,
2368                    })
2369                    .is_err()
2370                {
2371                    return;
2372                }
2373            } else {
2374                return;
2375            }
2376        }
2377    }
2378
2379    async fn pause_between_progress_updates(&self) {
2380        #[cfg(any(test, feature = "test-support"))]
2381        if self.fs.is_fake() {
2382            return self.executor.simulate_random_delay().await;
2383        }
2384        smol::Timer::after(Duration::from_millis(100)).await;
2385    }
2386
2387    async fn scan_dir(
2388        &self,
2389        root_char_bag: CharBag,
2390        next_entry_id: Arc<AtomicUsize>,
2391        job: &ScanJob,
2392    ) -> Result<()> {
2393        let mut new_entries: Vec<Entry> = Vec::new();
2394        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2395        let mut ignore_stack = job.ignore_stack.clone();
2396        let mut new_ignore = None;
2397
2398        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2399        while let Some(child_abs_path) = child_paths.next().await {
2400            let child_abs_path = match child_abs_path {
2401                Ok(child_abs_path) => child_abs_path,
2402                Err(error) => {
2403                    log::error!("error processing entry {:?}", error);
2404                    continue;
2405                }
2406            };
2407
2408            let child_name = child_abs_path.file_name().unwrap();
2409            let child_path: Arc<Path> = job.path.join(child_name).into();
2410            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2411                Ok(Some(metadata)) => metadata,
2412                Ok(None) => continue,
2413                Err(err) => {
2414                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2415                    continue;
2416                }
2417            };
2418
2419            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2420            if child_name == *GITIGNORE {
2421                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2422                    Ok(ignore) => {
2423                        let ignore = Arc::new(ignore);
2424                        ignore_stack =
2425                            ignore_stack.append(job.abs_path.as_path().into(), ignore.clone());
2426                        new_ignore = Some(ignore);
2427                    }
2428                    Err(error) => {
2429                        log::error!(
2430                            "error loading .gitignore file {:?} - {:?}",
2431                            child_name,
2432                            error
2433                        );
2434                    }
2435                }
2436
2437                // Update ignore status of any child entries we've already processed to reflect the
2438                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2439                // there should rarely be too numerous. Update the ignore stack associated with any
2440                // new jobs as well.
2441                let mut new_jobs = new_jobs.iter_mut();
2442                for entry in &mut new_entries {
2443                    let entry_abs_path = self.abs_path().join(&entry.path);
2444                    entry.is_ignored =
2445                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2446
2447                    if entry.is_dir() {
2448                        if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
2449                            job.ignore_stack = if entry.is_ignored {
2450                                IgnoreStack::all()
2451                            } else {
2452                                ignore_stack.clone()
2453                            };
2454                        }
2455                    }
2456                }
2457            }
2458
2459            let mut child_entry = Entry::new(
2460                child_path.clone(),
2461                &child_metadata,
2462                &next_entry_id,
2463                root_char_bag,
2464            );
2465
2466            if child_entry.is_dir() {
2467                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2468                child_entry.is_ignored = is_ignored;
2469
2470                // Avoid recursing until crash in the case of a recursive symlink
2471                if !job.ancestor_inodes.contains(&child_entry.inode) {
2472                    let mut ancestor_inodes = job.ancestor_inodes.clone();
2473                    ancestor_inodes.insert(child_entry.inode);
2474
2475                    new_jobs.push(Some(ScanJob {
2476                        abs_path: child_abs_path,
2477                        path: child_path,
2478                        ignore_stack: if is_ignored {
2479                            IgnoreStack::all()
2480                        } else {
2481                            ignore_stack.clone()
2482                        },
2483                        ancestor_inodes,
2484                        scan_queue: job.scan_queue.clone(),
2485                    }));
2486                } else {
2487                    new_jobs.push(None);
2488                }
2489            } else {
2490                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2491            }
2492
2493            new_entries.push(child_entry);
2494        }
2495
2496        self.snapshot.lock().populate_dir(
2497            job.path.clone(),
2498            new_entries,
2499            new_ignore,
2500            self.fs.as_ref(),
2501        );
2502
2503        for new_job in new_jobs {
2504            if let Some(new_job) = new_job {
2505                job.scan_queue.send(new_job).await.unwrap();
2506            }
2507        }
2508
2509        Ok(())
2510    }
2511
2512    async fn process_events(
2513        &self,
2514        abs_paths: Vec<PathBuf>,
2515        received_before_initialized: bool,
2516    ) -> Option<HashMap<Arc<Path>, PathChange>> {
2517        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2518
2519        let prev_snapshot = {
2520            let mut snapshot = self.snapshot.lock();
2521            snapshot.scan_started();
2522            snapshot.clone()
2523        };
2524
2525        let event_paths = self
2526            .update_entries_for_paths(abs_paths, Some(scan_queue_tx))
2527            .await?;
2528
2529        // Scan any directories that were created as part of this event batch.
2530        self.executor
2531            .scoped(|scope| {
2532                for _ in 0..self.executor.num_cpus() {
2533                    scope.spawn(async {
2534                        while let Ok(job) = scan_queue_rx.recv().await {
2535                            if let Err(err) = self
2536                                .scan_dir(
2537                                    prev_snapshot.root_char_bag,
2538                                    prev_snapshot.next_entry_id.clone(),
2539                                    &job,
2540                                )
2541                                .await
2542                            {
2543                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2544                            }
2545                        }
2546                    });
2547                }
2548            })
2549            .await;
2550
2551        // Attempt to detect renames only over a single batch of file-system events.
2552        self.snapshot.lock().removed_entry_ids.clear();
2553
2554        self.update_ignore_statuses().await;
2555        self.update_git_repositories();
2556        let changes = self.build_change_set(
2557            prev_snapshot.snapshot,
2558            event_paths,
2559            received_before_initialized,
2560        );
2561        self.snapshot.lock().scan_completed();
2562        Some(changes)
2563    }
2564
2565    async fn update_entries_for_paths(
2566        &self,
2567        mut abs_paths: Vec<PathBuf>,
2568        scan_queue_tx: Option<Sender<ScanJob>>,
2569    ) -> Option<Vec<Arc<Path>>> {
2570        abs_paths.sort_unstable();
2571        abs_paths.dedup_by(|a, b| a.starts_with(&b));
2572
2573        let root_abs_path = self.snapshot.lock().abs_path.clone();
2574        let root_canonical_path = self.fs.canonicalize(&root_abs_path).await.ok()?;
2575        let metadata = futures::future::join_all(
2576            abs_paths
2577                .iter()
2578                .map(|abs_path| self.fs.metadata(&abs_path))
2579                .collect::<Vec<_>>(),
2580        )
2581        .await;
2582
2583        let mut snapshot = self.snapshot.lock();
2584        if scan_queue_tx.is_some() {
2585            for abs_path in &abs_paths {
2586                if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
2587                    snapshot.remove_path(path);
2588                }
2589            }
2590        }
2591
2592        let mut event_paths = Vec::with_capacity(abs_paths.len());
2593        for (abs_path, metadata) in abs_paths.into_iter().zip(metadata.into_iter()) {
2594            let path: Arc<Path> = match abs_path.strip_prefix(&root_canonical_path) {
2595                Ok(path) => Arc::from(path.to_path_buf()),
2596                Err(_) => {
2597                    log::error!(
2598                        "unexpected event {:?} for root path {:?}",
2599                        abs_path,
2600                        root_canonical_path
2601                    );
2602                    continue;
2603                }
2604            };
2605            event_paths.push(path.clone());
2606            let abs_path = root_abs_path.join(&path);
2607
2608            match metadata {
2609                Ok(Some(metadata)) => {
2610                    let ignore_stack =
2611                        snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2612                    let mut fs_entry = Entry::new(
2613                        path.clone(),
2614                        &metadata,
2615                        snapshot.next_entry_id.as_ref(),
2616                        snapshot.root_char_bag,
2617                    );
2618                    fs_entry.is_ignored = ignore_stack.is_all();
2619                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
2620
2621                    let scan_id = snapshot.scan_id;
2622                    if let Some(repo) = snapshot.repo_with_dot_git_containing(&path) {
2623                        repo.repo.lock().reload_index();
2624                        repo.scan_id = scan_id;
2625                    }
2626
2627                    if let Some(scan_queue_tx) = &scan_queue_tx {
2628                        let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2629                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2630                            ancestor_inodes.insert(metadata.inode);
2631                            self.executor
2632                                .block(scan_queue_tx.send(ScanJob {
2633                                    abs_path,
2634                                    path,
2635                                    ignore_stack,
2636                                    ancestor_inodes,
2637                                    scan_queue: scan_queue_tx.clone(),
2638                                }))
2639                                .unwrap();
2640                        }
2641                    }
2642                }
2643                Ok(None) => {}
2644                Err(err) => {
2645                    // TODO - create a special 'error' entry in the entries tree to mark this
2646                    log::error!("error reading file on event {:?}", err);
2647                }
2648            }
2649        }
2650
2651        Some(event_paths)
2652    }
2653
2654    async fn update_ignore_statuses(&self) {
2655        let mut snapshot = self.snapshot.lock().clone();
2656        let mut ignores_to_update = Vec::new();
2657        let mut ignores_to_delete = Vec::new();
2658        for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2659            if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2660                if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2661                    ignores_to_update.push(parent_abs_path.clone());
2662                }
2663
2664                let ignore_path = parent_path.join(&*GITIGNORE);
2665                if snapshot.entry_for_path(ignore_path).is_none() {
2666                    ignores_to_delete.push(parent_abs_path.clone());
2667                }
2668            }
2669        }
2670
2671        for parent_abs_path in ignores_to_delete {
2672            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2673            self.snapshot
2674                .lock()
2675                .ignores_by_parent_abs_path
2676                .remove(&parent_abs_path);
2677        }
2678
2679        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2680        ignores_to_update.sort_unstable();
2681        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2682        while let Some(parent_abs_path) = ignores_to_update.next() {
2683            while ignores_to_update
2684                .peek()
2685                .map_or(false, |p| p.starts_with(&parent_abs_path))
2686            {
2687                ignores_to_update.next().unwrap();
2688            }
2689
2690            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2691            ignore_queue_tx
2692                .send(UpdateIgnoreStatusJob {
2693                    abs_path: parent_abs_path,
2694                    ignore_stack,
2695                    ignore_queue: ignore_queue_tx.clone(),
2696                })
2697                .await
2698                .unwrap();
2699        }
2700        drop(ignore_queue_tx);
2701
2702        self.executor
2703            .scoped(|scope| {
2704                for _ in 0..self.executor.num_cpus() {
2705                    scope.spawn(async {
2706                        while let Ok(job) = ignore_queue_rx.recv().await {
2707                            self.update_ignore_status(job, &snapshot).await;
2708                        }
2709                    });
2710                }
2711            })
2712            .await;
2713    }
2714
2715    fn update_git_repositories(&self) {
2716        let mut snapshot = self.snapshot.lock();
2717        let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2718        git_repositories.retain(|repo| snapshot.entry_for_path(&repo.git_dir_path).is_some());
2719        snapshot.git_repositories = git_repositories;
2720    }
2721
2722    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2723        let mut ignore_stack = job.ignore_stack;
2724        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2725            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2726        }
2727
2728        let mut entries_by_id_edits = Vec::new();
2729        let mut entries_by_path_edits = Vec::new();
2730        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2731        for mut entry in snapshot.child_entries(path).cloned() {
2732            let was_ignored = entry.is_ignored;
2733            let abs_path = self.abs_path().join(&entry.path);
2734            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2735            if entry.is_dir() {
2736                let child_ignore_stack = if entry.is_ignored {
2737                    IgnoreStack::all()
2738                } else {
2739                    ignore_stack.clone()
2740                };
2741                job.ignore_queue
2742                    .send(UpdateIgnoreStatusJob {
2743                        abs_path: abs_path.into(),
2744                        ignore_stack: child_ignore_stack,
2745                        ignore_queue: job.ignore_queue.clone(),
2746                    })
2747                    .await
2748                    .unwrap();
2749            }
2750
2751            if entry.is_ignored != was_ignored {
2752                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2753                path_entry.scan_id = snapshot.scan_id;
2754                path_entry.is_ignored = entry.is_ignored;
2755                entries_by_id_edits.push(Edit::Insert(path_entry));
2756                entries_by_path_edits.push(Edit::Insert(entry));
2757            }
2758        }
2759
2760        let mut snapshot = self.snapshot.lock();
2761        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2762        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2763    }
2764
2765    fn build_change_set(
2766        &self,
2767        old_snapshot: Snapshot,
2768        event_paths: Vec<Arc<Path>>,
2769        received_before_initialized: bool,
2770    ) -> HashMap<Arc<Path>, PathChange> {
2771        use PathChange::{Added, AddedOrUpdated, Removed, Updated};
2772
2773        let new_snapshot = self.snapshot.lock();
2774        let mut changes = HashMap::default();
2775        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
2776        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
2777
2778        for path in event_paths {
2779            let path = PathKey(path);
2780            old_paths.seek(&path, Bias::Left, &());
2781            new_paths.seek(&path, Bias::Left, &());
2782
2783            loop {
2784                match (old_paths.item(), new_paths.item()) {
2785                    (Some(old_entry), Some(new_entry)) => {
2786                        if old_entry.path > path.0
2787                            && new_entry.path > path.0
2788                            && !old_entry.path.starts_with(&path.0)
2789                            && !new_entry.path.starts_with(&path.0)
2790                        {
2791                            break;
2792                        }
2793
2794                        match Ord::cmp(&old_entry.path, &new_entry.path) {
2795                            Ordering::Less => {
2796                                changes.insert(old_entry.path.clone(), Removed);
2797                                old_paths.next(&());
2798                            }
2799                            Ordering::Equal => {
2800                                if received_before_initialized {
2801                                    // If the worktree was not fully initialized when this event was generated,
2802                                    // we can't know whether this entry was added during the scan or whether
2803                                    // it was merely updated.
2804                                    changes.insert(old_entry.path.clone(), AddedOrUpdated);
2805                                } else if old_entry.mtime != new_entry.mtime {
2806                                    changes.insert(old_entry.path.clone(), Updated);
2807                                }
2808                                old_paths.next(&());
2809                                new_paths.next(&());
2810                            }
2811                            Ordering::Greater => {
2812                                changes.insert(new_entry.path.clone(), Added);
2813                                new_paths.next(&());
2814                            }
2815                        }
2816                    }
2817                    (Some(old_entry), None) => {
2818                        changes.insert(old_entry.path.clone(), Removed);
2819                        old_paths.next(&());
2820                    }
2821                    (None, Some(new_entry)) => {
2822                        changes.insert(new_entry.path.clone(), Added);
2823                        new_paths.next(&());
2824                    }
2825                    (None, None) => break,
2826                }
2827            }
2828        }
2829        changes
2830    }
2831}
2832
2833fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2834    let mut result = root_char_bag;
2835    result.extend(
2836        path.to_string_lossy()
2837            .chars()
2838            .map(|c| c.to_ascii_lowercase()),
2839    );
2840    result
2841}
2842
2843struct ScanJob {
2844    abs_path: PathBuf,
2845    path: Arc<Path>,
2846    ignore_stack: Arc<IgnoreStack>,
2847    scan_queue: Sender<ScanJob>,
2848    ancestor_inodes: TreeSet<u64>,
2849}
2850
2851struct UpdateIgnoreStatusJob {
2852    abs_path: Arc<Path>,
2853    ignore_stack: Arc<IgnoreStack>,
2854    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2855}
2856
2857pub trait WorktreeHandle {
2858    #[cfg(any(test, feature = "test-support"))]
2859    fn flush_fs_events<'a>(
2860        &self,
2861        cx: &'a gpui::TestAppContext,
2862    ) -> futures::future::LocalBoxFuture<'a, ()>;
2863}
2864
2865impl WorktreeHandle for ModelHandle<Worktree> {
2866    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2867    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2868    // extra directory scans, and emit extra scan-state notifications.
2869    //
2870    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2871    // to ensure that all redundant FS events have already been processed.
2872    #[cfg(any(test, feature = "test-support"))]
2873    fn flush_fs_events<'a>(
2874        &self,
2875        cx: &'a gpui::TestAppContext,
2876    ) -> futures::future::LocalBoxFuture<'a, ()> {
2877        use smol::future::FutureExt;
2878
2879        let filename = "fs-event-sentinel";
2880        let tree = self.clone();
2881        let (fs, root_path) = self.read_with(cx, |tree, _| {
2882            let tree = tree.as_local().unwrap();
2883            (tree.fs.clone(), tree.abs_path().clone())
2884        });
2885
2886        async move {
2887            fs.create_file(&root_path.join(filename), Default::default())
2888                .await
2889                .unwrap();
2890            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
2891                .await;
2892
2893            fs.remove_file(&root_path.join(filename), Default::default())
2894                .await
2895                .unwrap();
2896            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
2897                .await;
2898
2899            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2900                .await;
2901        }
2902        .boxed_local()
2903    }
2904}
2905
2906#[derive(Clone, Debug)]
2907struct TraversalProgress<'a> {
2908    max_path: &'a Path,
2909    count: usize,
2910    visible_count: usize,
2911    file_count: usize,
2912    visible_file_count: usize,
2913}
2914
2915impl<'a> TraversalProgress<'a> {
2916    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2917        match (include_ignored, include_dirs) {
2918            (true, true) => self.count,
2919            (true, false) => self.file_count,
2920            (false, true) => self.visible_count,
2921            (false, false) => self.visible_file_count,
2922        }
2923    }
2924}
2925
2926impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2927    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2928        self.max_path = summary.max_path.as_ref();
2929        self.count += summary.count;
2930        self.visible_count += summary.visible_count;
2931        self.file_count += summary.file_count;
2932        self.visible_file_count += summary.visible_file_count;
2933    }
2934}
2935
2936impl<'a> Default for TraversalProgress<'a> {
2937    fn default() -> Self {
2938        Self {
2939            max_path: Path::new(""),
2940            count: 0,
2941            visible_count: 0,
2942            file_count: 0,
2943            visible_file_count: 0,
2944        }
2945    }
2946}
2947
2948pub struct Traversal<'a> {
2949    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2950    include_ignored: bool,
2951    include_dirs: bool,
2952}
2953
2954impl<'a> Traversal<'a> {
2955    pub fn advance(&mut self) -> bool {
2956        self.advance_to_offset(self.offset() + 1)
2957    }
2958
2959    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2960        self.cursor.seek_forward(
2961            &TraversalTarget::Count {
2962                count: offset,
2963                include_dirs: self.include_dirs,
2964                include_ignored: self.include_ignored,
2965            },
2966            Bias::Right,
2967            &(),
2968        )
2969    }
2970
2971    pub fn advance_to_sibling(&mut self) -> bool {
2972        while let Some(entry) = self.cursor.item() {
2973            self.cursor.seek_forward(
2974                &TraversalTarget::PathSuccessor(&entry.path),
2975                Bias::Left,
2976                &(),
2977            );
2978            if let Some(entry) = self.cursor.item() {
2979                if (self.include_dirs || !entry.is_dir())
2980                    && (self.include_ignored || !entry.is_ignored)
2981                {
2982                    return true;
2983                }
2984            }
2985        }
2986        false
2987    }
2988
2989    pub fn entry(&self) -> Option<&'a Entry> {
2990        self.cursor.item()
2991    }
2992
2993    pub fn offset(&self) -> usize {
2994        self.cursor
2995            .start()
2996            .count(self.include_dirs, self.include_ignored)
2997    }
2998}
2999
3000impl<'a> Iterator for Traversal<'a> {
3001    type Item = &'a Entry;
3002
3003    fn next(&mut self) -> Option<Self::Item> {
3004        if let Some(item) = self.entry() {
3005            self.advance();
3006            Some(item)
3007        } else {
3008            None
3009        }
3010    }
3011}
3012
3013#[derive(Debug)]
3014enum TraversalTarget<'a> {
3015    Path(&'a Path),
3016    PathSuccessor(&'a Path),
3017    Count {
3018        count: usize,
3019        include_ignored: bool,
3020        include_dirs: bool,
3021    },
3022}
3023
3024impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3025    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3026        match self {
3027            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3028            TraversalTarget::PathSuccessor(path) => {
3029                if !cursor_location.max_path.starts_with(path) {
3030                    Ordering::Equal
3031                } else {
3032                    Ordering::Greater
3033                }
3034            }
3035            TraversalTarget::Count {
3036                count,
3037                include_dirs,
3038                include_ignored,
3039            } => Ord::cmp(
3040                count,
3041                &cursor_location.count(*include_dirs, *include_ignored),
3042            ),
3043        }
3044    }
3045}
3046
3047struct ChildEntriesIter<'a> {
3048    parent_path: &'a Path,
3049    traversal: Traversal<'a>,
3050}
3051
3052impl<'a> Iterator for ChildEntriesIter<'a> {
3053    type Item = &'a Entry;
3054
3055    fn next(&mut self) -> Option<Self::Item> {
3056        if let Some(item) = self.traversal.entry() {
3057            if item.path.starts_with(&self.parent_path) {
3058                self.traversal.advance_to_sibling();
3059                return Some(item);
3060            }
3061        }
3062        None
3063    }
3064}
3065
3066impl<'a> From<&'a Entry> for proto::Entry {
3067    fn from(entry: &'a Entry) -> Self {
3068        Self {
3069            id: entry.id.to_proto(),
3070            is_dir: entry.is_dir(),
3071            path: entry.path.to_string_lossy().into(),
3072            inode: entry.inode,
3073            mtime: Some(entry.mtime.into()),
3074            is_symlink: entry.is_symlink,
3075            is_ignored: entry.is_ignored,
3076        }
3077    }
3078}
3079
3080impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3081    type Error = anyhow::Error;
3082
3083    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3084        if let Some(mtime) = entry.mtime {
3085            let kind = if entry.is_dir {
3086                EntryKind::Dir
3087            } else {
3088                let mut char_bag = *root_char_bag;
3089                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3090                EntryKind::File(char_bag)
3091            };
3092            let path: Arc<Path> = PathBuf::from(entry.path).into();
3093            Ok(Entry {
3094                id: ProjectEntryId::from_proto(entry.id),
3095                kind,
3096                path,
3097                inode: entry.inode,
3098                mtime: mtime.into(),
3099                is_symlink: entry.is_symlink,
3100                is_ignored: entry.is_ignored,
3101            })
3102        } else {
3103            Err(anyhow!(
3104                "missing mtime in remote worktree entry {:?}",
3105                entry.path
3106            ))
3107        }
3108    }
3109}
3110
3111#[cfg(test)]
3112mod tests {
3113    use super::*;
3114    use fs::repository::FakeGitRepository;
3115    use fs::{FakeFs, RealFs};
3116    use gpui::{executor::Deterministic, TestAppContext};
3117    use rand::prelude::*;
3118    use serde_json::json;
3119    use std::{env, fmt::Write};
3120    use util::http::FakeHttpClient;
3121
3122    use util::test::temp_tree;
3123
3124    #[gpui::test]
3125    async fn test_traversal(cx: &mut TestAppContext) {
3126        let fs = FakeFs::new(cx.background());
3127        fs.insert_tree(
3128            "/root",
3129            json!({
3130               ".gitignore": "a/b\n",
3131               "a": {
3132                   "b": "",
3133                   "c": "",
3134               }
3135            }),
3136        )
3137        .await;
3138
3139        let http_client = FakeHttpClient::with_404_response();
3140        let client = cx.read(|cx| Client::new(http_client, cx));
3141
3142        let tree = Worktree::local(
3143            client,
3144            Path::new("/root"),
3145            true,
3146            fs,
3147            Default::default(),
3148            &mut cx.to_async(),
3149        )
3150        .await
3151        .unwrap();
3152        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3153            .await;
3154
3155        tree.read_with(cx, |tree, _| {
3156            assert_eq!(
3157                tree.entries(false)
3158                    .map(|entry| entry.path.as_ref())
3159                    .collect::<Vec<_>>(),
3160                vec![
3161                    Path::new(""),
3162                    Path::new(".gitignore"),
3163                    Path::new("a"),
3164                    Path::new("a/c"),
3165                ]
3166            );
3167            assert_eq!(
3168                tree.entries(true)
3169                    .map(|entry| entry.path.as_ref())
3170                    .collect::<Vec<_>>(),
3171                vec![
3172                    Path::new(""),
3173                    Path::new(".gitignore"),
3174                    Path::new("a"),
3175                    Path::new("a/b"),
3176                    Path::new("a/c"),
3177                ]
3178            );
3179        })
3180    }
3181
3182    #[gpui::test(iterations = 10)]
3183    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3184        let fs = FakeFs::new(cx.background());
3185        fs.insert_tree(
3186            "/root",
3187            json!({
3188                "lib": {
3189                    "a": {
3190                        "a.txt": ""
3191                    },
3192                    "b": {
3193                        "b.txt": ""
3194                    }
3195                }
3196            }),
3197        )
3198        .await;
3199        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3200        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3201
3202        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3203        let tree = Worktree::local(
3204            client,
3205            Path::new("/root"),
3206            true,
3207            fs.clone(),
3208            Default::default(),
3209            &mut cx.to_async(),
3210        )
3211        .await
3212        .unwrap();
3213
3214        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3215            .await;
3216
3217        tree.read_with(cx, |tree, _| {
3218            assert_eq!(
3219                tree.entries(false)
3220                    .map(|entry| entry.path.as_ref())
3221                    .collect::<Vec<_>>(),
3222                vec![
3223                    Path::new(""),
3224                    Path::new("lib"),
3225                    Path::new("lib/a"),
3226                    Path::new("lib/a/a.txt"),
3227                    Path::new("lib/a/lib"),
3228                    Path::new("lib/b"),
3229                    Path::new("lib/b/b.txt"),
3230                    Path::new("lib/b/lib"),
3231                ]
3232            );
3233        });
3234
3235        fs.rename(
3236            Path::new("/root/lib/a/lib"),
3237            Path::new("/root/lib/a/lib-2"),
3238            Default::default(),
3239        )
3240        .await
3241        .unwrap();
3242        executor.run_until_parked();
3243        tree.read_with(cx, |tree, _| {
3244            assert_eq!(
3245                tree.entries(false)
3246                    .map(|entry| entry.path.as_ref())
3247                    .collect::<Vec<_>>(),
3248                vec![
3249                    Path::new(""),
3250                    Path::new("lib"),
3251                    Path::new("lib/a"),
3252                    Path::new("lib/a/a.txt"),
3253                    Path::new("lib/a/lib-2"),
3254                    Path::new("lib/b"),
3255                    Path::new("lib/b/b.txt"),
3256                    Path::new("lib/b/lib"),
3257                ]
3258            );
3259        });
3260    }
3261
3262    #[gpui::test]
3263    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3264        let parent_dir = temp_tree(json!({
3265            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3266            "tree": {
3267                ".git": {},
3268                ".gitignore": "ignored-dir\n",
3269                "tracked-dir": {
3270                    "tracked-file1": "",
3271                    "ancestor-ignored-file1": "",
3272                },
3273                "ignored-dir": {
3274                    "ignored-file1": ""
3275                }
3276            }
3277        }));
3278        let dir = parent_dir.path().join("tree");
3279
3280        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3281
3282        let tree = Worktree::local(
3283            client,
3284            dir.as_path(),
3285            true,
3286            Arc::new(RealFs),
3287            Default::default(),
3288            &mut cx.to_async(),
3289        )
3290        .await
3291        .unwrap();
3292        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3293            .await;
3294        tree.flush_fs_events(cx).await;
3295        cx.read(|cx| {
3296            let tree = tree.read(cx);
3297            assert!(
3298                !tree
3299                    .entry_for_path("tracked-dir/tracked-file1")
3300                    .unwrap()
3301                    .is_ignored
3302            );
3303            assert!(
3304                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3305                    .unwrap()
3306                    .is_ignored
3307            );
3308            assert!(
3309                tree.entry_for_path("ignored-dir/ignored-file1")
3310                    .unwrap()
3311                    .is_ignored
3312            );
3313        });
3314
3315        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3316        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3317        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3318        tree.flush_fs_events(cx).await;
3319        cx.read(|cx| {
3320            let tree = tree.read(cx);
3321            assert!(
3322                !tree
3323                    .entry_for_path("tracked-dir/tracked-file2")
3324                    .unwrap()
3325                    .is_ignored
3326            );
3327            assert!(
3328                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3329                    .unwrap()
3330                    .is_ignored
3331            );
3332            assert!(
3333                tree.entry_for_path("ignored-dir/ignored-file2")
3334                    .unwrap()
3335                    .is_ignored
3336            );
3337            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3338        });
3339    }
3340
3341    #[gpui::test]
3342    async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3343        let root = temp_tree(json!({
3344            "dir1": {
3345                ".git": {},
3346                "deps": {
3347                    "dep1": {
3348                        ".git": {},
3349                        "src": {
3350                            "a.txt": ""
3351                        }
3352                    }
3353                },
3354                "src": {
3355                    "b.txt": ""
3356                }
3357            },
3358            "c.txt": "",
3359        }));
3360
3361        let http_client = FakeHttpClient::with_404_response();
3362        let client = cx.read(|cx| Client::new(http_client, cx));
3363        let tree = Worktree::local(
3364            client,
3365            root.path(),
3366            true,
3367            Arc::new(RealFs),
3368            Default::default(),
3369            &mut cx.to_async(),
3370        )
3371        .await
3372        .unwrap();
3373
3374        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3375            .await;
3376        tree.flush_fs_events(cx).await;
3377
3378        tree.read_with(cx, |tree, _cx| {
3379            let tree = tree.as_local().unwrap();
3380
3381            assert!(tree.repo_for("c.txt".as_ref()).is_none());
3382
3383            let repo = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3384            assert_eq!(repo.content_path.as_ref(), Path::new("dir1"));
3385            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/.git"));
3386
3387            let repo = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3388            assert_eq!(repo.content_path.as_ref(), Path::new("dir1/deps/dep1"));
3389            assert_eq!(repo.git_dir_path.as_ref(), Path::new("dir1/deps/dep1/.git"),);
3390        });
3391
3392        let original_scan_id = tree.read_with(cx, |tree, _cx| {
3393            let tree = tree.as_local().unwrap();
3394            tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id
3395        });
3396
3397        std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3398        tree.flush_fs_events(cx).await;
3399
3400        tree.read_with(cx, |tree, _cx| {
3401            let tree = tree.as_local().unwrap();
3402            let new_scan_id = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap().scan_id;
3403            assert_ne!(
3404                original_scan_id, new_scan_id,
3405                "original {original_scan_id}, new {new_scan_id}"
3406            );
3407        });
3408
3409        std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3410        tree.flush_fs_events(cx).await;
3411
3412        tree.read_with(cx, |tree, _cx| {
3413            let tree = tree.as_local().unwrap();
3414
3415            assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3416        });
3417    }
3418
3419    #[test]
3420    fn test_changed_repos() {
3421        fn fake_entry(git_dir_path: impl AsRef<Path>, scan_id: usize) -> GitRepositoryEntry {
3422            GitRepositoryEntry {
3423                repo: Arc::new(Mutex::new(FakeGitRepository::default())),
3424                scan_id,
3425                content_path: git_dir_path.as_ref().parent().unwrap().into(),
3426                git_dir_path: git_dir_path.as_ref().into(),
3427            }
3428        }
3429
3430        let prev_repos: Vec<GitRepositoryEntry> = vec![
3431            fake_entry("/.git", 0),
3432            fake_entry("/a/.git", 0),
3433            fake_entry("/a/b/.git", 0),
3434        ];
3435
3436        let new_repos: Vec<GitRepositoryEntry> = vec![
3437            fake_entry("/a/.git", 1),
3438            fake_entry("/a/b/.git", 0),
3439            fake_entry("/a/c/.git", 0),
3440        ];
3441
3442        let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3443
3444        // Deletion retained
3445        assert!(res
3446            .iter()
3447            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/.git") && repo.scan_id == 0)
3448            .is_some());
3449
3450        // Update retained
3451        assert!(res
3452            .iter()
3453            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/.git") && repo.scan_id == 1)
3454            .is_some());
3455
3456        // Addition retained
3457        assert!(res
3458            .iter()
3459            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/c/.git") && repo.scan_id == 0)
3460            .is_some());
3461
3462        // Nochange, not retained
3463        assert!(res
3464            .iter()
3465            .find(|repo| repo.git_dir_path.as_ref() == Path::new("/a/b/.git") && repo.scan_id == 0)
3466            .is_none());
3467    }
3468
3469    #[gpui::test]
3470    async fn test_write_file(cx: &mut TestAppContext) {
3471        let dir = temp_tree(json!({
3472            ".git": {},
3473            ".gitignore": "ignored-dir\n",
3474            "tracked-dir": {},
3475            "ignored-dir": {}
3476        }));
3477
3478        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3479
3480        let tree = Worktree::local(
3481            client,
3482            dir.path(),
3483            true,
3484            Arc::new(RealFs),
3485            Default::default(),
3486            &mut cx.to_async(),
3487        )
3488        .await
3489        .unwrap();
3490        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3491            .await;
3492        tree.flush_fs_events(cx).await;
3493
3494        tree.update(cx, |tree, cx| {
3495            tree.as_local().unwrap().write_file(
3496                Path::new("tracked-dir/file.txt"),
3497                "hello".into(),
3498                Default::default(),
3499                cx,
3500            )
3501        })
3502        .await
3503        .unwrap();
3504        tree.update(cx, |tree, cx| {
3505            tree.as_local().unwrap().write_file(
3506                Path::new("ignored-dir/file.txt"),
3507                "world".into(),
3508                Default::default(),
3509                cx,
3510            )
3511        })
3512        .await
3513        .unwrap();
3514
3515        tree.read_with(cx, |tree, _| {
3516            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3517            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3518            assert!(!tracked.is_ignored);
3519            assert!(ignored.is_ignored);
3520        });
3521    }
3522
3523    #[gpui::test(iterations = 30)]
3524    async fn test_create_directory(cx: &mut TestAppContext) {
3525        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3526
3527        let fs = FakeFs::new(cx.background());
3528        fs.insert_tree(
3529            "/a",
3530            json!({
3531                "b": {},
3532                "c": {},
3533                "d": {},
3534            }),
3535        )
3536        .await;
3537
3538        let tree = Worktree::local(
3539            client,
3540            "/a".as_ref(),
3541            true,
3542            fs,
3543            Default::default(),
3544            &mut cx.to_async(),
3545        )
3546        .await
3547        .unwrap();
3548
3549        let entry = tree
3550            .update(cx, |tree, cx| {
3551                tree.as_local_mut()
3552                    .unwrap()
3553                    .create_entry("a/e".as_ref(), true, cx)
3554            })
3555            .await
3556            .unwrap();
3557        assert!(entry.is_dir());
3558
3559        cx.foreground().run_until_parked();
3560        tree.read_with(cx, |tree, _| {
3561            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3562        });
3563    }
3564
3565    #[gpui::test(iterations = 100)]
3566    async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
3567        let operations = env::var("OPERATIONS")
3568            .map(|o| o.parse().unwrap())
3569            .unwrap_or(40);
3570        let initial_entries = env::var("INITIAL_ENTRIES")
3571            .map(|o| o.parse().unwrap())
3572            .unwrap_or(20);
3573
3574        let root_dir = Path::new("/test");
3575        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
3576        fs.as_fake().insert_tree(root_dir, json!({})).await;
3577        for _ in 0..initial_entries {
3578            randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3579        }
3580        log::info!("generated initial tree");
3581
3582        let next_entry_id = Arc::new(AtomicUsize::default());
3583        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3584        let worktree = Worktree::local(
3585            client.clone(),
3586            root_dir,
3587            true,
3588            fs.clone(),
3589            next_entry_id.clone(),
3590            &mut cx.to_async(),
3591        )
3592        .await
3593        .unwrap();
3594
3595        worktree
3596            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3597            .await;
3598
3599        // After the initial scan is complete, the `UpdatedEntries` event can
3600        // be used to follow along with all changes to the worktree's snapshot.
3601        worktree.update(cx, |tree, cx| {
3602            let mut paths = tree
3603                .as_local()
3604                .unwrap()
3605                .paths()
3606                .cloned()
3607                .collect::<Vec<_>>();
3608
3609            cx.subscribe(&worktree, move |tree, _, event, _| {
3610                if let Event::UpdatedEntries(changes) = event {
3611                    for (path, change_type) in changes.iter() {
3612                        let path = path.clone();
3613                        let ix = match paths.binary_search(&path) {
3614                            Ok(ix) | Err(ix) => ix,
3615                        };
3616                        match change_type {
3617                            PathChange::Added => {
3618                                assert_ne!(paths.get(ix), Some(&path));
3619                                paths.insert(ix, path);
3620                            }
3621                            PathChange::Removed => {
3622                                assert_eq!(paths.get(ix), Some(&path));
3623                                paths.remove(ix);
3624                            }
3625                            PathChange::Updated => {
3626                                assert_eq!(paths.get(ix), Some(&path));
3627                            }
3628                            PathChange::AddedOrUpdated => {
3629                                if paths[ix] != path {
3630                                    paths.insert(ix, path);
3631                                }
3632                            }
3633                        }
3634                    }
3635                    let new_paths = tree.paths().cloned().collect::<Vec<_>>();
3636                    assert_eq!(paths, new_paths, "incorrect changes: {:?}", changes);
3637                }
3638            })
3639            .detach();
3640        });
3641
3642        let mut snapshots = Vec::new();
3643        let mut mutations_len = operations;
3644        while mutations_len > 1 {
3645            randomly_mutate_tree(&fs, root_dir, 1.0, &mut rng).await;
3646            let buffered_event_count = fs.as_fake().buffered_event_count().await;
3647            if buffered_event_count > 0 && rng.gen_bool(0.3) {
3648                let len = rng.gen_range(0..=buffered_event_count);
3649                log::info!("flushing {} events", len);
3650                fs.as_fake().flush_events(len).await;
3651            } else {
3652                randomly_mutate_tree(&fs, root_dir, 0.6, &mut rng).await;
3653                mutations_len -= 1;
3654            }
3655
3656            cx.foreground().run_until_parked();
3657            if rng.gen_bool(0.2) {
3658                log::info!("storing snapshot {}", snapshots.len());
3659                let snapshot =
3660                    worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3661                snapshots.push(snapshot);
3662            }
3663        }
3664
3665        log::info!("quiescing");
3666        fs.as_fake().flush_events(usize::MAX).await;
3667        cx.foreground().run_until_parked();
3668        let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3669        snapshot.check_invariants();
3670
3671        {
3672            let new_worktree = Worktree::local(
3673                client.clone(),
3674                root_dir,
3675                true,
3676                fs.clone(),
3677                next_entry_id,
3678                &mut cx.to_async(),
3679            )
3680            .await
3681            .unwrap();
3682            new_worktree
3683                .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3684                .await;
3685            let new_snapshot =
3686                new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3687            assert_eq!(snapshot.to_vec(true), new_snapshot.to_vec(true));
3688        }
3689
3690        for (i, mut prev_snapshot) in snapshots.into_iter().enumerate() {
3691            let include_ignored = rng.gen::<bool>();
3692            if !include_ignored {
3693                let mut entries_by_path_edits = Vec::new();
3694                let mut entries_by_id_edits = Vec::new();
3695                for entry in prev_snapshot
3696                    .entries_by_id
3697                    .cursor::<()>()
3698                    .filter(|e| e.is_ignored)
3699                {
3700                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3701                    entries_by_id_edits.push(Edit::Remove(entry.id));
3702                }
3703
3704                prev_snapshot
3705                    .entries_by_path
3706                    .edit(entries_by_path_edits, &());
3707                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3708            }
3709
3710            let update = snapshot.build_update(&prev_snapshot, 0, 0, include_ignored);
3711            prev_snapshot.apply_remote_update(update.clone()).unwrap();
3712            assert_eq!(
3713                prev_snapshot.to_vec(include_ignored),
3714                snapshot.to_vec(include_ignored),
3715                "wrong update for snapshot {i}. update: {:?}",
3716                update
3717            );
3718        }
3719    }
3720
3721    async fn randomly_mutate_tree(
3722        fs: &Arc<dyn Fs>,
3723        root_path: &Path,
3724        insertion_probability: f64,
3725        rng: &mut impl Rng,
3726    ) {
3727        let mut files = Vec::new();
3728        let mut dirs = Vec::new();
3729        for path in fs.as_fake().paths().await {
3730            if path.starts_with(root_path) {
3731                if fs.is_file(&path).await {
3732                    files.push(path);
3733                } else {
3734                    dirs.push(path);
3735                }
3736            }
3737        }
3738
3739        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3740            let path = dirs.choose(rng).unwrap();
3741            let new_path = path.join(gen_name(rng));
3742
3743            if rng.gen() {
3744                log::info!(
3745                    "creating dir {:?}",
3746                    new_path.strip_prefix(root_path).unwrap()
3747                );
3748                fs.create_dir(&new_path).await.unwrap();
3749            } else {
3750                log::info!(
3751                    "creating file {:?}",
3752                    new_path.strip_prefix(root_path).unwrap()
3753                );
3754                fs.create_file(&new_path, Default::default()).await.unwrap();
3755            }
3756        } else if rng.gen_bool(0.05) {
3757            let ignore_dir_path = dirs.choose(rng).unwrap();
3758            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3759
3760            let subdirs = dirs
3761                .iter()
3762                .filter(|d| d.starts_with(&ignore_dir_path))
3763                .cloned()
3764                .collect::<Vec<_>>();
3765            let subfiles = files
3766                .iter()
3767                .filter(|d| d.starts_with(&ignore_dir_path))
3768                .cloned()
3769                .collect::<Vec<_>>();
3770            let files_to_ignore = {
3771                let len = rng.gen_range(0..=subfiles.len());
3772                subfiles.choose_multiple(rng, len)
3773            };
3774            let dirs_to_ignore = {
3775                let len = rng.gen_range(0..subdirs.len());
3776                subdirs.choose_multiple(rng, len)
3777            };
3778
3779            let mut ignore_contents = String::new();
3780            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3781                writeln!(
3782                    ignore_contents,
3783                    "{}",
3784                    path_to_ignore
3785                        .strip_prefix(&ignore_dir_path)
3786                        .unwrap()
3787                        .to_str()
3788                        .unwrap()
3789                )
3790                .unwrap();
3791            }
3792            log::info!(
3793                "creating gitignore {:?} with contents:\n{}",
3794                ignore_path.strip_prefix(&root_path).unwrap(),
3795                ignore_contents
3796            );
3797            fs.save(
3798                &ignore_path,
3799                &ignore_contents.as_str().into(),
3800                Default::default(),
3801            )
3802            .await
3803            .unwrap();
3804        } else {
3805            let old_path = {
3806                let file_path = files.choose(rng);
3807                let dir_path = dirs[1..].choose(rng);
3808                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3809            };
3810
3811            let is_rename = rng.gen();
3812            if is_rename {
3813                let new_path_parent = dirs
3814                    .iter()
3815                    .filter(|d| !d.starts_with(old_path))
3816                    .choose(rng)
3817                    .unwrap();
3818
3819                let overwrite_existing_dir =
3820                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3821                let new_path = if overwrite_existing_dir {
3822                    fs.remove_dir(
3823                        &new_path_parent,
3824                        RemoveOptions {
3825                            recursive: true,
3826                            ignore_if_not_exists: true,
3827                        },
3828                    )
3829                    .await
3830                    .unwrap();
3831                    new_path_parent.to_path_buf()
3832                } else {
3833                    new_path_parent.join(gen_name(rng))
3834                };
3835
3836                log::info!(
3837                    "renaming {:?} to {}{:?}",
3838                    old_path.strip_prefix(&root_path).unwrap(),
3839                    if overwrite_existing_dir {
3840                        "overwrite "
3841                    } else {
3842                        ""
3843                    },
3844                    new_path.strip_prefix(&root_path).unwrap()
3845                );
3846                fs.rename(
3847                    &old_path,
3848                    &new_path,
3849                    fs::RenameOptions {
3850                        overwrite: true,
3851                        ignore_if_exists: true,
3852                    },
3853                )
3854                .await
3855                .unwrap();
3856            } else if fs.is_file(&old_path).await {
3857                log::info!(
3858                    "deleting file {:?}",
3859                    old_path.strip_prefix(&root_path).unwrap()
3860                );
3861                fs.remove_file(old_path, Default::default()).await.unwrap();
3862            } else {
3863                log::info!(
3864                    "deleting dir {:?}",
3865                    old_path.strip_prefix(&root_path).unwrap()
3866                );
3867                fs.remove_dir(
3868                    &old_path,
3869                    RemoveOptions {
3870                        recursive: true,
3871                        ignore_if_not_exists: true,
3872                    },
3873                )
3874                .await
3875                .unwrap();
3876            }
3877        }
3878    }
3879
3880    fn gen_name(rng: &mut impl Rng) -> String {
3881        (0..6)
3882            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3883            .map(char::from)
3884            .collect()
3885    }
3886
3887    impl LocalSnapshot {
3888        fn check_invariants(&self) {
3889            let mut files = self.files(true, 0);
3890            let mut visible_files = self.files(false, 0);
3891            for entry in self.entries_by_path.cursor::<()>() {
3892                if entry.is_file() {
3893                    assert_eq!(files.next().unwrap().inode, entry.inode);
3894                    if !entry.is_ignored {
3895                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3896                    }
3897                }
3898            }
3899            assert!(files.next().is_none());
3900            assert!(visible_files.next().is_none());
3901
3902            let mut bfs_paths = Vec::new();
3903            let mut stack = vec![Path::new("")];
3904            while let Some(path) = stack.pop() {
3905                bfs_paths.push(path);
3906                let ix = stack.len();
3907                for child_entry in self.child_entries(path) {
3908                    stack.insert(ix, &child_entry.path);
3909                }
3910            }
3911
3912            let dfs_paths_via_iter = self
3913                .entries_by_path
3914                .cursor::<()>()
3915                .map(|e| e.path.as_ref())
3916                .collect::<Vec<_>>();
3917            assert_eq!(bfs_paths, dfs_paths_via_iter);
3918
3919            let dfs_paths_via_traversal = self
3920                .entries(true)
3921                .map(|e| e.path.as_ref())
3922                .collect::<Vec<_>>();
3923            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3924
3925            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
3926                let ignore_parent_path =
3927                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
3928                assert!(self.entry_for_path(&ignore_parent_path).is_some());
3929                assert!(self
3930                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3931                    .is_some());
3932            }
3933        }
3934
3935        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3936            let mut paths = Vec::new();
3937            for entry in self.entries_by_path.cursor::<()>() {
3938                if include_ignored || !entry.is_ignored {
3939                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3940                }
3941            }
3942            paths.sort_by(|a, b| a.0.cmp(b.0));
3943            paths
3944        }
3945    }
3946}