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