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