worktree.rs

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