worktree.rs

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