worktree.rs

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