worktree.rs

   1use crate::{ProjectEntryId, RemoveOptions};
   2
   3use super::{
   4    fs::{self, Fs},
   5    ignore::IgnoreStack,
   6    DiagnosticSummary,
   7};
   8use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   9use anyhow::{anyhow, Context, Result};
  10use client::{proto, Client};
  11use clock::ReplicaId;
  12use collections::{HashMap, VecDeque};
  13use futures::{
  14    channel::{
  15        mpsc::{self, UnboundedSender},
  16        oneshot,
  17    },
  18    Stream, StreamExt,
  19};
  20use fuzzy::CharBag;
  21use gpui::{
  22    executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext,
  23    Task,
  24};
  25use language::{
  26    proto::{deserialize_version, serialize_version},
  27    Buffer, DiagnosticEntry, PointUtf16, Rope,
  28};
  29use lazy_static::lazy_static;
  30use parking_lot::Mutex;
  31use postage::{
  32    prelude::{Sink as _, Stream as _},
  33    watch,
  34};
  35use smol::channel::{self, Sender};
  36use std::{
  37    any::Any,
  38    cmp::{self, Ordering},
  39    convert::TryFrom,
  40    ffi::{OsStr, OsString},
  41    fmt,
  42    future::Future,
  43    ops::{Deref, DerefMut},
  44    os::unix::prelude::{OsStrExt, OsStringExt},
  45    path::{Path, PathBuf},
  46    sync::{atomic::AtomicUsize, Arc},
  47    task::Poll,
  48    time::{Duration, SystemTime},
  49};
  50use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap};
  51use util::{ResultExt, TryFutureExt};
  52
  53lazy_static! {
  54    static ref GITIGNORE: &'static OsStr = OsStr::new(".gitignore");
  55}
  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    background_snapshot: Arc<Mutex<LocalSnapshot>>,
  68    last_scan_state_rx: watch::Receiver<ScanState>,
  69    _background_scanner_task: Option<Task<()>>,
  70    poll_task: Option<Task<()>>,
  71    share: Option<ShareState>,
  72    diagnostics: HashMap<Arc<Path>, Vec<DiagnosticEntry<PointUtf16>>>,
  73    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  74    client: Arc<Client>,
  75    fs: Arc<dyn Fs>,
  76    visible: bool,
  77}
  78
  79pub struct RemoteWorktree {
  80    pub snapshot: Snapshot,
  81    pub(crate) background_snapshot: Arc<Mutex<Snapshot>>,
  82    project_id: u64,
  83    client: Arc<Client>,
  84    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
  85    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
  86    replica_id: ReplicaId,
  87    diagnostic_summaries: TreeMap<PathKey, DiagnosticSummary>,
  88    visible: bool,
  89}
  90
  91#[derive(Clone)]
  92pub struct Snapshot {
  93    id: WorktreeId,
  94    root_name: String,
  95    root_char_bag: CharBag,
  96    entries_by_path: SumTree<Entry>,
  97    entries_by_id: SumTree<PathEntry>,
  98    scan_id: usize,
  99    is_complete: bool,
 100}
 101
 102#[derive(Clone)]
 103pub struct LocalSnapshot {
 104    abs_path: Arc<Path>,
 105    ignores: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 106    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 107    next_entry_id: Arc<AtomicUsize>,
 108    snapshot: Snapshot,
 109}
 110
 111impl Deref for LocalSnapshot {
 112    type Target = Snapshot;
 113
 114    fn deref(&self) -> &Self::Target {
 115        &self.snapshot
 116    }
 117}
 118
 119impl DerefMut for LocalSnapshot {
 120    fn deref_mut(&mut self) -> &mut Self::Target {
 121        &mut self.snapshot
 122    }
 123}
 124
 125#[derive(Clone, Debug)]
 126enum ScanState {
 127    Idle,
 128    /// The worktree is performing its initial scan of the filesystem.
 129    Initializing,
 130    /// The worktree is updating in response to filesystem events.
 131    Updating,
 132    Err(Arc<anyhow::Error>),
 133}
 134
 135struct ShareState {
 136    project_id: u64,
 137    snapshots_tx: watch::Sender<LocalSnapshot>,
 138    _maintain_remote_snapshot: Option<Task<Option<()>>>,
 139}
 140
 141pub enum Event {
 142    UpdatedEntries,
 143}
 144
 145impl Entity for Worktree {
 146    type Event = Event;
 147}
 148
 149impl Worktree {
 150    pub async fn local(
 151        client: Arc<Client>,
 152        path: impl Into<Arc<Path>>,
 153        visible: bool,
 154        fs: Arc<dyn Fs>,
 155        next_entry_id: Arc<AtomicUsize>,
 156        cx: &mut AsyncAppContext,
 157    ) -> Result<ModelHandle<Self>> {
 158        let (tree, scan_states_tx) =
 159            LocalWorktree::new(client, path, visible, fs.clone(), next_entry_id, cx).await?;
 160        tree.update(cx, |tree, cx| {
 161            let tree = tree.as_local_mut().unwrap();
 162            let abs_path = tree.abs_path().clone();
 163            let background_snapshot = tree.background_snapshot.clone();
 164            let background = cx.background().clone();
 165            tree._background_scanner_task = Some(cx.background().spawn(async move {
 166                let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 167                let scanner =
 168                    BackgroundScanner::new(background_snapshot, scan_states_tx, fs, background);
 169                scanner.run(events).await;
 170            }));
 171        });
 172        Ok(tree)
 173    }
 174
 175    pub fn remote(
 176        project_remote_id: u64,
 177        replica_id: ReplicaId,
 178        worktree: proto::WorktreeMetadata,
 179        client: Arc<Client>,
 180        cx: &mut MutableAppContext,
 181    ) -> ModelHandle<Self> {
 182        let remote_id = worktree.id;
 183        let root_char_bag: CharBag = worktree
 184            .root_name
 185            .chars()
 186            .map(|c| c.to_ascii_lowercase())
 187            .collect();
 188        let root_name = worktree.root_name.clone();
 189        let visible = worktree.visible;
 190        let snapshot = Snapshot {
 191            id: WorktreeId(remote_id as usize),
 192            root_name,
 193            root_char_bag,
 194            entries_by_path: Default::default(),
 195            entries_by_id: Default::default(),
 196            scan_id: 0,
 197            is_complete: false,
 198        };
 199
 200        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 201        let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 202        let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 203        let worktree_handle = cx.add_model(|_: &mut ModelContext<Worktree>| {
 204            Worktree::Remote(RemoteWorktree {
 205                project_id: project_remote_id,
 206                replica_id,
 207                snapshot: snapshot.clone(),
 208                background_snapshot: background_snapshot.clone(),
 209                updates_tx: Some(updates_tx),
 210                snapshot_subscriptions: Default::default(),
 211                client: client.clone(),
 212                diagnostic_summaries: Default::default(),
 213                visible,
 214            })
 215        });
 216
 217        cx.background()
 218            .spawn(async move {
 219                while let Some(update) = updates_rx.next().await {
 220                    if let Err(error) = background_snapshot.lock().apply_remote_update(update) {
 221                        log::error!("error applying worktree update: {}", error);
 222                    }
 223                    snapshot_updated_tx.send(()).await.ok();
 224                }
 225            })
 226            .detach();
 227
 228        cx.spawn(|mut cx| {
 229            let this = worktree_handle.downgrade();
 230            async move {
 231                while let Some(_) = snapshot_updated_rx.recv().await {
 232                    if let Some(this) = this.upgrade(&cx) {
 233                        this.update(&mut cx, |this, cx| {
 234                            this.poll_snapshot(cx);
 235                            let this = this.as_remote_mut().unwrap();
 236                            while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 237                                if this.observed_snapshot(*scan_id) {
 238                                    let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 239                                    let _ = tx.send(());
 240                                } else {
 241                                    break;
 242                                }
 243                            }
 244                        });
 245                    } else {
 246                        break;
 247                    }
 248                }
 249            }
 250        })
 251        .detach();
 252
 253        worktree_handle
 254    }
 255
 256    pub fn as_local(&self) -> Option<&LocalWorktree> {
 257        if let Worktree::Local(worktree) = self {
 258            Some(worktree)
 259        } else {
 260            None
 261        }
 262    }
 263
 264    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 265        if let Worktree::Remote(worktree) = self {
 266            Some(worktree)
 267        } else {
 268            None
 269        }
 270    }
 271
 272    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 273        if let Worktree::Local(worktree) = self {
 274            Some(worktree)
 275        } else {
 276            None
 277        }
 278    }
 279
 280    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 281        if let Worktree::Remote(worktree) = self {
 282            Some(worktree)
 283        } else {
 284            None
 285        }
 286    }
 287
 288    pub fn is_local(&self) -> bool {
 289        matches!(self, Worktree::Local(_))
 290    }
 291
 292    pub fn is_remote(&self) -> bool {
 293        !self.is_local()
 294    }
 295
 296    pub fn snapshot(&self) -> Snapshot {
 297        match self {
 298            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 299            Worktree::Remote(worktree) => worktree.snapshot(),
 300        }
 301    }
 302
 303    pub fn scan_id(&self) -> usize {
 304        match self {
 305            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 306            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 307        }
 308    }
 309
 310    pub fn is_visible(&self) -> bool {
 311        match self {
 312            Worktree::Local(worktree) => worktree.visible,
 313            Worktree::Remote(worktree) => worktree.visible,
 314        }
 315    }
 316
 317    pub fn replica_id(&self) -> ReplicaId {
 318        match self {
 319            Worktree::Local(_) => 0,
 320            Worktree::Remote(worktree) => worktree.replica_id,
 321        }
 322    }
 323
 324    pub fn diagnostic_summaries<'a>(
 325        &'a self,
 326    ) -> impl Iterator<Item = (Arc<Path>, DiagnosticSummary)> + 'a {
 327        match self {
 328            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 329            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 330        }
 331        .iter()
 332        .map(|(path, summary)| (path.0.clone(), summary.clone()))
 333    }
 334
 335    fn poll_snapshot(&mut self, cx: &mut ModelContext<Self>) {
 336        match self {
 337            Self::Local(worktree) => worktree.poll_snapshot(cx),
 338            Self::Remote(worktree) => worktree.poll_snapshot(cx),
 339        };
 340    }
 341}
 342
 343impl LocalWorktree {
 344    async fn new(
 345        client: Arc<Client>,
 346        path: impl Into<Arc<Path>>,
 347        visible: bool,
 348        fs: Arc<dyn Fs>,
 349        next_entry_id: Arc<AtomicUsize>,
 350        cx: &mut AsyncAppContext,
 351    ) -> Result<(ModelHandle<Worktree>, UnboundedSender<ScanState>)> {
 352        let abs_path = path.into();
 353        let path: Arc<Path> = Arc::from(Path::new(""));
 354
 355        // After determining whether the root entry is a file or a directory, populate the
 356        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 357        let root_name = abs_path
 358            .file_name()
 359            .map_or(String::new(), |f| f.to_string_lossy().to_string());
 360        let root_char_bag = root_name.chars().map(|c| c.to_ascii_lowercase()).collect();
 361        let metadata = fs
 362            .metadata(&abs_path)
 363            .await
 364            .context("failed to stat worktree path")?;
 365
 366        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 367        let (mut last_scan_state_tx, last_scan_state_rx) =
 368            watch::channel_with(ScanState::Initializing);
 369        let tree = cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 370            let mut snapshot = LocalSnapshot {
 371                abs_path,
 372                ignores: Default::default(),
 373                removed_entry_ids: Default::default(),
 374                next_entry_id,
 375                snapshot: Snapshot {
 376                    id: WorktreeId::from_usize(cx.model_id()),
 377                    root_name: root_name.clone(),
 378                    root_char_bag,
 379                    entries_by_path: Default::default(),
 380                    entries_by_id: Default::default(),
 381                    scan_id: 0,
 382                    is_complete: true,
 383                },
 384            };
 385            if let Some(metadata) = metadata {
 386                let entry = Entry::new(
 387                    path.into(),
 388                    &metadata,
 389                    &snapshot.next_entry_id,
 390                    snapshot.root_char_bag,
 391                );
 392                snapshot.insert_entry(entry, fs.as_ref());
 393            }
 394
 395            let tree = Self {
 396                snapshot: snapshot.clone(),
 397                background_snapshot: Arc::new(Mutex::new(snapshot)),
 398                last_scan_state_rx,
 399                _background_scanner_task: None,
 400                share: None,
 401                poll_task: None,
 402                diagnostics: Default::default(),
 403                diagnostic_summaries: Default::default(),
 404                client,
 405                fs,
 406                visible,
 407            };
 408
 409            cx.spawn_weak(|this, mut cx| async move {
 410                while let Some(scan_state) = scan_states_rx.next().await {
 411                    if let Some(this) = this.upgrade(&cx) {
 412                        last_scan_state_tx.blocking_send(scan_state).ok();
 413                        this.update(&mut cx, |this, cx| {
 414                            this.poll_snapshot(cx);
 415                            this.as_local_mut().unwrap().broadcast_snapshot()
 416                        });
 417                    } else {
 418                        break;
 419                    }
 420                }
 421            })
 422            .detach();
 423
 424            Worktree::Local(tree)
 425        });
 426
 427        Ok((tree, scan_states_tx))
 428    }
 429
 430    pub fn contains_abs_path(&self, path: &Path) -> bool {
 431        path.starts_with(&self.abs_path)
 432    }
 433
 434    fn absolutize(&self, path: &Path) -> PathBuf {
 435        if path.file_name().is_some() {
 436            self.abs_path.join(path)
 437        } else {
 438            self.abs_path.to_path_buf()
 439        }
 440    }
 441
 442    pub(crate) fn load_buffer(
 443        &mut self,
 444        path: &Path,
 445        cx: &mut ModelContext<Worktree>,
 446    ) -> Task<Result<ModelHandle<Buffer>>> {
 447        let path = Arc::from(path);
 448        cx.spawn(move |this, mut cx| async move {
 449            let (file, contents) = this
 450                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 451                .await?;
 452            Ok(cx.add_model(|cx| Buffer::from_file(0, contents, Arc::new(file), cx)))
 453        })
 454    }
 455
 456    pub fn diagnostics_for_path(&self, path: &Path) -> Option<Vec<DiagnosticEntry<PointUtf16>>> {
 457        self.diagnostics.get(path).cloned()
 458    }
 459
 460    pub fn update_diagnostics(
 461        &mut self,
 462        language_server_id: usize,
 463        worktree_path: Arc<Path>,
 464        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
 465        _: &mut ModelContext<Worktree>,
 466    ) -> Result<bool> {
 467        self.diagnostics.remove(&worktree_path);
 468        let old_summary = self
 469            .diagnostic_summaries
 470            .remove(&PathKey(worktree_path.clone()))
 471            .unwrap_or_default();
 472        let new_summary = DiagnosticSummary::new(language_server_id, &diagnostics);
 473        if !new_summary.is_empty() {
 474            self.diagnostic_summaries
 475                .insert(PathKey(worktree_path.clone()), new_summary);
 476            self.diagnostics.insert(worktree_path.clone(), diagnostics);
 477        }
 478
 479        let updated = !old_summary.is_empty() || !new_summary.is_empty();
 480        if updated {
 481            if let Some(share) = self.share.as_ref() {
 482                self.client
 483                    .send(proto::UpdateDiagnosticSummary {
 484                        project_id: share.project_id,
 485                        worktree_id: self.id().to_proto(),
 486                        summary: Some(proto::DiagnosticSummary {
 487                            path: worktree_path.to_string_lossy().to_string(),
 488                            language_server_id: language_server_id as u64,
 489                            error_count: new_summary.error_count as u32,
 490                            warning_count: new_summary.warning_count as u32,
 491                        }),
 492                    })
 493                    .log_err();
 494            }
 495        }
 496
 497        Ok(updated)
 498    }
 499
 500    fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
 501        match self.scan_state() {
 502            ScanState::Idle => {
 503                self.snapshot = self.background_snapshot.lock().clone();
 504                self.poll_task.take();
 505                cx.emit(Event::UpdatedEntries);
 506            }
 507            ScanState::Initializing => {
 508                self.snapshot = self.background_snapshot.lock().clone();
 509                if self.poll_task.is_none() {
 510                    let is_fake_fs = self.fs.is_fake();
 511                    self.poll_task = Some(cx.spawn_weak(|this, mut cx| async move {
 512                        if is_fake_fs {
 513                            #[cfg(any(test, feature = "test-support"))]
 514                            cx.background().simulate_random_delay().await;
 515                        } else {
 516                            smol::Timer::after(Duration::from_millis(100)).await;
 517                        }
 518                        if let Some(this) = this.upgrade(&cx) {
 519                            this.update(&mut cx, |this, cx| {
 520                                this.as_local_mut().unwrap().poll_task = None;
 521                                this.poll_snapshot(cx);
 522                            });
 523                        }
 524                    }));
 525                }
 526                cx.emit(Event::UpdatedEntries);
 527            }
 528            ScanState::Updating => {}
 529            ScanState::Err(_) => {}
 530        }
 531        cx.notify();
 532    }
 533
 534    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 535        let mut scan_state_rx = self.last_scan_state_rx.clone();
 536        async move {
 537            let mut scan_state = Some(scan_state_rx.borrow().clone());
 538            while let Some(ScanState::Initializing | ScanState::Updating) = scan_state {
 539                scan_state = scan_state_rx.recv().await;
 540            }
 541        }
 542    }
 543
 544    fn scan_state(&self) -> ScanState {
 545        self.last_scan_state_rx.borrow().clone()
 546    }
 547
 548    pub fn snapshot(&self) -> LocalSnapshot {
 549        self.snapshot.clone()
 550    }
 551
 552    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 553        proto::WorktreeMetadata {
 554            id: self.id().to_proto(),
 555            root_name: self.root_name().to_string(),
 556            visible: self.visible,
 557        }
 558    }
 559
 560    fn load(&self, path: &Path, cx: &mut ModelContext<Worktree>) -> Task<Result<(File, String)>> {
 561        let handle = cx.handle();
 562        let path = Arc::from(path);
 563        let abs_path = self.absolutize(&path);
 564        let fs = self.fs.clone();
 565        cx.spawn(|this, mut cx| async move {
 566            let text = fs.load(&abs_path).await?;
 567            // Eagerly populate the snapshot with an updated entry for the loaded file
 568            let entry = this
 569                .update(&mut cx, |this, cx| {
 570                    this.as_local()
 571                        .unwrap()
 572                        .refresh_entry(path, abs_path, None, cx)
 573                })
 574                .await?;
 575            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 576            Ok((
 577                File {
 578                    entry_id: Some(entry.id),
 579                    worktree: handle,
 580                    path: entry.path,
 581                    mtime: entry.mtime,
 582                    is_local: true,
 583                },
 584                text,
 585            ))
 586        })
 587    }
 588
 589    pub fn save_buffer_as(
 590        &self,
 591        buffer_handle: ModelHandle<Buffer>,
 592        path: impl Into<Arc<Path>>,
 593        cx: &mut ModelContext<Worktree>,
 594    ) -> Task<Result<()>> {
 595        let buffer = buffer_handle.read(cx);
 596        let text = buffer.as_rope().clone();
 597        let fingerprint = text.fingerprint();
 598        let version = buffer.version();
 599        let save = self.write_file(path, text, cx);
 600        let handle = cx.handle();
 601        cx.as_mut().spawn(|mut cx| async move {
 602            let entry = save.await?;
 603            let file = File {
 604                entry_id: Some(entry.id),
 605                worktree: handle,
 606                path: entry.path,
 607                mtime: entry.mtime,
 608                is_local: true,
 609            };
 610
 611            buffer_handle.update(&mut cx, |buffer, cx| {
 612                buffer.did_save(version, fingerprint, file.mtime, Some(Arc::new(file)), cx);
 613            });
 614
 615            Ok(())
 616        })
 617    }
 618
 619    pub fn create_entry(
 620        &self,
 621        path: impl Into<Arc<Path>>,
 622        is_dir: bool,
 623        cx: &mut ModelContext<Worktree>,
 624    ) -> Task<Result<Entry>> {
 625        self.write_entry_internal(
 626            path,
 627            if is_dir {
 628                None
 629            } else {
 630                Some(Default::default())
 631            },
 632            cx,
 633        )
 634    }
 635
 636    pub fn write_file(
 637        &self,
 638        path: impl Into<Arc<Path>>,
 639        text: Rope,
 640        cx: &mut ModelContext<Worktree>,
 641    ) -> Task<Result<Entry>> {
 642        self.write_entry_internal(path, Some(text), cx)
 643    }
 644
 645    pub fn delete_entry(
 646        &self,
 647        entry_id: ProjectEntryId,
 648        cx: &mut ModelContext<Worktree>,
 649    ) -> Option<Task<Result<()>>> {
 650        let entry = self.entry_for_id(entry_id)?.clone();
 651        let abs_path = self.absolutize(&entry.path);
 652        let delete = cx.background().spawn({
 653            let fs = self.fs.clone();
 654            let abs_path = abs_path.clone();
 655            async move {
 656                if entry.is_file() {
 657                    fs.remove_file(&abs_path, Default::default()).await
 658                } else {
 659                    fs.remove_dir(
 660                        &abs_path,
 661                        RemoveOptions {
 662                            recursive: true,
 663                            ignore_if_not_exists: false,
 664                        },
 665                    )
 666                    .await
 667                }
 668            }
 669        });
 670
 671        Some(cx.spawn(|this, mut cx| async move {
 672            delete.await?;
 673            this.update(&mut cx, |this, cx| {
 674                let this = this.as_local_mut().unwrap();
 675                {
 676                    let mut snapshot = this.background_snapshot.lock();
 677                    snapshot.delete_entry(entry_id);
 678                }
 679                this.poll_snapshot(cx);
 680                this.broadcast_snapshot();
 681            });
 682            Ok(())
 683        }))
 684    }
 685
 686    pub fn rename_entry(
 687        &self,
 688        entry_id: ProjectEntryId,
 689        new_path: impl Into<Arc<Path>>,
 690        cx: &mut ModelContext<Worktree>,
 691    ) -> Option<Task<Result<Entry>>> {
 692        let old_path = self.entry_for_id(entry_id)?.path.clone();
 693        let new_path = new_path.into();
 694        let abs_old_path = self.absolutize(&old_path);
 695        let abs_new_path = self.absolutize(&new_path);
 696        let rename = cx.background().spawn({
 697            let fs = self.fs.clone();
 698            let abs_new_path = abs_new_path.clone();
 699            async move {
 700                fs.rename(&abs_old_path, &abs_new_path, Default::default())
 701                    .await
 702            }
 703        });
 704
 705        Some(cx.spawn(|this, mut cx| async move {
 706            rename.await?;
 707            let entry = this
 708                .update(&mut cx, |this, cx| {
 709                    this.as_local_mut().unwrap().refresh_entry(
 710                        new_path.clone(),
 711                        abs_new_path,
 712                        Some(old_path),
 713                        cx,
 714                    )
 715                })
 716                .await?;
 717            this.update(&mut cx, |this, cx| {
 718                let this = this.as_local_mut().unwrap();
 719                this.poll_snapshot(cx);
 720                this.broadcast_snapshot();
 721            });
 722            Ok(entry)
 723        }))
 724    }
 725
 726    pub fn copy_entry(
 727        &self,
 728        entry_id: ProjectEntryId,
 729        new_path: impl Into<Arc<Path>>,
 730        cx: &mut ModelContext<Worktree>,
 731    ) -> Option<Task<Result<Entry>>> {
 732        let old_path = self.entry_for_id(entry_id)?.path.clone();
 733        let new_path = new_path.into();
 734        let abs_old_path = self.absolutize(&old_path);
 735        let abs_new_path = self.absolutize(&new_path);
 736        let copy = cx.background().spawn({
 737            let fs = self.fs.clone();
 738            let abs_new_path = abs_new_path.clone();
 739            async move {
 740                fs.copy(&abs_old_path, &abs_new_path, Default::default())
 741                    .await
 742            }
 743        });
 744
 745        Some(cx.spawn(|this, mut cx| async move {
 746            copy.await?;
 747            let entry = this
 748                .update(&mut cx, |this, cx| {
 749                    this.as_local_mut().unwrap().refresh_entry(
 750                        new_path.clone(),
 751                        abs_new_path,
 752                        None,
 753                        cx,
 754                    )
 755                })
 756                .await?;
 757            this.update(&mut cx, |this, cx| {
 758                let this = this.as_local_mut().unwrap();
 759                this.poll_snapshot(cx);
 760                this.broadcast_snapshot()
 761            });
 762            Ok(entry)
 763        }))
 764    }
 765
 766    fn write_entry_internal(
 767        &self,
 768        path: impl Into<Arc<Path>>,
 769        text_if_file: Option<Rope>,
 770        cx: &mut ModelContext<Worktree>,
 771    ) -> Task<Result<Entry>> {
 772        let path = path.into();
 773        let abs_path = self.absolutize(&path);
 774        let write = cx.background().spawn({
 775            let fs = self.fs.clone();
 776            let abs_path = abs_path.clone();
 777            async move {
 778                if let Some(text) = text_if_file {
 779                    fs.save(&abs_path, &text).await
 780                } else {
 781                    fs.create_dir(&abs_path).await
 782                }
 783            }
 784        });
 785
 786        cx.spawn(|this, mut cx| async move {
 787            write.await?;
 788            let entry = this
 789                .update(&mut cx, |this, cx| {
 790                    this.as_local_mut()
 791                        .unwrap()
 792                        .refresh_entry(path, abs_path, None, cx)
 793                })
 794                .await?;
 795            this.update(&mut cx, |this, cx| {
 796                let this = this.as_local_mut().unwrap();
 797                this.poll_snapshot(cx);
 798                this.broadcast_snapshot();
 799            });
 800            Ok(entry)
 801        })
 802    }
 803
 804    fn refresh_entry(
 805        &self,
 806        path: Arc<Path>,
 807        abs_path: PathBuf,
 808        old_path: Option<Arc<Path>>,
 809        cx: &mut ModelContext<Worktree>,
 810    ) -> Task<Result<Entry>> {
 811        let fs = self.fs.clone();
 812        let root_char_bag;
 813        let next_entry_id;
 814        {
 815            let snapshot = self.background_snapshot.lock();
 816            root_char_bag = snapshot.root_char_bag;
 817            next_entry_id = snapshot.next_entry_id.clone();
 818        }
 819        cx.spawn_weak(|this, mut cx| async move {
 820            let mut entry = Entry::new(
 821                path.clone(),
 822                &fs.metadata(&abs_path)
 823                    .await?
 824                    .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
 825                &next_entry_id,
 826                root_char_bag,
 827            );
 828
 829            let this = this
 830                .upgrade(&cx)
 831                .ok_or_else(|| anyhow!("worktree was dropped"))?;
 832            this.update(&mut cx, |this, cx| {
 833                let this = this.as_local_mut().unwrap();
 834                let inserted_entry;
 835                {
 836                    let mut snapshot = this.background_snapshot.lock();
 837                    entry.is_ignored = snapshot
 838                        .ignore_stack_for_path(&path, entry.is_dir())
 839                        .is_path_ignored(&path, entry.is_dir());
 840                    if let Some(old_path) = old_path {
 841                        snapshot.remove_path(&old_path);
 842                    }
 843                    inserted_entry = snapshot.insert_entry(entry, fs.as_ref());
 844                    snapshot.scan_id += 1;
 845                }
 846                this.poll_snapshot(cx);
 847                this.broadcast_snapshot();
 848                Ok(inserted_entry)
 849            })
 850        })
 851    }
 852
 853    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 854        let (share_tx, share_rx) = oneshot::channel();
 855
 856        if self.share.is_some() {
 857            let _ = share_tx.send(Ok(()));
 858        } else {
 859            let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
 860            let rpc = self.client.clone();
 861            let worktree_id = cx.model_id() as u64;
 862            let maintain_remote_snapshot = cx.background().spawn({
 863                let rpc = rpc.clone();
 864                let diagnostic_summaries = self.diagnostic_summaries.clone();
 865                async move {
 866                    let mut prev_snapshot = match snapshots_rx.recv().await {
 867                        Some(snapshot) => {
 868                            let update = proto::UpdateWorktree {
 869                                project_id,
 870                                worktree_id,
 871                                root_name: snapshot.root_name().to_string(),
 872                                updated_entries: snapshot
 873                                    .entries_by_path
 874                                    .iter()
 875                                    .map(Into::into)
 876                                    .collect(),
 877                                removed_entries: Default::default(),
 878                                scan_id: snapshot.scan_id as u64,
 879                                is_last_update: true,
 880                            };
 881                            if let Err(error) = send_worktree_update(&rpc, update).await {
 882                                let _ = share_tx.send(Err(error));
 883                                return Err(anyhow!("failed to send initial update worktree"));
 884                            } else {
 885                                let _ = share_tx.send(Ok(()));
 886                                snapshot
 887                            }
 888                        }
 889                        None => {
 890                            share_tx
 891                                .send(Err(anyhow!("worktree dropped before share completed")))
 892                                .ok();
 893                            return Err(anyhow!("failed to send initial update worktree"));
 894                        }
 895                    };
 896
 897                    for (path, summary) in diagnostic_summaries.iter() {
 898                        rpc.send(proto::UpdateDiagnosticSummary {
 899                            project_id,
 900                            worktree_id,
 901                            summary: Some(summary.to_proto(&path.0)),
 902                        })?;
 903                    }
 904
 905                    while let Some(snapshot) = snapshots_rx.recv().await {
 906                        send_worktree_update(
 907                            &rpc,
 908                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, true),
 909                        )
 910                        .await?;
 911                        prev_snapshot = snapshot;
 912                    }
 913
 914                    Ok::<_, anyhow::Error>(())
 915                }
 916                .log_err()
 917            });
 918            self.share = Some(ShareState {
 919                project_id,
 920                snapshots_tx,
 921                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
 922            });
 923        }
 924
 925        cx.foreground().spawn(async move {
 926            share_rx
 927                .await
 928                .unwrap_or_else(|_| Err(anyhow!("share ended")))
 929        })
 930    }
 931
 932    pub fn unshare(&mut self) {
 933        self.share.take();
 934    }
 935
 936    pub fn is_shared(&self) -> bool {
 937        self.share.is_some()
 938    }
 939
 940    fn broadcast_snapshot(&mut self) {
 941        if matches!(self.scan_state(), ScanState::Idle) {
 942            let snapshot = self.snapshot();
 943            if let Some(share) = self.share.as_mut() {
 944                *share.snapshots_tx.borrow_mut() = snapshot;
 945            }
 946        }
 947    }
 948}
 949
 950impl RemoteWorktree {
 951    fn snapshot(&self) -> Snapshot {
 952        self.snapshot.clone()
 953    }
 954
 955    fn poll_snapshot(&mut self, cx: &mut ModelContext<Worktree>) {
 956        self.snapshot = self.background_snapshot.lock().clone();
 957        cx.emit(Event::UpdatedEntries);
 958        cx.notify();
 959    }
 960
 961    pub fn disconnected_from_host(&mut self) {
 962        self.updates_tx.take();
 963        self.snapshot_subscriptions.clear();
 964    }
 965
 966    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
 967        if let Some(updates_tx) = &self.updates_tx {
 968            updates_tx
 969                .unbounded_send(update)
 970                .expect("consumer runs to completion");
 971        }
 972    }
 973
 974    fn observed_snapshot(&self, scan_id: usize) -> bool {
 975        self.scan_id > scan_id || (self.scan_id == scan_id && self.is_complete)
 976    }
 977
 978    fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = ()> {
 979        let (tx, rx) = oneshot::channel();
 980        if self.observed_snapshot(scan_id) {
 981            let _ = tx.send(());
 982        } else {
 983            match self
 984                .snapshot_subscriptions
 985                .binary_search_by_key(&scan_id, |probe| probe.0)
 986            {
 987                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
 988            }
 989        }
 990
 991        async move {
 992            let _ = rx.await;
 993        }
 994    }
 995
 996    pub fn update_diagnostic_summary(
 997        &mut self,
 998        path: Arc<Path>,
 999        summary: &proto::DiagnosticSummary,
1000    ) {
1001        let summary = DiagnosticSummary {
1002            language_server_id: summary.language_server_id as usize,
1003            error_count: summary.error_count as usize,
1004            warning_count: summary.warning_count as usize,
1005        };
1006        if summary.is_empty() {
1007            self.diagnostic_summaries.remove(&PathKey(path.clone()));
1008        } else {
1009            self.diagnostic_summaries
1010                .insert(PathKey(path.clone()), summary);
1011        }
1012    }
1013
1014    pub fn insert_entry(
1015        &mut self,
1016        entry: proto::Entry,
1017        scan_id: usize,
1018        cx: &mut ModelContext<Worktree>,
1019    ) -> Task<Result<Entry>> {
1020        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1021        cx.spawn(|this, mut cx| async move {
1022            wait_for_snapshot.await;
1023            this.update(&mut cx, |worktree, _| {
1024                let worktree = worktree.as_remote_mut().unwrap();
1025                let mut snapshot = worktree.background_snapshot.lock();
1026                let entry = snapshot.insert_entry(entry);
1027                worktree.snapshot = snapshot.clone();
1028                entry
1029            })
1030        })
1031    }
1032
1033    pub(crate) fn delete_entry(
1034        &mut self,
1035        id: ProjectEntryId,
1036        scan_id: usize,
1037        cx: &mut ModelContext<Worktree>,
1038    ) -> Task<Result<()>> {
1039        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1040        cx.spawn(|this, mut cx| async move {
1041            wait_for_snapshot.await;
1042            this.update(&mut cx, |worktree, _| {
1043                let worktree = worktree.as_remote_mut().unwrap();
1044                let mut snapshot = worktree.background_snapshot.lock();
1045                snapshot.delete_entry(id);
1046                worktree.snapshot = snapshot.clone();
1047            });
1048            Ok(())
1049        })
1050    }
1051}
1052
1053impl Snapshot {
1054    pub fn id(&self) -> WorktreeId {
1055        self.id
1056    }
1057
1058    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1059        self.entries_by_id.get(&entry_id, &()).is_some()
1060    }
1061
1062    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1063        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1064        let old_entry = self.entries_by_id.insert_or_replace(
1065            PathEntry {
1066                id: entry.id,
1067                path: entry.path.clone(),
1068                is_ignored: entry.is_ignored,
1069                scan_id: 0,
1070            },
1071            &(),
1072        );
1073        if let Some(old_entry) = old_entry {
1074            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1075        }
1076        self.entries_by_path.insert_or_replace(entry.clone(), &());
1077        Ok(entry)
1078    }
1079
1080    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1081        if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1082            self.entries_by_path = {
1083                let mut cursor = self.entries_by_path.cursor();
1084                let mut new_entries_by_path =
1085                    cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1086                while let Some(entry) = cursor.item() {
1087                    if entry.path.starts_with(&removed_entry.path) {
1088                        self.entries_by_id.remove(&entry.id, &());
1089                        cursor.next(&());
1090                    } else {
1091                        break;
1092                    }
1093                }
1094                new_entries_by_path.push_tree(cursor.suffix(&()), &());
1095                new_entries_by_path
1096            };
1097
1098            true
1099        } else {
1100            false
1101        }
1102    }
1103
1104    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1105        let mut entries_by_path_edits = Vec::new();
1106        let mut entries_by_id_edits = Vec::new();
1107        for entry_id in update.removed_entries {
1108            let entry = self
1109                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1110                .ok_or_else(|| anyhow!("unknown entry {}", entry_id))?;
1111            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1112            entries_by_id_edits.push(Edit::Remove(entry.id));
1113        }
1114
1115        for entry in update.updated_entries {
1116            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1117            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1118                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1119            }
1120            entries_by_id_edits.push(Edit::Insert(PathEntry {
1121                id: entry.id,
1122                path: entry.path.clone(),
1123                is_ignored: entry.is_ignored,
1124                scan_id: 0,
1125            }));
1126            entries_by_path_edits.push(Edit::Insert(entry));
1127        }
1128
1129        self.entries_by_path.edit(entries_by_path_edits, &());
1130        self.entries_by_id.edit(entries_by_id_edits, &());
1131        self.scan_id = update.scan_id as usize;
1132        self.is_complete = update.is_last_update;
1133
1134        Ok(())
1135    }
1136
1137    pub fn file_count(&self) -> usize {
1138        self.entries_by_path.summary().file_count
1139    }
1140
1141    pub fn visible_file_count(&self) -> usize {
1142        self.entries_by_path.summary().visible_file_count
1143    }
1144
1145    fn traverse_from_offset(
1146        &self,
1147        include_dirs: bool,
1148        include_ignored: bool,
1149        start_offset: usize,
1150    ) -> Traversal {
1151        let mut cursor = self.entries_by_path.cursor();
1152        cursor.seek(
1153            &TraversalTarget::Count {
1154                count: start_offset,
1155                include_dirs,
1156                include_ignored,
1157            },
1158            Bias::Right,
1159            &(),
1160        );
1161        Traversal {
1162            cursor,
1163            include_dirs,
1164            include_ignored,
1165        }
1166    }
1167
1168    fn traverse_from_path(
1169        &self,
1170        include_dirs: bool,
1171        include_ignored: bool,
1172        path: &Path,
1173    ) -> Traversal {
1174        let mut cursor = self.entries_by_path.cursor();
1175        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1176        Traversal {
1177            cursor,
1178            include_dirs,
1179            include_ignored,
1180        }
1181    }
1182
1183    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1184        self.traverse_from_offset(false, include_ignored, start)
1185    }
1186
1187    pub fn entries(&self, include_ignored: bool) -> Traversal {
1188        self.traverse_from_offset(true, include_ignored, 0)
1189    }
1190
1191    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1192        let empty_path = Path::new("");
1193        self.entries_by_path
1194            .cursor::<()>()
1195            .filter(move |entry| entry.path.as_ref() != empty_path)
1196            .map(|entry| &entry.path)
1197    }
1198
1199    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1200        let mut cursor = self.entries_by_path.cursor();
1201        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1202        let traversal = Traversal {
1203            cursor,
1204            include_dirs: true,
1205            include_ignored: true,
1206        };
1207        ChildEntriesIter {
1208            traversal,
1209            parent_path,
1210        }
1211    }
1212
1213    pub fn root_entry(&self) -> Option<&Entry> {
1214        self.entry_for_path("")
1215    }
1216
1217    pub fn root_name(&self) -> &str {
1218        &self.root_name
1219    }
1220
1221    pub fn scan_id(&self) -> usize {
1222        self.scan_id
1223    }
1224
1225    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1226        let path = path.as_ref();
1227        self.traverse_from_path(true, true, path)
1228            .entry()
1229            .and_then(|entry| {
1230                if entry.path.as_ref() == path {
1231                    Some(entry)
1232                } else {
1233                    None
1234                }
1235            })
1236    }
1237
1238    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1239        let entry = self.entries_by_id.get(&id, &())?;
1240        self.entry_for_path(&entry.path)
1241    }
1242
1243    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1244        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1245    }
1246}
1247
1248impl LocalSnapshot {
1249    pub fn abs_path(&self) -> &Arc<Path> {
1250        &self.abs_path
1251    }
1252
1253    #[cfg(test)]
1254    pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1255        let root_name = self.root_name.clone();
1256        proto::UpdateWorktree {
1257            project_id,
1258            worktree_id: self.id().to_proto(),
1259            root_name,
1260            updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1261            removed_entries: Default::default(),
1262            scan_id: self.scan_id as u64,
1263            is_last_update: true,
1264        }
1265    }
1266
1267    pub(crate) fn build_update(
1268        &self,
1269        other: &Self,
1270        project_id: u64,
1271        worktree_id: u64,
1272        include_ignored: bool,
1273    ) -> proto::UpdateWorktree {
1274        let mut updated_entries = Vec::new();
1275        let mut removed_entries = Vec::new();
1276        let mut self_entries = self
1277            .entries_by_id
1278            .cursor::<()>()
1279            .filter(|e| include_ignored || !e.is_ignored)
1280            .peekable();
1281        let mut other_entries = other
1282            .entries_by_id
1283            .cursor::<()>()
1284            .filter(|e| include_ignored || !e.is_ignored)
1285            .peekable();
1286        loop {
1287            match (self_entries.peek(), other_entries.peek()) {
1288                (Some(self_entry), Some(other_entry)) => {
1289                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1290                        Ordering::Less => {
1291                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1292                            updated_entries.push(entry);
1293                            self_entries.next();
1294                        }
1295                        Ordering::Equal => {
1296                            if self_entry.scan_id != other_entry.scan_id {
1297                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1298                                updated_entries.push(entry);
1299                            }
1300
1301                            self_entries.next();
1302                            other_entries.next();
1303                        }
1304                        Ordering::Greater => {
1305                            removed_entries.push(other_entry.id.to_proto());
1306                            other_entries.next();
1307                        }
1308                    }
1309                }
1310                (Some(self_entry), None) => {
1311                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1312                    updated_entries.push(entry);
1313                    self_entries.next();
1314                }
1315                (None, Some(other_entry)) => {
1316                    removed_entries.push(other_entry.id.to_proto());
1317                    other_entries.next();
1318                }
1319                (None, None) => break,
1320            }
1321        }
1322
1323        proto::UpdateWorktree {
1324            project_id,
1325            worktree_id,
1326            root_name: self.root_name().to_string(),
1327            updated_entries,
1328            removed_entries,
1329            scan_id: self.scan_id as u64,
1330            is_last_update: true,
1331        }
1332    }
1333
1334    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1335        if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1336            let abs_path = self.abs_path.join(&entry.path);
1337            match build_gitignore(&abs_path, fs) {
1338                Ok(ignore) => {
1339                    let ignore_dir_path = entry.path.parent().unwrap();
1340                    self.ignores
1341                        .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1342                }
1343                Err(error) => {
1344                    log::error!(
1345                        "error loading .gitignore file {:?} - {:?}",
1346                        &entry.path,
1347                        error
1348                    );
1349                }
1350            }
1351        }
1352
1353        self.reuse_entry_id(&mut entry);
1354        self.entries_by_path.insert_or_replace(entry.clone(), &());
1355        let scan_id = self.scan_id;
1356        self.entries_by_id.insert_or_replace(
1357            PathEntry {
1358                id: entry.id,
1359                path: entry.path.clone(),
1360                is_ignored: entry.is_ignored,
1361                scan_id,
1362            },
1363            &(),
1364        );
1365        entry
1366    }
1367
1368    fn populate_dir(
1369        &mut self,
1370        parent_path: Arc<Path>,
1371        entries: impl IntoIterator<Item = Entry>,
1372        ignore: Option<Arc<Gitignore>>,
1373    ) {
1374        let mut parent_entry = if let Some(parent_entry) =
1375            self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1376        {
1377            parent_entry.clone()
1378        } else {
1379            log::warn!(
1380                "populating a directory {:?} that has been removed",
1381                parent_path
1382            );
1383            return;
1384        };
1385
1386        if let Some(ignore) = ignore {
1387            self.ignores.insert(parent_path, (ignore, self.scan_id));
1388        }
1389        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1390            parent_entry.kind = EntryKind::Dir;
1391        } else {
1392            unreachable!();
1393        }
1394
1395        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1396        let mut entries_by_id_edits = Vec::new();
1397
1398        for mut entry in entries {
1399            self.reuse_entry_id(&mut entry);
1400            entries_by_id_edits.push(Edit::Insert(PathEntry {
1401                id: entry.id,
1402                path: entry.path.clone(),
1403                is_ignored: entry.is_ignored,
1404                scan_id: self.scan_id,
1405            }));
1406            entries_by_path_edits.push(Edit::Insert(entry));
1407        }
1408
1409        self.entries_by_path.edit(entries_by_path_edits, &());
1410        self.entries_by_id.edit(entries_by_id_edits, &());
1411    }
1412
1413    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1414        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1415            entry.id = removed_entry_id;
1416        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1417            entry.id = existing_entry.id;
1418        }
1419    }
1420
1421    fn remove_path(&mut self, path: &Path) {
1422        let mut new_entries;
1423        let removed_entries;
1424        {
1425            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1426            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1427            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1428            new_entries.push_tree(cursor.suffix(&()), &());
1429        }
1430        self.entries_by_path = new_entries;
1431
1432        let mut entries_by_id_edits = Vec::new();
1433        for entry in removed_entries.cursor::<()>() {
1434            let removed_entry_id = self
1435                .removed_entry_ids
1436                .entry(entry.inode)
1437                .or_insert(entry.id);
1438            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1439            entries_by_id_edits.push(Edit::Remove(entry.id));
1440        }
1441        self.entries_by_id.edit(entries_by_id_edits, &());
1442
1443        if path.file_name() == Some(&GITIGNORE) {
1444            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1445                *scan_id = self.snapshot.scan_id;
1446            }
1447        }
1448    }
1449
1450    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1451        let mut new_ignores = Vec::new();
1452        for ancestor in path.ancestors().skip(1) {
1453            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1454                new_ignores.push((ancestor, Some(ignore.clone())));
1455            } else {
1456                new_ignores.push((ancestor, None));
1457            }
1458        }
1459
1460        let mut ignore_stack = IgnoreStack::none();
1461        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1462            if ignore_stack.is_path_ignored(&parent_path, true) {
1463                ignore_stack = IgnoreStack::all();
1464                break;
1465            } else if let Some(ignore) = ignore {
1466                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1467            }
1468        }
1469
1470        if ignore_stack.is_path_ignored(path, is_dir) {
1471            ignore_stack = IgnoreStack::all();
1472        }
1473
1474        ignore_stack
1475    }
1476}
1477
1478fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1479    let contents = smol::block_on(fs.load(&abs_path))?;
1480    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1481    let mut builder = GitignoreBuilder::new(parent);
1482    for line in contents.lines() {
1483        builder.add_line(Some(abs_path.into()), line)?;
1484    }
1485    Ok(builder.build()?)
1486}
1487
1488impl WorktreeId {
1489    pub fn from_usize(handle_id: usize) -> Self {
1490        Self(handle_id)
1491    }
1492
1493    pub(crate) fn from_proto(id: u64) -> Self {
1494        Self(id as usize)
1495    }
1496
1497    pub fn to_proto(&self) -> u64 {
1498        self.0 as u64
1499    }
1500
1501    pub fn to_usize(&self) -> usize {
1502        self.0
1503    }
1504}
1505
1506impl fmt::Display for WorktreeId {
1507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1508        self.0.fmt(f)
1509    }
1510}
1511
1512impl Deref for Worktree {
1513    type Target = Snapshot;
1514
1515    fn deref(&self) -> &Self::Target {
1516        match self {
1517            Worktree::Local(worktree) => &worktree.snapshot,
1518            Worktree::Remote(worktree) => &worktree.snapshot,
1519        }
1520    }
1521}
1522
1523impl Deref for LocalWorktree {
1524    type Target = LocalSnapshot;
1525
1526    fn deref(&self) -> &Self::Target {
1527        &self.snapshot
1528    }
1529}
1530
1531impl Deref for RemoteWorktree {
1532    type Target = Snapshot;
1533
1534    fn deref(&self) -> &Self::Target {
1535        &self.snapshot
1536    }
1537}
1538
1539impl fmt::Debug for LocalWorktree {
1540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1541        self.snapshot.fmt(f)
1542    }
1543}
1544
1545impl fmt::Debug for Snapshot {
1546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1548        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1549
1550        impl<'a> fmt::Debug for EntriesByPath<'a> {
1551            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1552                f.debug_map()
1553                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1554                    .finish()
1555            }
1556        }
1557
1558        impl<'a> fmt::Debug for EntriesById<'a> {
1559            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1560                f.debug_list().entries(self.0.iter()).finish()
1561            }
1562        }
1563
1564        f.debug_struct("Snapshot")
1565            .field("id", &self.id)
1566            .field("root_name", &self.root_name)
1567            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1568            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1569            .finish()
1570    }
1571}
1572
1573#[derive(Clone, PartialEq)]
1574pub struct File {
1575    pub worktree: ModelHandle<Worktree>,
1576    pub path: Arc<Path>,
1577    pub mtime: SystemTime,
1578    pub(crate) entry_id: Option<ProjectEntryId>,
1579    pub(crate) is_local: bool,
1580}
1581
1582impl language::File for File {
1583    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1584        if self.is_local {
1585            Some(self)
1586        } else {
1587            None
1588        }
1589    }
1590
1591    fn mtime(&self) -> SystemTime {
1592        self.mtime
1593    }
1594
1595    fn path(&self) -> &Arc<Path> {
1596        &self.path
1597    }
1598
1599    fn full_path(&self, cx: &AppContext) -> PathBuf {
1600        let mut full_path = PathBuf::new();
1601        full_path.push(self.worktree.read(cx).root_name());
1602        if self.path.components().next().is_some() {
1603            full_path.push(&self.path);
1604        }
1605        full_path
1606    }
1607
1608    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1609    /// of its worktree, then this method will return the name of the worktree itself.
1610    fn file_name(&self, cx: &AppContext) -> OsString {
1611        self.path
1612            .file_name()
1613            .map(|name| name.into())
1614            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1615    }
1616
1617    fn is_deleted(&self) -> bool {
1618        self.entry_id.is_none()
1619    }
1620
1621    fn save(
1622        &self,
1623        buffer_id: u64,
1624        text: Rope,
1625        version: clock::Global,
1626        cx: &mut MutableAppContext,
1627    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1628        self.worktree.update(cx, |worktree, cx| match worktree {
1629            Worktree::Local(worktree) => {
1630                let rpc = worktree.client.clone();
1631                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1632                let fingerprint = text.fingerprint();
1633                let save = worktree.write_file(self.path.clone(), text, cx);
1634                cx.background().spawn(async move {
1635                    let entry = save.await?;
1636                    if let Some(project_id) = project_id {
1637                        rpc.send(proto::BufferSaved {
1638                            project_id,
1639                            buffer_id,
1640                            version: serialize_version(&version),
1641                            mtime: Some(entry.mtime.into()),
1642                            fingerprint: fingerprint.clone(),
1643                        })?;
1644                    }
1645                    Ok((version, fingerprint, entry.mtime))
1646                })
1647            }
1648            Worktree::Remote(worktree) => {
1649                let rpc = worktree.client.clone();
1650                let project_id = worktree.project_id;
1651                cx.foreground().spawn(async move {
1652                    let response = rpc
1653                        .request(proto::SaveBuffer {
1654                            project_id,
1655                            buffer_id,
1656                            version: serialize_version(&version),
1657                        })
1658                        .await?;
1659                    let version = deserialize_version(response.version);
1660                    let mtime = response
1661                        .mtime
1662                        .ok_or_else(|| anyhow!("missing mtime"))?
1663                        .into();
1664                    Ok((version, response.fingerprint, mtime))
1665                })
1666            }
1667        })
1668    }
1669
1670    fn as_any(&self) -> &dyn Any {
1671        self
1672    }
1673
1674    fn to_proto(&self) -> rpc::proto::File {
1675        rpc::proto::File {
1676            worktree_id: self.worktree.id() as u64,
1677            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1678            path: self.path.to_string_lossy().into(),
1679            mtime: Some(self.mtime.into()),
1680        }
1681    }
1682}
1683
1684impl language::LocalFile for File {
1685    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1686        self.worktree
1687            .read(cx)
1688            .as_local()
1689            .unwrap()
1690            .abs_path
1691            .join(&self.path)
1692    }
1693
1694    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1695        let worktree = self.worktree.read(cx).as_local().unwrap();
1696        let abs_path = worktree.absolutize(&self.path);
1697        let fs = worktree.fs.clone();
1698        cx.background()
1699            .spawn(async move { fs.load(&abs_path).await })
1700    }
1701
1702    fn buffer_reloaded(
1703        &self,
1704        buffer_id: u64,
1705        version: &clock::Global,
1706        fingerprint: String,
1707        mtime: SystemTime,
1708        cx: &mut MutableAppContext,
1709    ) {
1710        let worktree = self.worktree.read(cx).as_local().unwrap();
1711        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1712            worktree
1713                .client
1714                .send(proto::BufferReloaded {
1715                    project_id,
1716                    buffer_id,
1717                    version: serialize_version(&version),
1718                    mtime: Some(mtime.into()),
1719                    fingerprint,
1720                })
1721                .log_err();
1722        }
1723    }
1724}
1725
1726impl File {
1727    pub fn from_proto(
1728        proto: rpc::proto::File,
1729        worktree: ModelHandle<Worktree>,
1730        cx: &AppContext,
1731    ) -> Result<Self> {
1732        let worktree_id = worktree
1733            .read(cx)
1734            .as_remote()
1735            .ok_or_else(|| anyhow!("not remote"))?
1736            .id();
1737
1738        if worktree_id.to_proto() != proto.worktree_id {
1739            return Err(anyhow!("worktree id does not match file"));
1740        }
1741
1742        Ok(Self {
1743            worktree,
1744            path: Path::new(&proto.path).into(),
1745            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1746            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1747            is_local: false,
1748        })
1749    }
1750
1751    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1752        file.and_then(|f| f.as_any().downcast_ref())
1753    }
1754
1755    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1756        self.worktree.read(cx).id()
1757    }
1758
1759    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1760        self.entry_id
1761    }
1762}
1763
1764#[derive(Clone, Debug, PartialEq, Eq)]
1765pub struct Entry {
1766    pub id: ProjectEntryId,
1767    pub kind: EntryKind,
1768    pub path: Arc<Path>,
1769    pub inode: u64,
1770    pub mtime: SystemTime,
1771    pub is_symlink: bool,
1772    pub is_ignored: bool,
1773}
1774
1775#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1776pub enum EntryKind {
1777    PendingDir,
1778    Dir,
1779    File(CharBag),
1780}
1781
1782impl Entry {
1783    fn new(
1784        path: Arc<Path>,
1785        metadata: &fs::Metadata,
1786        next_entry_id: &AtomicUsize,
1787        root_char_bag: CharBag,
1788    ) -> Self {
1789        Self {
1790            id: ProjectEntryId::new(next_entry_id),
1791            kind: if metadata.is_dir {
1792                EntryKind::PendingDir
1793            } else {
1794                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1795            },
1796            path,
1797            inode: metadata.inode,
1798            mtime: metadata.mtime,
1799            is_symlink: metadata.is_symlink,
1800            is_ignored: false,
1801        }
1802    }
1803
1804    pub fn is_dir(&self) -> bool {
1805        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1806    }
1807
1808    pub fn is_file(&self) -> bool {
1809        matches!(self.kind, EntryKind::File(_))
1810    }
1811}
1812
1813impl sum_tree::Item for Entry {
1814    type Summary = EntrySummary;
1815
1816    fn summary(&self) -> Self::Summary {
1817        let visible_count = if self.is_ignored { 0 } else { 1 };
1818        let file_count;
1819        let visible_file_count;
1820        if self.is_file() {
1821            file_count = 1;
1822            visible_file_count = visible_count;
1823        } else {
1824            file_count = 0;
1825            visible_file_count = 0;
1826        }
1827
1828        EntrySummary {
1829            max_path: self.path.clone(),
1830            count: 1,
1831            visible_count,
1832            file_count,
1833            visible_file_count,
1834        }
1835    }
1836}
1837
1838impl sum_tree::KeyedItem for Entry {
1839    type Key = PathKey;
1840
1841    fn key(&self) -> Self::Key {
1842        PathKey(self.path.clone())
1843    }
1844}
1845
1846#[derive(Clone, Debug)]
1847pub struct EntrySummary {
1848    max_path: Arc<Path>,
1849    count: usize,
1850    visible_count: usize,
1851    file_count: usize,
1852    visible_file_count: usize,
1853}
1854
1855impl Default for EntrySummary {
1856    fn default() -> Self {
1857        Self {
1858            max_path: Arc::from(Path::new("")),
1859            count: 0,
1860            visible_count: 0,
1861            file_count: 0,
1862            visible_file_count: 0,
1863        }
1864    }
1865}
1866
1867impl sum_tree::Summary for EntrySummary {
1868    type Context = ();
1869
1870    fn add_summary(&mut self, rhs: &Self, _: &()) {
1871        self.max_path = rhs.max_path.clone();
1872        self.count += rhs.count;
1873        self.visible_count += rhs.visible_count;
1874        self.file_count += rhs.file_count;
1875        self.visible_file_count += rhs.visible_file_count;
1876    }
1877}
1878
1879#[derive(Clone, Debug)]
1880struct PathEntry {
1881    id: ProjectEntryId,
1882    path: Arc<Path>,
1883    is_ignored: bool,
1884    scan_id: usize,
1885}
1886
1887impl sum_tree::Item for PathEntry {
1888    type Summary = PathEntrySummary;
1889
1890    fn summary(&self) -> Self::Summary {
1891        PathEntrySummary { max_id: self.id }
1892    }
1893}
1894
1895impl sum_tree::KeyedItem for PathEntry {
1896    type Key = ProjectEntryId;
1897
1898    fn key(&self) -> Self::Key {
1899        self.id
1900    }
1901}
1902
1903#[derive(Clone, Debug, Default)]
1904struct PathEntrySummary {
1905    max_id: ProjectEntryId,
1906}
1907
1908impl sum_tree::Summary for PathEntrySummary {
1909    type Context = ();
1910
1911    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
1912        self.max_id = summary.max_id;
1913    }
1914}
1915
1916impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
1917    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
1918        *self = summary.max_id;
1919    }
1920}
1921
1922#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
1923pub struct PathKey(Arc<Path>);
1924
1925impl Default for PathKey {
1926    fn default() -> Self {
1927        Self(Path::new("").into())
1928    }
1929}
1930
1931impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
1932    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
1933        self.0 = summary.max_path.clone();
1934    }
1935}
1936
1937struct BackgroundScanner {
1938    fs: Arc<dyn Fs>,
1939    snapshot: Arc<Mutex<LocalSnapshot>>,
1940    notify: UnboundedSender<ScanState>,
1941    executor: Arc<executor::Background>,
1942}
1943
1944impl BackgroundScanner {
1945    fn new(
1946        snapshot: Arc<Mutex<LocalSnapshot>>,
1947        notify: UnboundedSender<ScanState>,
1948        fs: Arc<dyn Fs>,
1949        executor: Arc<executor::Background>,
1950    ) -> Self {
1951        Self {
1952            fs,
1953            snapshot,
1954            notify,
1955            executor,
1956        }
1957    }
1958
1959    fn abs_path(&self) -> Arc<Path> {
1960        self.snapshot.lock().abs_path.clone()
1961    }
1962
1963    fn snapshot(&self) -> LocalSnapshot {
1964        self.snapshot.lock().clone()
1965    }
1966
1967    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
1968        if self.notify.unbounded_send(ScanState::Initializing).is_err() {
1969            return;
1970        }
1971
1972        if let Err(err) = self.scan_dirs().await {
1973            if self
1974                .notify
1975                .unbounded_send(ScanState::Err(Arc::new(err)))
1976                .is_err()
1977            {
1978                return;
1979            }
1980        }
1981
1982        if self.notify.unbounded_send(ScanState::Idle).is_err() {
1983            return;
1984        }
1985
1986        futures::pin_mut!(events_rx);
1987
1988        while let Some(mut events) = events_rx.next().await {
1989            while let Poll::Ready(Some(additional_events)) = futures::poll!(events_rx.next()) {
1990                events.extend(additional_events);
1991            }
1992
1993            if self.notify.unbounded_send(ScanState::Updating).is_err() {
1994                break;
1995            }
1996
1997            if !self.process_events(events).await {
1998                break;
1999            }
2000
2001            if self.notify.unbounded_send(ScanState::Idle).is_err() {
2002                break;
2003            }
2004        }
2005    }
2006
2007    async fn scan_dirs(&mut self) -> Result<()> {
2008        let root_char_bag;
2009        let next_entry_id;
2010        let is_dir;
2011        {
2012            let snapshot = self.snapshot.lock();
2013            root_char_bag = snapshot.root_char_bag;
2014            next_entry_id = snapshot.next_entry_id.clone();
2015            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2016        };
2017
2018        if is_dir {
2019            let path: Arc<Path> = Arc::from(Path::new(""));
2020            let abs_path = self.abs_path();
2021            let (tx, rx) = channel::unbounded();
2022            self.executor
2023                .block(tx.send(ScanJob {
2024                    abs_path: abs_path.to_path_buf(),
2025                    path,
2026                    ignore_stack: IgnoreStack::none(),
2027                    scan_queue: tx.clone(),
2028                }))
2029                .unwrap();
2030            drop(tx);
2031
2032            self.executor
2033                .scoped(|scope| {
2034                    for _ in 0..self.executor.num_cpus() {
2035                        scope.spawn(async {
2036                            while let Ok(job) = rx.recv().await {
2037                                if let Err(err) = self
2038                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2039                                    .await
2040                                {
2041                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2042                                }
2043                            }
2044                        });
2045                    }
2046                })
2047                .await;
2048        }
2049
2050        Ok(())
2051    }
2052
2053    async fn scan_dir(
2054        &self,
2055        root_char_bag: CharBag,
2056        next_entry_id: Arc<AtomicUsize>,
2057        job: &ScanJob,
2058    ) -> Result<()> {
2059        let mut new_entries: Vec<Entry> = Vec::new();
2060        let mut new_jobs: Vec<ScanJob> = Vec::new();
2061        let mut ignore_stack = job.ignore_stack.clone();
2062        let mut new_ignore = None;
2063
2064        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2065        while let Some(child_abs_path) = child_paths.next().await {
2066            let child_abs_path = match child_abs_path {
2067                Ok(child_abs_path) => child_abs_path,
2068                Err(error) => {
2069                    log::error!("error processing entry {:?}", error);
2070                    continue;
2071                }
2072            };
2073            let child_name = child_abs_path.file_name().unwrap();
2074            let child_path: Arc<Path> = job.path.join(child_name).into();
2075            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2076                Ok(Some(metadata)) => metadata,
2077                Ok(None) => continue,
2078                Err(err) => {
2079                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2080                    continue;
2081                }
2082            };
2083
2084            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2085            if child_name == *GITIGNORE {
2086                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2087                    Ok(ignore) => {
2088                        let ignore = Arc::new(ignore);
2089                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2090                        new_ignore = Some(ignore);
2091                    }
2092                    Err(error) => {
2093                        log::error!(
2094                            "error loading .gitignore file {:?} - {:?}",
2095                            child_name,
2096                            error
2097                        );
2098                    }
2099                }
2100
2101                // Update ignore status of any child entries we've already processed to reflect the
2102                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2103                // there should rarely be too numerous. Update the ignore stack associated with any
2104                // new jobs as well.
2105                let mut new_jobs = new_jobs.iter_mut();
2106                for entry in &mut new_entries {
2107                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2108                    if entry.is_dir() {
2109                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2110                            IgnoreStack::all()
2111                        } else {
2112                            ignore_stack.clone()
2113                        };
2114                    }
2115                }
2116            }
2117
2118            let mut child_entry = Entry::new(
2119                child_path.clone(),
2120                &child_metadata,
2121                &next_entry_id,
2122                root_char_bag,
2123            );
2124
2125            if child_metadata.is_dir {
2126                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2127                child_entry.is_ignored = is_ignored;
2128                new_entries.push(child_entry);
2129                new_jobs.push(ScanJob {
2130                    abs_path: child_abs_path,
2131                    path: child_path,
2132                    ignore_stack: if is_ignored {
2133                        IgnoreStack::all()
2134                    } else {
2135                        ignore_stack.clone()
2136                    },
2137                    scan_queue: job.scan_queue.clone(),
2138                });
2139            } else {
2140                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2141                new_entries.push(child_entry);
2142            };
2143        }
2144
2145        self.snapshot
2146            .lock()
2147            .populate_dir(job.path.clone(), new_entries, new_ignore);
2148        for new_job in new_jobs {
2149            job.scan_queue.send(new_job).await.unwrap();
2150        }
2151
2152        Ok(())
2153    }
2154
2155    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2156        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2157        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2158
2159        let root_char_bag;
2160        let root_abs_path;
2161        let next_entry_id;
2162        {
2163            let snapshot = self.snapshot.lock();
2164            root_char_bag = snapshot.root_char_bag;
2165            root_abs_path = snapshot.abs_path.clone();
2166            next_entry_id = snapshot.next_entry_id.clone();
2167        }
2168
2169        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2170            abs_path
2171        } else {
2172            return false;
2173        };
2174        let metadata = futures::future::join_all(
2175            events
2176                .iter()
2177                .map(|event| self.fs.metadata(&event.path))
2178                .collect::<Vec<_>>(),
2179        )
2180        .await;
2181
2182        // Hold the snapshot lock while clearing and re-inserting the root entries
2183        // for each event. This way, the snapshot is not observable to the foreground
2184        // thread while this operation is in-progress.
2185        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2186        {
2187            let mut snapshot = self.snapshot.lock();
2188            snapshot.scan_id += 1;
2189            for event in &events {
2190                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2191                    snapshot.remove_path(&path);
2192                }
2193            }
2194
2195            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2196                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2197                    Ok(path) => Arc::from(path.to_path_buf()),
2198                    Err(_) => {
2199                        log::error!(
2200                            "unexpected event {:?} for root path {:?}",
2201                            event.path,
2202                            root_abs_path
2203                        );
2204                        continue;
2205                    }
2206                };
2207
2208                match metadata {
2209                    Ok(Some(metadata)) => {
2210                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2211                        let mut fs_entry = Entry::new(
2212                            path.clone(),
2213                            &metadata,
2214                            snapshot.next_entry_id.as_ref(),
2215                            snapshot.root_char_bag,
2216                        );
2217                        fs_entry.is_ignored = ignore_stack.is_all();
2218                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2219                        if metadata.is_dir {
2220                            self.executor
2221                                .block(scan_queue_tx.send(ScanJob {
2222                                    abs_path: event.path,
2223                                    path,
2224                                    ignore_stack,
2225                                    scan_queue: scan_queue_tx.clone(),
2226                                }))
2227                                .unwrap();
2228                        }
2229                    }
2230                    Ok(None) => {}
2231                    Err(err) => {
2232                        // TODO - create a special 'error' entry in the entries tree to mark this
2233                        log::error!("error reading file on event {:?}", err);
2234                    }
2235                }
2236            }
2237            drop(scan_queue_tx);
2238        }
2239
2240        // Scan any directories that were created as part of this event batch.
2241        self.executor
2242            .scoped(|scope| {
2243                for _ in 0..self.executor.num_cpus() {
2244                    scope.spawn(async {
2245                        while let Ok(job) = scan_queue_rx.recv().await {
2246                            if let Err(err) = self
2247                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2248                                .await
2249                            {
2250                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2251                            }
2252                        }
2253                    });
2254                }
2255            })
2256            .await;
2257
2258        // Attempt to detect renames only over a single batch of file-system events.
2259        self.snapshot.lock().removed_entry_ids.clear();
2260
2261        self.update_ignore_statuses().await;
2262        true
2263    }
2264
2265    async fn update_ignore_statuses(&self) {
2266        let mut snapshot = self.snapshot();
2267
2268        let mut ignores_to_update = Vec::new();
2269        let mut ignores_to_delete = Vec::new();
2270        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2271            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2272                ignores_to_update.push(parent_path.clone());
2273            }
2274
2275            let ignore_path = parent_path.join(&*GITIGNORE);
2276            if snapshot.entry_for_path(ignore_path).is_none() {
2277                ignores_to_delete.push(parent_path.clone());
2278            }
2279        }
2280
2281        for parent_path in ignores_to_delete {
2282            snapshot.ignores.remove(&parent_path);
2283            self.snapshot.lock().ignores.remove(&parent_path);
2284        }
2285
2286        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2287        ignores_to_update.sort_unstable();
2288        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2289        while let Some(parent_path) = ignores_to_update.next() {
2290            while ignores_to_update
2291                .peek()
2292                .map_or(false, |p| p.starts_with(&parent_path))
2293            {
2294                ignores_to_update.next().unwrap();
2295            }
2296
2297            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2298            ignore_queue_tx
2299                .send(UpdateIgnoreStatusJob {
2300                    path: parent_path,
2301                    ignore_stack,
2302                    ignore_queue: ignore_queue_tx.clone(),
2303                })
2304                .await
2305                .unwrap();
2306        }
2307        drop(ignore_queue_tx);
2308
2309        self.executor
2310            .scoped(|scope| {
2311                for _ in 0..self.executor.num_cpus() {
2312                    scope.spawn(async {
2313                        while let Ok(job) = ignore_queue_rx.recv().await {
2314                            self.update_ignore_status(job, &snapshot).await;
2315                        }
2316                    });
2317                }
2318            })
2319            .await;
2320    }
2321
2322    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2323        let mut ignore_stack = job.ignore_stack;
2324        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2325            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2326        }
2327
2328        let mut entries_by_id_edits = Vec::new();
2329        let mut entries_by_path_edits = Vec::new();
2330        for mut entry in snapshot.child_entries(&job.path).cloned() {
2331            let was_ignored = entry.is_ignored;
2332            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2333            if entry.is_dir() {
2334                let child_ignore_stack = if entry.is_ignored {
2335                    IgnoreStack::all()
2336                } else {
2337                    ignore_stack.clone()
2338                };
2339                job.ignore_queue
2340                    .send(UpdateIgnoreStatusJob {
2341                        path: entry.path.clone(),
2342                        ignore_stack: child_ignore_stack,
2343                        ignore_queue: job.ignore_queue.clone(),
2344                    })
2345                    .await
2346                    .unwrap();
2347            }
2348
2349            if entry.is_ignored != was_ignored {
2350                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2351                path_entry.scan_id = snapshot.scan_id;
2352                path_entry.is_ignored = entry.is_ignored;
2353                entries_by_id_edits.push(Edit::Insert(path_entry));
2354                entries_by_path_edits.push(Edit::Insert(entry));
2355            }
2356        }
2357
2358        let mut snapshot = self.snapshot.lock();
2359        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2360        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2361    }
2362}
2363
2364fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2365    let mut result = root_char_bag;
2366    result.extend(
2367        path.to_string_lossy()
2368            .chars()
2369            .map(|c| c.to_ascii_lowercase()),
2370    );
2371    result
2372}
2373
2374struct ScanJob {
2375    abs_path: PathBuf,
2376    path: Arc<Path>,
2377    ignore_stack: Arc<IgnoreStack>,
2378    scan_queue: Sender<ScanJob>,
2379}
2380
2381struct UpdateIgnoreStatusJob {
2382    path: Arc<Path>,
2383    ignore_stack: Arc<IgnoreStack>,
2384    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2385}
2386
2387pub trait WorktreeHandle {
2388    #[cfg(any(test, feature = "test-support"))]
2389    fn flush_fs_events<'a>(
2390        &self,
2391        cx: &'a gpui::TestAppContext,
2392    ) -> futures::future::LocalBoxFuture<'a, ()>;
2393}
2394
2395impl WorktreeHandle for ModelHandle<Worktree> {
2396    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2397    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2398    // extra directory scans, and emit extra scan-state notifications.
2399    //
2400    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2401    // to ensure that all redundant FS events have already been processed.
2402    #[cfg(any(test, feature = "test-support"))]
2403    fn flush_fs_events<'a>(
2404        &self,
2405        cx: &'a gpui::TestAppContext,
2406    ) -> futures::future::LocalBoxFuture<'a, ()> {
2407        use smol::future::FutureExt;
2408
2409        let filename = "fs-event-sentinel";
2410        let tree = self.clone();
2411        let (fs, root_path) = self.read_with(cx, |tree, _| {
2412            let tree = tree.as_local().unwrap();
2413            (tree.fs.clone(), tree.abs_path().clone())
2414        });
2415
2416        async move {
2417            fs.create_file(&root_path.join(filename), Default::default())
2418                .await
2419                .unwrap();
2420            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2421                .await;
2422
2423            fs.remove_file(&root_path.join(filename), Default::default())
2424                .await
2425                .unwrap();
2426            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2427                .await;
2428
2429            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2430                .await;
2431        }
2432        .boxed_local()
2433    }
2434}
2435
2436#[derive(Clone, Debug)]
2437struct TraversalProgress<'a> {
2438    max_path: &'a Path,
2439    count: usize,
2440    visible_count: usize,
2441    file_count: usize,
2442    visible_file_count: usize,
2443}
2444
2445impl<'a> TraversalProgress<'a> {
2446    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2447        match (include_ignored, include_dirs) {
2448            (true, true) => self.count,
2449            (true, false) => self.file_count,
2450            (false, true) => self.visible_count,
2451            (false, false) => self.visible_file_count,
2452        }
2453    }
2454}
2455
2456impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2457    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2458        self.max_path = summary.max_path.as_ref();
2459        self.count += summary.count;
2460        self.visible_count += summary.visible_count;
2461        self.file_count += summary.file_count;
2462        self.visible_file_count += summary.visible_file_count;
2463    }
2464}
2465
2466impl<'a> Default for TraversalProgress<'a> {
2467    fn default() -> Self {
2468        Self {
2469            max_path: Path::new(""),
2470            count: 0,
2471            visible_count: 0,
2472            file_count: 0,
2473            visible_file_count: 0,
2474        }
2475    }
2476}
2477
2478pub struct Traversal<'a> {
2479    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2480    include_ignored: bool,
2481    include_dirs: bool,
2482}
2483
2484impl<'a> Traversal<'a> {
2485    pub fn advance(&mut self) -> bool {
2486        self.advance_to_offset(self.offset() + 1)
2487    }
2488
2489    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2490        self.cursor.seek_forward(
2491            &TraversalTarget::Count {
2492                count: offset,
2493                include_dirs: self.include_dirs,
2494                include_ignored: self.include_ignored,
2495            },
2496            Bias::Right,
2497            &(),
2498        )
2499    }
2500
2501    pub fn advance_to_sibling(&mut self) -> bool {
2502        while let Some(entry) = self.cursor.item() {
2503            self.cursor.seek_forward(
2504                &TraversalTarget::PathSuccessor(&entry.path),
2505                Bias::Left,
2506                &(),
2507            );
2508            if let Some(entry) = self.cursor.item() {
2509                if (self.include_dirs || !entry.is_dir())
2510                    && (self.include_ignored || !entry.is_ignored)
2511                {
2512                    return true;
2513                }
2514            }
2515        }
2516        false
2517    }
2518
2519    pub fn entry(&self) -> Option<&'a Entry> {
2520        self.cursor.item()
2521    }
2522
2523    pub fn offset(&self) -> usize {
2524        self.cursor
2525            .start()
2526            .count(self.include_dirs, self.include_ignored)
2527    }
2528}
2529
2530impl<'a> Iterator for Traversal<'a> {
2531    type Item = &'a Entry;
2532
2533    fn next(&mut self) -> Option<Self::Item> {
2534        if let Some(item) = self.entry() {
2535            self.advance();
2536            Some(item)
2537        } else {
2538            None
2539        }
2540    }
2541}
2542
2543#[derive(Debug)]
2544enum TraversalTarget<'a> {
2545    Path(&'a Path),
2546    PathSuccessor(&'a Path),
2547    Count {
2548        count: usize,
2549        include_ignored: bool,
2550        include_dirs: bool,
2551    },
2552}
2553
2554impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2555    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2556        match self {
2557            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2558            TraversalTarget::PathSuccessor(path) => {
2559                if !cursor_location.max_path.starts_with(path) {
2560                    Ordering::Equal
2561                } else {
2562                    Ordering::Greater
2563                }
2564            }
2565            TraversalTarget::Count {
2566                count,
2567                include_dirs,
2568                include_ignored,
2569            } => Ord::cmp(
2570                count,
2571                &cursor_location.count(*include_dirs, *include_ignored),
2572            ),
2573        }
2574    }
2575}
2576
2577struct ChildEntriesIter<'a> {
2578    parent_path: &'a Path,
2579    traversal: Traversal<'a>,
2580}
2581
2582impl<'a> Iterator for ChildEntriesIter<'a> {
2583    type Item = &'a Entry;
2584
2585    fn next(&mut self) -> Option<Self::Item> {
2586        if let Some(item) = self.traversal.entry() {
2587            if item.path.starts_with(&self.parent_path) {
2588                self.traversal.advance_to_sibling();
2589                return Some(item);
2590            }
2591        }
2592        None
2593    }
2594}
2595
2596impl<'a> From<&'a Entry> for proto::Entry {
2597    fn from(entry: &'a Entry) -> Self {
2598        Self {
2599            id: entry.id.to_proto(),
2600            is_dir: entry.is_dir(),
2601            path: entry.path.as_os_str().as_bytes().to_vec(),
2602            inode: entry.inode,
2603            mtime: Some(entry.mtime.into()),
2604            is_symlink: entry.is_symlink,
2605            is_ignored: entry.is_ignored,
2606        }
2607    }
2608}
2609
2610impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2611    type Error = anyhow::Error;
2612
2613    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2614        if let Some(mtime) = entry.mtime {
2615            let kind = if entry.is_dir {
2616                EntryKind::Dir
2617            } else {
2618                let mut char_bag = root_char_bag.clone();
2619                char_bag.extend(
2620                    String::from_utf8_lossy(&entry.path)
2621                        .chars()
2622                        .map(|c| c.to_ascii_lowercase()),
2623                );
2624                EntryKind::File(char_bag)
2625            };
2626            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2627            Ok(Entry {
2628                id: ProjectEntryId::from_proto(entry.id),
2629                kind,
2630                path: path.clone(),
2631                inode: entry.inode,
2632                mtime: mtime.into(),
2633                is_symlink: entry.is_symlink,
2634                is_ignored: entry.is_ignored,
2635            })
2636        } else {
2637            Err(anyhow!(
2638                "missing mtime in remote worktree entry {:?}",
2639                entry.path
2640            ))
2641        }
2642    }
2643}
2644
2645async fn send_worktree_update(client: &Arc<Client>, update: proto::UpdateWorktree) -> Result<()> {
2646    #[cfg(any(test, feature = "test-support"))]
2647    const MAX_CHUNK_SIZE: usize = 2;
2648    #[cfg(not(any(test, feature = "test-support")))]
2649    const MAX_CHUNK_SIZE: usize = 256;
2650
2651    for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
2652        client.request(update).await?;
2653    }
2654
2655    Ok(())
2656}
2657
2658#[cfg(test)]
2659mod tests {
2660    use super::*;
2661    use crate::fs::FakeFs;
2662    use anyhow::Result;
2663    use client::test::FakeHttpClient;
2664    use fs::RealFs;
2665    use gpui::TestAppContext;
2666    use rand::prelude::*;
2667    use serde_json::json;
2668    use std::{
2669        env,
2670        fmt::Write,
2671        time::{SystemTime, UNIX_EPOCH},
2672    };
2673    use util::test::temp_tree;
2674
2675    #[gpui::test]
2676    async fn test_traversal(cx: &mut TestAppContext) {
2677        let fs = FakeFs::new(cx.background());
2678        fs.insert_tree(
2679            "/root",
2680            json!({
2681               ".gitignore": "a/b\n",
2682               "a": {
2683                   "b": "",
2684                   "c": "",
2685               }
2686            }),
2687        )
2688        .await;
2689
2690        let http_client = FakeHttpClient::with_404_response();
2691        let client = Client::new(http_client);
2692
2693        let tree = Worktree::local(
2694            client,
2695            Arc::from(Path::new("/root")),
2696            true,
2697            fs,
2698            Default::default(),
2699            &mut cx.to_async(),
2700        )
2701        .await
2702        .unwrap();
2703        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2704            .await;
2705
2706        tree.read_with(cx, |tree, _| {
2707            assert_eq!(
2708                tree.entries(false)
2709                    .map(|entry| entry.path.as_ref())
2710                    .collect::<Vec<_>>(),
2711                vec![
2712                    Path::new(""),
2713                    Path::new(".gitignore"),
2714                    Path::new("a"),
2715                    Path::new("a/c"),
2716                ]
2717            );
2718            assert_eq!(
2719                tree.entries(true)
2720                    .map(|entry| entry.path.as_ref())
2721                    .collect::<Vec<_>>(),
2722                vec![
2723                    Path::new(""),
2724                    Path::new(".gitignore"),
2725                    Path::new("a"),
2726                    Path::new("a/b"),
2727                    Path::new("a/c"),
2728                ]
2729            );
2730        })
2731    }
2732
2733    #[gpui::test]
2734    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
2735        let dir = temp_tree(json!({
2736            ".git": {},
2737            ".gitignore": "ignored-dir\n",
2738            "tracked-dir": {
2739                "tracked-file1": "tracked contents",
2740            },
2741            "ignored-dir": {
2742                "ignored-file1": "ignored contents",
2743            }
2744        }));
2745
2746        let http_client = FakeHttpClient::with_404_response();
2747        let client = Client::new(http_client.clone());
2748
2749        let tree = Worktree::local(
2750            client,
2751            dir.path(),
2752            true,
2753            Arc::new(RealFs),
2754            Default::default(),
2755            &mut cx.to_async(),
2756        )
2757        .await
2758        .unwrap();
2759        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2760            .await;
2761        tree.flush_fs_events(&cx).await;
2762        cx.read(|cx| {
2763            let tree = tree.read(cx);
2764            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2765            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2766            assert_eq!(tracked.is_ignored, false);
2767            assert_eq!(ignored.is_ignored, true);
2768        });
2769
2770        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2771        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2772        tree.flush_fs_events(&cx).await;
2773        cx.read(|cx| {
2774            let tree = tree.read(cx);
2775            let dot_git = tree.entry_for_path(".git").unwrap();
2776            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2777            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2778            assert_eq!(tracked.is_ignored, false);
2779            assert_eq!(ignored.is_ignored, true);
2780            assert_eq!(dot_git.is_ignored, true);
2781        });
2782    }
2783
2784    #[gpui::test]
2785    async fn test_write_file(cx: &mut TestAppContext) {
2786        let dir = temp_tree(json!({
2787            ".git": {},
2788            ".gitignore": "ignored-dir\n",
2789            "tracked-dir": {},
2790            "ignored-dir": {}
2791        }));
2792
2793        let http_client = FakeHttpClient::with_404_response();
2794        let client = Client::new(http_client.clone());
2795
2796        let tree = Worktree::local(
2797            client,
2798            dir.path(),
2799            true,
2800            Arc::new(RealFs),
2801            Default::default(),
2802            &mut cx.to_async(),
2803        )
2804        .await
2805        .unwrap();
2806        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2807            .await;
2808        tree.flush_fs_events(&cx).await;
2809
2810        tree.update(cx, |tree, cx| {
2811            tree.as_local().unwrap().write_file(
2812                Path::new("tracked-dir/file.txt"),
2813                "hello".into(),
2814                cx,
2815            )
2816        })
2817        .await
2818        .unwrap();
2819        tree.update(cx, |tree, cx| {
2820            tree.as_local().unwrap().write_file(
2821                Path::new("ignored-dir/file.txt"),
2822                "world".into(),
2823                cx,
2824            )
2825        })
2826        .await
2827        .unwrap();
2828
2829        tree.read_with(cx, |tree, _| {
2830            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
2831            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
2832            assert_eq!(tracked.is_ignored, false);
2833            assert_eq!(ignored.is_ignored, true);
2834        });
2835    }
2836
2837    #[gpui::test(iterations = 100)]
2838    fn test_random(mut rng: StdRng) {
2839        let operations = env::var("OPERATIONS")
2840            .map(|o| o.parse().unwrap())
2841            .unwrap_or(40);
2842        let initial_entries = env::var("INITIAL_ENTRIES")
2843            .map(|o| o.parse().unwrap())
2844            .unwrap_or(20);
2845
2846        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2847        for _ in 0..initial_entries {
2848            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2849        }
2850        log::info!("Generated initial tree");
2851
2852        let (notify_tx, _notify_rx) = mpsc::unbounded();
2853        let fs = Arc::new(RealFs);
2854        let next_entry_id = Arc::new(AtomicUsize::new(0));
2855        let mut initial_snapshot = LocalSnapshot {
2856            abs_path: root_dir.path().into(),
2857            removed_entry_ids: Default::default(),
2858            ignores: Default::default(),
2859            next_entry_id: next_entry_id.clone(),
2860            snapshot: Snapshot {
2861                id: WorktreeId::from_usize(0),
2862                entries_by_path: Default::default(),
2863                entries_by_id: Default::default(),
2864                root_name: Default::default(),
2865                root_char_bag: Default::default(),
2866                scan_id: 0,
2867                is_complete: true,
2868            },
2869        };
2870        initial_snapshot.insert_entry(
2871            Entry::new(
2872                Path::new("").into(),
2873                &smol::block_on(fs.metadata(root_dir.path()))
2874                    .unwrap()
2875                    .unwrap(),
2876                &next_entry_id,
2877                Default::default(),
2878            ),
2879            fs.as_ref(),
2880        );
2881        let mut scanner = BackgroundScanner::new(
2882            Arc::new(Mutex::new(initial_snapshot.clone())),
2883            notify_tx,
2884            fs.clone(),
2885            Arc::new(gpui::executor::Background::new()),
2886        );
2887        smol::block_on(scanner.scan_dirs()).unwrap();
2888        scanner.snapshot().check_invariants();
2889
2890        let mut events = Vec::new();
2891        let mut snapshots = Vec::new();
2892        let mut mutations_len = operations;
2893        while mutations_len > 1 {
2894            if !events.is_empty() && rng.gen_bool(0.4) {
2895                let len = rng.gen_range(0..=events.len());
2896                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2897                log::info!("Delivering events: {:#?}", to_deliver);
2898                smol::block_on(scanner.process_events(to_deliver));
2899                scanner.snapshot().check_invariants();
2900            } else {
2901                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2902                mutations_len -= 1;
2903            }
2904
2905            if rng.gen_bool(0.2) {
2906                snapshots.push(scanner.snapshot());
2907            }
2908        }
2909        log::info!("Quiescing: {:#?}", events);
2910        smol::block_on(scanner.process_events(events));
2911        scanner.snapshot().check_invariants();
2912
2913        let (notify_tx, _notify_rx) = mpsc::unbounded();
2914        let mut new_scanner = BackgroundScanner::new(
2915            Arc::new(Mutex::new(initial_snapshot)),
2916            notify_tx,
2917            scanner.fs.clone(),
2918            scanner.executor.clone(),
2919        );
2920        smol::block_on(new_scanner.scan_dirs()).unwrap();
2921        assert_eq!(
2922            scanner.snapshot().to_vec(true),
2923            new_scanner.snapshot().to_vec(true)
2924        );
2925
2926        for mut prev_snapshot in snapshots {
2927            let include_ignored = rng.gen::<bool>();
2928            if !include_ignored {
2929                let mut entries_by_path_edits = Vec::new();
2930                let mut entries_by_id_edits = Vec::new();
2931                for entry in prev_snapshot
2932                    .entries_by_id
2933                    .cursor::<()>()
2934                    .filter(|e| e.is_ignored)
2935                {
2936                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2937                    entries_by_id_edits.push(Edit::Remove(entry.id));
2938                }
2939
2940                prev_snapshot
2941                    .entries_by_path
2942                    .edit(entries_by_path_edits, &());
2943                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2944            }
2945
2946            let update = scanner
2947                .snapshot()
2948                .build_update(&prev_snapshot, 0, 0, include_ignored);
2949            prev_snapshot.apply_remote_update(update).unwrap();
2950            assert_eq!(
2951                prev_snapshot.to_vec(true),
2952                scanner.snapshot().to_vec(include_ignored)
2953            );
2954        }
2955    }
2956
2957    fn randomly_mutate_tree(
2958        root_path: &Path,
2959        insertion_probability: f64,
2960        rng: &mut impl Rng,
2961    ) -> Result<Vec<fsevent::Event>> {
2962        let root_path = root_path.canonicalize().unwrap();
2963        let (dirs, files) = read_dir_recursive(root_path.clone());
2964
2965        let mut events = Vec::new();
2966        let mut record_event = |path: PathBuf| {
2967            events.push(fsevent::Event {
2968                event_id: SystemTime::now()
2969                    .duration_since(UNIX_EPOCH)
2970                    .unwrap()
2971                    .as_secs(),
2972                flags: fsevent::StreamFlags::empty(),
2973                path,
2974            });
2975        };
2976
2977        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2978            let path = dirs.choose(rng).unwrap();
2979            let new_path = path.join(gen_name(rng));
2980
2981            if rng.gen() {
2982                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2983                std::fs::create_dir(&new_path)?;
2984            } else {
2985                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2986                std::fs::write(&new_path, "")?;
2987            }
2988            record_event(new_path);
2989        } else if rng.gen_bool(0.05) {
2990            let ignore_dir_path = dirs.choose(rng).unwrap();
2991            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2992
2993            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2994            let files_to_ignore = {
2995                let len = rng.gen_range(0..=subfiles.len());
2996                subfiles.choose_multiple(rng, len)
2997            };
2998            let dirs_to_ignore = {
2999                let len = rng.gen_range(0..subdirs.len());
3000                subdirs.choose_multiple(rng, len)
3001            };
3002
3003            let mut ignore_contents = String::new();
3004            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3005                write!(
3006                    ignore_contents,
3007                    "{}\n",
3008                    path_to_ignore
3009                        .strip_prefix(&ignore_dir_path)?
3010                        .to_str()
3011                        .unwrap()
3012                )
3013                .unwrap();
3014            }
3015            log::info!(
3016                "Creating {:?} with contents:\n{}",
3017                ignore_path.strip_prefix(&root_path)?,
3018                ignore_contents
3019            );
3020            std::fs::write(&ignore_path, ignore_contents).unwrap();
3021            record_event(ignore_path);
3022        } else {
3023            let old_path = {
3024                let file_path = files.choose(rng);
3025                let dir_path = dirs[1..].choose(rng);
3026                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3027            };
3028
3029            let is_rename = rng.gen();
3030            if is_rename {
3031                let new_path_parent = dirs
3032                    .iter()
3033                    .filter(|d| !d.starts_with(old_path))
3034                    .choose(rng)
3035                    .unwrap();
3036
3037                let overwrite_existing_dir =
3038                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3039                let new_path = if overwrite_existing_dir {
3040                    std::fs::remove_dir_all(&new_path_parent).ok();
3041                    new_path_parent.to_path_buf()
3042                } else {
3043                    new_path_parent.join(gen_name(rng))
3044                };
3045
3046                log::info!(
3047                    "Renaming {:?} to {}{:?}",
3048                    old_path.strip_prefix(&root_path)?,
3049                    if overwrite_existing_dir {
3050                        "overwrite "
3051                    } else {
3052                        ""
3053                    },
3054                    new_path.strip_prefix(&root_path)?
3055                );
3056                std::fs::rename(&old_path, &new_path)?;
3057                record_event(old_path.clone());
3058                record_event(new_path);
3059            } else if old_path.is_dir() {
3060                let (dirs, files) = read_dir_recursive(old_path.clone());
3061
3062                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3063                std::fs::remove_dir_all(&old_path).unwrap();
3064                for file in files {
3065                    record_event(file);
3066                }
3067                for dir in dirs {
3068                    record_event(dir);
3069                }
3070            } else {
3071                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3072                std::fs::remove_file(old_path).unwrap();
3073                record_event(old_path.clone());
3074            }
3075        }
3076
3077        Ok(events)
3078    }
3079
3080    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3081        let child_entries = std::fs::read_dir(&path).unwrap();
3082        let mut dirs = vec![path];
3083        let mut files = Vec::new();
3084        for child_entry in child_entries {
3085            let child_path = child_entry.unwrap().path();
3086            if child_path.is_dir() {
3087                let (child_dirs, child_files) = read_dir_recursive(child_path);
3088                dirs.extend(child_dirs);
3089                files.extend(child_files);
3090            } else {
3091                files.push(child_path);
3092            }
3093        }
3094        (dirs, files)
3095    }
3096
3097    fn gen_name(rng: &mut impl Rng) -> String {
3098        (0..6)
3099            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3100            .map(char::from)
3101            .collect()
3102    }
3103
3104    impl LocalSnapshot {
3105        fn check_invariants(&self) {
3106            let mut files = self.files(true, 0);
3107            let mut visible_files = self.files(false, 0);
3108            for entry in self.entries_by_path.cursor::<()>() {
3109                if entry.is_file() {
3110                    assert_eq!(files.next().unwrap().inode, entry.inode);
3111                    if !entry.is_ignored {
3112                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3113                    }
3114                }
3115            }
3116            assert!(files.next().is_none());
3117            assert!(visible_files.next().is_none());
3118
3119            let mut bfs_paths = Vec::new();
3120            let mut stack = vec![Path::new("")];
3121            while let Some(path) = stack.pop() {
3122                bfs_paths.push(path);
3123                let ix = stack.len();
3124                for child_entry in self.child_entries(path) {
3125                    stack.insert(ix, &child_entry.path);
3126                }
3127            }
3128
3129            let dfs_paths_via_iter = self
3130                .entries_by_path
3131                .cursor::<()>()
3132                .map(|e| e.path.as_ref())
3133                .collect::<Vec<_>>();
3134            assert_eq!(bfs_paths, dfs_paths_via_iter);
3135
3136            let dfs_paths_via_traversal = self
3137                .entries(true)
3138                .map(|e| e.path.as_ref())
3139                .collect::<Vec<_>>();
3140            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3141
3142            for (ignore_parent_path, _) in &self.ignores {
3143                assert!(self.entry_for_path(ignore_parent_path).is_some());
3144                assert!(self
3145                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3146                    .is_some());
3147            }
3148        }
3149
3150        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3151            let mut paths = Vec::new();
3152            for entry in self.entries_by_path.cursor::<()>() {
3153                if include_ignored || !entry.is_ignored {
3154                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3155                }
3156            }
3157            paths.sort_by(|a, b| a.0.cmp(&b.0));
3158            paths
3159        }
3160    }
3161}