worktree.rs

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