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