worktree.rs

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