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