worktree.rs

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