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