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