worktree.rs

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